From 97fcdeb73eb437dd261d523b498c270b81851917 Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Thu, 19 Nov 2026 17:02:49 +0800 Subject: [PATCH 1/2] Replace DRIT.Drawing with owned metafile rendering Switch portable conversion to managed EMF and WMF rendering, resolve real font faces, preserve cropping, and remove incorporated Drawing sources and package notices. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/MiniPdf/DocxReader.cs | 31 +- src/MiniPdf/Drawing/Brushes/Brush.cs | 53 - src/MiniPdf/Drawing/Brushes/Brushes.cs | 727 ------ src/MiniPdf/Drawing/Brushes/SolidBrush.cs | 48 - src/MiniPdf/Drawing/Brushes/TextureBrush.cs | 139 -- src/MiniPdf/Drawing/Codecs/BmpCodec.cs | 129 - src/MiniPdf/Drawing/Codecs/CodecRegistry.cs | 86 - src/MiniPdf/Drawing/Codecs/EmfCodec.cs | 39 - src/MiniPdf/Drawing/Codecs/GifCodec.cs | 468 ---- src/MiniPdf/Drawing/Codecs/IImageCodec.cs | 22 - src/MiniPdf/Drawing/Codecs/IcoCodec.cs | 129 - .../Drawing/Codecs/Jpeg/CoefficientBuffer.cs | 78 - .../Drawing/Codecs/Jpeg/ColorConverter.cs | 31 - .../Drawing/Codecs/Jpeg/EntropyDecoder.cs | 267 --- src/MiniPdf/Drawing/Codecs/Jpeg/ExifReader.cs | 78 - src/MiniPdf/Drawing/Codecs/Jpeg/ForwardDct.cs | 50 - .../Drawing/Codecs/Jpeg/FrameComponent.cs | 21 - .../Drawing/Codecs/Jpeg/FrameHeader.cs | 82 - .../Drawing/Codecs/Jpeg/HuffmanEncoder.cs | 225 -- .../Drawing/Codecs/Jpeg/HuffmanTable.cs | 141 -- .../Drawing/Codecs/Jpeg/IdctTransform.cs | 53 - src/MiniPdf/Drawing/Codecs/Jpeg/JfifHeader.cs | 58 - .../Drawing/Codecs/Jpeg/JpegDecoder.cs | 250 -- .../Drawing/Codecs/Jpeg/JpegEncoder.cs | 143 -- src/MiniPdf/Drawing/Codecs/Jpeg/JpegMarker.cs | 59 - src/MiniPdf/Drawing/Codecs/Jpeg/JpegReader.cs | 237 -- src/MiniPdf/Drawing/Codecs/Jpeg/JpegWriter.cs | 146 -- .../Drawing/Codecs/Jpeg/ProgressiveDecoder.cs | 489 ---- .../Drawing/Codecs/Jpeg/QuantizationTable.cs | 65 - src/MiniPdf/Drawing/Codecs/Jpeg/Quantizer.cs | 80 - .../Drawing/Codecs/Jpeg/ScanComponent.cs | 17 - src/MiniPdf/Drawing/Codecs/Jpeg/ScanHeader.cs | 62 - .../Drawing/Codecs/Jpeg/UpsampleBuffer.cs | 44 - src/MiniPdf/Drawing/Codecs/JpegCodec.cs | 33 - .../Drawing/Codecs/Png/ApngChunkData.cs | 86 - .../Drawing/Codecs/Png/ApngFrameBuilder.cs | 44 - src/MiniPdf/Drawing/Codecs/Png/PngHelpers.cs | 230 -- src/MiniPdf/Drawing/Codecs/PngCodec.cs | 317 --- src/MiniPdf/Drawing/Codecs/TiffCodec.cs | 214 -- src/MiniPdf/Drawing/Codecs/ZlibHelper.cs | 119 - src/MiniPdf/Drawing/Colors/Color.cs | 985 -------- src/MiniPdf/Drawing/Colors/KnownColor.cs | 190 -- src/MiniPdf/Drawing/Colors/KnownColorTable.cs | 204 -- src/MiniPdf/Drawing/Colors/SystemColors.cs | 174 -- src/MiniPdf/Drawing/Drawing2D/Blend.cs | 37 - src/MiniPdf/Drawing/Drawing2D/ColorBlend.cs | 39 - src/MiniPdf/Drawing/Drawing2D/CombineMode.cs | 38 - .../Drawing/Drawing2D/CompositingMode.cs | 18 - .../Drawing/Drawing2D/CompositingQuality.cs | 38 - src/MiniPdf/Drawing/Drawing2D/DashCap.cs | 23 - src/MiniPdf/Drawing/Drawing2D/DashStyle.cs | 38 - src/MiniPdf/Drawing/Drawing2D/FillMode.cs | 18 - .../Drawing/Drawing2D/FlushIntention.cs | 18 - src/MiniPdf/Drawing/Drawing2D/GraphicsPath.cs | 1243 ---------- src/MiniPdf/Drawing/Drawing2D/HatchBrush.cs | 59 - src/MiniPdf/Drawing/Drawing2D/HatchStyle.cs | 288 --- .../Drawing/Drawing2D/ImageAttributes.cs | 276 --- .../Drawing/Drawing2D/InterpolationMode.cs | 53 - src/MiniPdf/Drawing/Drawing2D/LineCap.cs | 63 - src/MiniPdf/Drawing/Drawing2D/LineJoin.cs | 28 - .../Drawing/Drawing2D/LinearGradientBrush.cs | 387 --- .../Drawing/Drawing2D/LinearGradientMode.cs | 28 - src/MiniPdf/Drawing/Drawing2D/Matrix.cs | 312 --- src/MiniPdf/Drawing/Drawing2D/MatrixOrder.cs | 18 - src/MiniPdf/Drawing/Drawing2D/PathData.cs | 20 - .../Drawing/Drawing2D/PathGradientBrush.cs | 293 --- .../Drawing/Drawing2D/PathPointType.cs | 51 - src/MiniPdf/Drawing/Drawing2D/PenAlignment.cs | 18 - src/MiniPdf/Drawing/Drawing2D/PenType.cs | 33 - .../Drawing/Drawing2D/PixelOffsetMode.cs | 38 - src/MiniPdf/Drawing/Drawing2D/Region.cs | 561 ----- src/MiniPdf/Drawing/Drawing2D/RegionData.cs | 13 - src/MiniPdf/Drawing/Drawing2D/RegionNode.cs | 292 --- .../Drawing/Drawing2D/SmoothingMode.cs | 38 - src/MiniPdf/Drawing/Drawing2D/WrapMode.cs | 33 - src/MiniPdf/Drawing/Enums/FontStyle.cs | 36 - src/MiniPdf/Drawing/Enums/GraphicsUnit.cs | 43 - src/MiniPdf/Drawing/Enums/ImageLockMode.cs | 28 - src/MiniPdf/Drawing/Enums/PixelFormat.cs | 123 - src/MiniPdf/Drawing/Enums/RotateFlipType.cs | 48 - src/MiniPdf/Drawing/Font/Cff/CffData.cs | 58 - src/MiniPdf/Drawing/Font/Cff/CffFont.cs | 208 -- src/MiniPdf/Drawing/Font/Cff/CffFontReader.cs | 136 -- src/MiniPdf/Drawing/Font/Cff/CffFontWriter.cs | 65 - .../Drawing/Font/Cff/CffGlyphAccessor.cs | 86 - src/MiniPdf/Drawing/Font/Cff/CffParser.cs | 553 ----- .../Drawing/Font/Cff/CffPrivateDict.cs | 27 - .../Drawing/Font/Cff/Type2Interpreter.cs | 893 ------- .../Drawing/Font/Core/FontFaceCollection.cs | 33 - .../Drawing/Font/Core/FontFaceStyle.cs | 28 - src/MiniPdf/Drawing/Font/Core/FontMetrics.cs | 63 - src/MiniPdf/Drawing/Font/Core/FontType.cs | 26 - .../Drawing/Font/Core/FontVariationAxis.cs | 40 - .../Font/Core/FontVariationInstance.cs | 29 - src/MiniPdf/Drawing/Font/Core/GlyphClass.cs | 24 - src/MiniPdf/Drawing/Font/Core/IFont.cs | 41 - src/MiniPdf/Drawing/Font/Core/IFontMetrics.cs | 68 - src/MiniPdf/Drawing/Font/Core/LicenseFlags.cs | 78 - .../Drawing/Font/Encoding/IFontEncoding.cs | 72 - .../Drawing/Font/Encoding/NullEncoding.cs | 32 - .../Font/Encoding/TtfUnicodeEncoding.cs | 49 - src/MiniPdf/Drawing/Font/FontFactory.cs | 142 -- src/MiniPdf/Drawing/Font/Glyphs/Glyph.cs | 42 - .../Drawing/Font/Glyphs/GlyphBoundingBox.cs | 52 - src/MiniPdf/Drawing/Font/Glyphs/GlyphId.cs | 33 - .../Drawing/Font/Glyphs/GlyphUInt32Id.cs | 37 - .../Drawing/Font/Glyphs/IGlyphAccessor.cs | 20 - .../Drawing/Font/IO/FontBinaryReader.cs | 126 - .../Drawing/Font/IO/FontBinaryWriter.cs | 127 - .../Drawing/Font/IO/FontStreamReader.cs | 113 - .../Drawing/Font/IO/OpenTypeOffsetTable.cs | 89 - .../Drawing/Font/IO/OpenTypeTableDirectory.cs | 118 - .../Drawing/Font/IO/OpenTypeTableRecord.cs | 47 - src/MiniPdf/Drawing/Font/IO/TtcReader.cs | 116 - src/MiniPdf/Drawing/Font/IO/Woff2Reader.cs | 45 - src/MiniPdf/Drawing/Font/IO/WoffReader.cs | 271 --- src/MiniPdf/Drawing/Font/Rendering/CurveTo.cs | 55 - .../Font/Rendering/GlyphOutlineRenderer.cs | 126 - .../Font/Rendering/IGlyphOutlinePainter.cs | 32 - src/MiniPdf/Drawing/Font/Rendering/LineTo.cs | 33 - src/MiniPdf/Drawing/Font/Rendering/MoveTo.cs | 33 - .../Font/Rendering/TtfOutlineRenderer.cs | 268 --- .../Font/Sources/ByteContentStreamSource.cs | 26 - .../Font/Sources/FileSystemStreamSource.cs | 30 - .../Drawing/Font/Sources/FontDefinition.cs | 43 - .../Font/Sources/FontFileDefinition.cs | 35 - .../Drawing/Font/Sources/IStreamSource.cs | 18 - .../Font/Ttf/Glyphs/GlyphOutlineData.cs | 47 - .../Font/Ttf/Glyphs/TtfCompositeGlyph.cs | 78 - .../Drawing/Font/Ttf/Glyphs/TtfPoint.cs | 49 - .../Drawing/Font/Ttf/Glyphs/TtfSimpleGlyph.cs | 52 - .../Drawing/Font/Ttf/Tables/TtfAvarTable.cs | 152 -- .../Font/Ttf/Tables/TtfCMapFormat0Table.cs | 47 - .../Font/Ttf/Tables/TtfCMapFormat12Table.cs | 87 - .../Font/Ttf/Tables/TtfCMapFormat4Table.cs | 146 -- .../Font/Ttf/Tables/TtfCMapFormatBaseTable.cs | 39 - .../Drawing/Font/Ttf/Tables/TtfCMapTable.cs | 136 -- .../Drawing/Font/Ttf/Tables/TtfCbdtTable.cs | 108 - .../Drawing/Font/Ttf/Tables/TtfCblcTable.cs | 263 --- .../Drawing/Font/Ttf/Tables/TtfFvarTable.cs | 141 -- .../Drawing/Font/Ttf/Tables/TtfGdefTable.cs | 170 -- .../Drawing/Font/Ttf/Tables/TtfGlyfTable.cs | 282 --- .../Drawing/Font/Ttf/Tables/TtfGposTable.cs | 49 - .../Drawing/Font/Ttf/Tables/TtfGsubTable.cs | 93 - .../Drawing/Font/Ttf/Tables/TtfGvarTable.cs | 149 -- .../Drawing/Font/Ttf/Tables/TtfHeadTable.cs | 102 - .../Drawing/Font/Ttf/Tables/TtfHheaTable.cs | 104 - .../Drawing/Font/Ttf/Tables/TtfHmtxTable.cs | 117 - .../Drawing/Font/Ttf/Tables/TtfKernTable.cs | 124 - .../Drawing/Font/Ttf/Tables/TtfLocaTable.cs | 112 - .../Drawing/Font/Ttf/Tables/TtfMaxpTable.cs | 149 -- .../Drawing/Font/Ttf/Tables/TtfNameTable.cs | 172 -- .../Drawing/Font/Ttf/Tables/TtfOs2Table.cs | 133 -- .../Drawing/Font/Ttf/Tables/TtfPostTable.cs | 82 - .../Drawing/Font/Ttf/Tables/TtfSvgTable.cs | 179 -- .../Drawing/Font/Ttf/Tables/TtfTableBase.cs | 42 - src/MiniPdf/Drawing/Font/Ttf/TtfFont.cs | 154 -- src/MiniPdf/Drawing/Font/Ttf/TtfFontReader.cs | 155 -- src/MiniPdf/Drawing/Font/Ttf/TtfFontWriter.cs | 264 --- .../Drawing/Font/Ttf/TtfGlyphAccessor.cs | 54 - src/MiniPdf/Drawing/Font/Ttf/TtfTables.cs | 122 - .../Font/Type1/Type1CharStringInterpreter.cs | 398 ---- src/MiniPdf/Drawing/Font/Type1/Type1Data.cs | 49 - src/MiniPdf/Drawing/Font/Type1/Type1Font.cs | 382 --- src/MiniPdf/Drawing/Font/Type1/Type1Parser.cs | 878 ------- src/MiniPdf/Drawing/Geometry/Point.cs | 133 -- src/MiniPdf/Drawing/Geometry/PointF.cs | 117 - .../Drawing/Geometry/PointTransform.cs | 32 - src/MiniPdf/Drawing/Geometry/Rectangle.cs | 304 --- src/MiniPdf/Drawing/Geometry/RectangleF.cs | 339 --- src/MiniPdf/Drawing/Geometry/Size.cs | 126 - src/MiniPdf/Drawing/Geometry/SizeF.cs | 128 - src/MiniPdf/Drawing/Graphics/Graphics.cs | 2104 ----------------- .../Drawing/Graphics/IDrawingContext.cs | 77 - .../Drawing/Graphics/RecordingGraphics.cs | 147 -- src/MiniPdf/Drawing/Imaging/AnimationFrame.cs | 21 - src/MiniPdf/Drawing/Imaging/Bitmap.cs | 721 ------ src/MiniPdf/Drawing/Imaging/BitmapData.cs | 41 - .../Drawing/Imaging/ColorAdjustType.cs | 43 - src/MiniPdf/Drawing/Imaging/ColorMap.cs | 20 - src/MiniPdf/Drawing/Imaging/ColorMatrix.cs | 175 -- .../Drawing/Imaging/ColorMatrixFlag.cs | 23 - src/MiniPdf/Drawing/Imaging/ColorPalette.cs | 40 - src/MiniPdf/Drawing/Imaging/Cursor.cs | 152 -- src/MiniPdf/Drawing/Imaging/EmfType.cs | 23 - src/MiniPdf/Drawing/Imaging/Encoder.cs | 67 - .../Drawing/Imaging/EncoderParameter.cs | 62 - .../Drawing/Imaging/EncoderParameters.cs | 31 - src/MiniPdf/Drawing/Imaging/FrameAnimator.cs | 142 -- .../Drawing/Imaging/FrameBlendMethod.cs | 8 - src/MiniPdf/Drawing/Imaging/FrameDimension.cs | 47 - .../Drawing/Imaging/FrameDisposeMethod.cs | 9 - src/MiniPdf/Drawing/Imaging/Icon.cs | 170 -- src/MiniPdf/Drawing/Imaging/Image.cs | 232 -- src/MiniPdf/Drawing/Imaging/ImageFlags.cs | 81 - src/MiniPdf/Drawing/Imaging/ImageFormat.cs | 97 - src/MiniPdf/Drawing/Imaging/Metafile.cs | 449 ---- .../Drawing/Imaging/MetafileFrameUnit.cs | 38 - src/MiniPdf/Drawing/Imaging/MetafileHeader.cs | 81 - src/MiniPdf/Drawing/Imaging/PropertyItem.cs | 30 - src/MiniPdf/Drawing/Imaging/SvgImage.cs | 197 -- src/MiniPdf/Drawing/Imaging/SystemIcons.cs | 98 - src/MiniPdf/Drawing/LICENSE.DRIT.Drawing | 21 - src/MiniPdf/Drawing/Metafile/BitUtils.cs | 41 - src/MiniPdf/Drawing/Metafile/Emf/EmfReader.cs | 199 -- .../Metafile/Emf/Enumerations/ArcDirection.cs | 20 - .../Metafile/Emf/Enumerations/ArmStyle.cs | 30 - .../Emf/Enumerations/BackgroundMode.cs | 20 - .../Emf/Enumerations/ColorAdjustment.cs | 27 - .../Emf/Enumerations/ColorMatchToTarget.cs | 27 - .../Enumerations/ColorMatchToTargetAction.cs | 9 - .../Metafile/Emf/Enumerations/ColorSpace.cs | 32 - .../Metafile/Emf/Enumerations/Contrast.cs | 28 - .../Metafile/Emf/Enumerations/DIBColors.cs | 32 - .../Metafile/Emf/Enumerations/EmrComment.cs | 47 - .../Emf/Enumerations/ExtTextOutOptions.cs | 43 - .../Metafile/Emf/Enumerations/FamilyType.cs | 31 - .../Emf/Enumerations/FormatSignature.cs | 27 - .../Metafile/Emf/Enumerations/GradientFill.cs | 32 - .../Metafile/Emf/Enumerations/GraphicsMode.cs | 24 - .../Metafile/Emf/Enumerations/HatchStyle.cs | 24 - .../Metafile/Emf/Enumerations/IcmMode.cs | 10 - .../Emf/Enumerations/IcmProfileFlags.cs | 12 - .../Enumerations/ModifyWorldTransformMode.cs | 10 - .../Metafile/Emf/Enumerations/RecordType.cs | 125 - .../Metafile/Emf/Enumerations/RegionMode.cs | 11 - .../Metafile/Emf/Objects/ColorAdjustment.cs | 110 - .../Drawing/Metafile/Emf/Objects/EmrText.cs | 167 -- .../Metafile/Emf/Objects/GradientRectangle.cs | 23 - .../Metafile/Emf/Objects/GradientTriangle.cs | 27 - .../Drawing/Metafile/Emf/Objects/Header.cs | 116 - .../Metafile/Emf/Objects/HeaderExtension1.cs | 42 - .../Metafile/Emf/Objects/HeaderExtension2.cs | 41 - .../Drawing/Metafile/Emf/Objects/TriVertex.cs | 39 - .../Drawing/Metafile/Emf/Objects/XForm.cs | 39 - .../DrawingRecordTypes/EMR_ALPHABLEND.cs | 125 - .../DrawingRecordTypes/EMR_ANGLEARC.cs | 44 - .../Emf/Records/DrawingRecordTypes/EMR_ARC.cs | 47 - .../Records/DrawingRecordTypes/EMR_ARCTO.cs | 47 - .../Records/DrawingRecordTypes/EMR_BITBLT.cs | 118 - .../Records/DrawingRecordTypes/EMR_CHORD.cs | 47 - .../Records/DrawingRecordTypes/EMR_ELLIPSE.cs | 33 - .../Emf/Records/DrawingRecordTypes/EMR_EOF.cs | 45 - .../DrawingRecordTypes/EMR_EXTFLOODFILL.cs | 51 - .../DrawingRecordTypes/EMR_EXTTEXTOUTA.cs | 66 - .../DrawingRecordTypes/EMR_EXTTEXTOUTW.cs | 47 - .../DrawingRecordTypes/EMR_GRADIENTFILL.cs | 108 - .../Records/DrawingRecordTypes/EMR_LINETO.cs | 30 - .../Records/DrawingRecordTypes/EMR_MASKBLT.cs | 176 -- .../Emf/Records/DrawingRecordTypes/EMR_PIE.cs | 40 - .../Records/DrawingRecordTypes/EMR_PLGBLT.cs | 171 -- .../DrawingRecordTypes/EMR_POLYBEZIER.cs | 48 - .../DrawingRecordTypes/EMR_POLYBEZIER16.cs | 48 - .../DrawingRecordTypes/EMR_POLYBEZIERTO.cs | 47 - .../DrawingRecordTypes/EMR_POLYBEZIERTO16.cs | 47 - .../DrawingRecordTypes/EMR_POLYDRAW.cs | 66 - .../DrawingRecordTypes/EMR_POLYDRAW16.cs | 67 - .../Records/DrawingRecordTypes/EMR_POLYGON.cs | 47 - .../DrawingRecordTypes/EMR_POLYGON16.cs | 47 - .../DrawingRecordTypes/EMR_POLYLINE.cs | 47 - .../DrawingRecordTypes/EMR_POLYLINE16.cs | 47 - .../DrawingRecordTypes/EMR_POLYLINETO.cs | 48 - .../DrawingRecordTypes/EMR_POLYLINETO16.cs | 48 - .../DrawingRecordTypes/EMR_POLYPOLYGON.cs | 67 - .../DrawingRecordTypes/EMR_POLYPOLYGON16.cs | 67 - .../DrawingRecordTypes/EMR_POLYPOLYLINE.cs | 67 - .../DrawingRecordTypes/EMR_POLYPOLYLINE16.cs | 68 - .../DrawingRecordTypes/EMR_POLYTEXTOUTA.cs | 62 - .../DrawingRecordTypes/EMR_POLYTEXTOUTW.cs | 62 - .../DrawingRecordTypes/EMR_RECTANGLE.cs | 29 - .../DrawingRecordTypes/EMR_ROUNDRECT.cs | 35 - .../EMR_SETDIBITSTODEVICE.cs | 112 - .../DrawingRecordTypes/EMR_STRETCHBLT.cs | 126 - .../DrawingRecordTypes/EMR_STRETCHDIBITS.cs | 116 - .../DrawingRecordTypes/EMR_TRANSPARENTBLT.cs | 122 - .../EMR_CREATEBRUSHINDIRECT.cs | 37 - .../EMR_CREATEDIBPATTERNBRUSHPT.cs | 79 - .../ObjectRecordTypes/EMR_CREATEMONOBRUSH.cs | 78 - .../ObjectRecordTypes/EMR_CREATEPEN.cs | 32 - .../EMR_EXTCREATEFONTINDIRECTW.cs | 33 - .../ObjectRecordTypes/EMR_EXTCREATEPEN.cs | 117 - .../Drawing/Metafile/Emf/Records/Record.cs | 29 - .../Metafile/Emf/Records/RecordHeader.cs | 32 - .../Records/StateRecordTypes/EMR_ABORTPATH.cs | 24 - .../Records/StateRecordTypes/EMR_BEGINPATH.cs | 23 - .../StateRecordTypes/EMR_CLOSEFIGURE.cs | 24 - .../EMR_COLORCORRECTPALETTE.cs | 31 - .../EMR_COLORMATCHTOTARGETW.cs | 51 - .../Records/StateRecordTypes/EMR_COMMENT.cs | 33 - .../StateRecordTypes/EMR_CREATECOLORSPACE.cs | 36 - .../StateRecordTypes/EMR_CREATECOLORSPACEW.cs | 36 - .../StateRecordTypes/EMR_CREATEPALETTE.cs | 36 - .../StateRecordTypes/EMR_DELETECOLORSPACE.cs | 28 - .../StateRecordTypes/EMR_DELETEOBJECT.cs | 29 - .../StateRecordTypes/EMR_DRAWESCAPE.cs | 35 - .../Records/StateRecordTypes/EMR_ENDPATH.cs | 23 - .../StateRecordTypes/EMR_EXCLUDECLIPRECT.cs | 30 - .../Records/StateRecordTypes/EMR_EXTESCAPE.cs | 37 - .../StateRecordTypes/EMR_EXTSELECTCLIPRGN.cs | 38 - .../Records/StateRecordTypes/EMR_FILLPATH.cs | 29 - .../Records/StateRecordTypes/EMR_FILLRGN.cs | 44 - .../StateRecordTypes/EMR_FLATTENPATH.cs | 23 - .../StateRecordTypes/EMR_FORCEUFIMAPPING.cs | 24 - .../Records/StateRecordTypes/EMR_FRAMERGN.cs | 51 - .../StateRecordTypes/EMR_GLSBOUNDEDRECORD.cs | 39 - .../Records/StateRecordTypes/EMR_GLSRECORD.cs | 33 - .../Records/StateRecordTypes/EMR_HEADER.cs | 60 - .../StateRecordTypes/EMR_INTERSECTCLIPRECT.cs | 29 - .../Records/StateRecordTypes/EMR_INVERTRGN.cs | 40 - .../EMR_MODIFYWORLDTRANSFORM.cs | 51 - .../Records/StateRecordTypes/EMR_MOVETOEX.cs | 31 - .../StateRecordTypes/EMR_NAMEDESCAPE.cs | 38 - .../StateRecordTypes/EMR_OFFSETCLIPRGN.cs | 32 - .../Records/StateRecordTypes/EMR_PAINTRGN.cs | 40 - .../StateRecordTypes/EMR_PIXELFORMAT.cs | 33 - .../StateRecordTypes/EMR_REALIZEPALETTE.cs | 23 - .../StateRecordTypes/EMR_RESIZEPALETTE.cs | 32 - .../Records/StateRecordTypes/EMR_RESTOREDC.cs | 29 - .../Records/StateRecordTypes/EMR_SAVEDC.cs | 25 - .../EMR_SCALEVIEWPORTEXTEX.cs | 39 - .../StateRecordTypes/EMR_SCALEWINDOWEXTEX.cs | 40 - .../StateRecordTypes/EMR_SELECTCLIPPATH.cs | 27 - .../StateRecordTypes/EMR_SELECTOBJECT.cs | 28 - .../StateRecordTypes/EMR_SELECTPALETTE.cs | 27 - .../StateRecordTypes/EMR_SETARCDIRECTION.cs | 29 - .../StateRecordTypes/EMR_SETBKCOLOR.cs | 30 - .../Records/StateRecordTypes/EMR_SETBKMODE.cs | 28 - .../StateRecordTypes/EMR_SETBRUSHORGEX.cs | 32 - .../EMR_SETCOLORADJUSTMENT.cs | 29 - .../StateRecordTypes/EMR_SETCOLORSPACE.cs | 28 - .../StateRecordTypes/EMR_SETICMMODE.cs | 27 - .../StateRecordTypes/EMR_SETICMPROFILEA.cs | 46 - .../StateRecordTypes/EMR_SETICMPROFILEW.cs | 47 - .../Records/StateRecordTypes/EMR_SETLAYOUT.cs | 28 - .../StateRecordTypes/EMR_SETLINKEDUFIS.cs | 34 - .../StateRecordTypes/EMR_SETMAPMODE.cs | 30 - .../StateRecordTypes/EMR_SETMAPPERFLAGS.cs | 28 - .../StateRecordTypes/EMR_SETMETARGN.cs | 24 - .../StateRecordTypes/EMR_SETMITERLIMIT.cs | 28 - .../StateRecordTypes/EMR_SETPALETTEENTRIES.cs | 47 - .../Records/StateRecordTypes/EMR_SETPIXELV.cs | 35 - .../StateRecordTypes/EMR_SETPOLYFILLMODE.cs | 28 - .../Records/StateRecordTypes/EMR_SETROP2.cs | 26 - .../StateRecordTypes/EMR_SETSTRETCHBLTMODE.cs | 28 - .../StateRecordTypes/EMR_SETTEXTALIGN.cs | 28 - .../StateRecordTypes/EMR_SETTEXTCOLOR.cs | 30 - .../EMR_SETTEXTJUSTIFICATION.cs | 33 - .../StateRecordTypes/EMR_SETVIEWPORTEXTEX.cs | 32 - .../StateRecordTypes/EMR_SETVIEWPORTORGEX.cs | 32 - .../StateRecordTypes/EMR_SETWINDOWEXTEX.cs | 33 - .../StateRecordTypes/EMR_SETWINDOWORGEX.cs | 33 - .../StateRecordTypes/EMR_SETWORLDTRANSFORM.cs | 48 - .../StateRecordTypes/EMR_SMALLTEXTOUT.cs | 56 - .../StateRecordTypes/EMR_STROKEANDFILLPATH.cs | 29 - .../StateRecordTypes/EMR_STROKEPATH.cs | 30 - .../Records/StateRecordTypes/EMR_WIDENPATH.cs | 23 - .../Drawing/Metafile/EmfPlus/EmfPlusReader.cs | 124 - .../Enumerations/EmfPlusCombineMode.cs | 12 - .../Enumerations/EmfPlusCompositingMode.cs | 8 - .../Enumerations/EmfPlusCompositingQuality.cs | 12 - .../Enumerations/EmfPlusHeaderFlags.cs | 11 - .../Enumerations/EmfPlusInterpolationMode.cs | 15 - .../Enumerations/EmfPlusMatrixOrder.cs | 8 - .../Enumerations/EmfPlusPixelOffsetMode.cs | 12 - .../Enumerations/EmfPlusSmoothingMode.cs | 12 - .../Enumerations/EmfPlusTextRenderingHint.cs | 38 - .../EmfPlus/Enumerations/EmfPlusUnitType.cs | 13 - .../EmfPlus/Enumerations/ObjectType.cs | 22 - .../EmfPlus/Enumerations/RecordType.cs | 70 - .../Enumerations/RegionNodeDataType.cs | 21 - .../Objects/EmfPlusGraphicsVersionObject.cs | 13 - .../EmfPlus/Objects/EmfPlusRectFObject.cs | 31 - .../Objects/EmfPlusRegionNodeObject.cs | 17 - .../EmfPlus/Objects/EmfPlusRegionObject.cs | 17 - .../EmfPlusBeginContainerNoParamsRecord.cs | 32 - .../Records/EmfPlusBeginContainerRecord.cs | 20 - .../EmfPlus/Records/EmfPlusClearRecord.cs | 32 - .../EmfPlus/Records/EmfPlusCommentRecord.cs | 17 - .../EmfPlus/Records/EmfPlusDrawArcRecord.cs | 44 - .../Records/EmfPlusDrawBeziersRecord.cs | 20 - .../Records/EmfPlusDrawClosedCurveRecord.cs | 20 - .../EmfPlus/Records/EmfPlusDrawCurveRecord.cs | 20 - .../Records/EmfPlusDrawDriverstringRecord.cs | 20 - .../Records/EmfPlusDrawEllipseRecord.cs | 35 - .../Records/EmfPlusDrawImagePointsRecord.cs | 82 - .../EmfPlus/Records/EmfPlusDrawImageRecord.cs | 46 - .../EmfPlus/Records/EmfPlusDrawLinesRecord.cs | 20 - .../EmfPlus/Records/EmfPlusDrawPathRecord.cs | 34 - .../EmfPlus/Records/EmfPlusDrawPieRecord.cs | 44 - .../EmfPlus/Records/EmfPlusDrawRectsRecord.cs | 47 - .../Records/EmfPlusDrawStringRecord.cs | 48 - .../Records/EmfPlusEndContainerRecord.cs | 32 - .../EmfPlus/Records/EmfPlusEndOfFileRecord.cs | 32 - .../Records/EmfPlusFillClosedCurveRecord.cs | 20 - .../Records/EmfPlusFillEllipseRecord.cs | 35 - .../EmfPlus/Records/EmfPlusFillPathRecord.cs | 34 - .../EmfPlus/Records/EmfPlusFillPieRecord.cs | 44 - .../Records/EmfPlusFillPolygonRecord.cs | 20 - .../EmfPlus/Records/EmfPlusFillRectsRecord.cs | 47 - .../Records/EmfPlusFillRegionRecord.cs | 34 - .../EmfPlus/Records/EmfPlusGetDCRecord.cs | 20 - .../EmfPlus/Records/EmfPlusHeaderRecord.cs | 44 - .../Records/EmfPlusMultiFormatEndRecord.cs | 20 - .../EmfPlusMultiFormatSectionRecord.cs | 20 - .../Records/EmfPlusMultiFormatStartRecord.cs | 20 - .../EmfPlusMultiplyWorldTransformRecord.cs | 50 - .../EmfPlus/Records/EmfPlusObjectRecord.cs | 49 - .../Records/EmfPlusOffsetClipRecord.cs | 35 - .../EmfPlus/Records/EmfPlusResetClipRecord.cs | 20 - .../EmfPlusResetWorldTransformRecord.cs | 20 - .../EmfPlus/Records/EmfPlusRestoreRecord.cs | 32 - .../EmfPlusRotateWorldTransformRecord.cs | 35 - .../EmfPlus/Records/EmfPlusSaveRecord.cs | 32 - .../EmfPlusScaleWorldTransformRecord.cs | 38 - .../EmfPlusSerializableObjectRecord.cs | 20 - .../Records/EmfPlusSetAntiAliasModeRecord.cs | 23 - .../Records/EmfPlusSetClipPathRecord.cs | 35 - .../Records/EmfPlusSetClipRectRecord.cs | 36 - .../Records/EmfPlusSetClipRegionRecord.cs | 35 - .../EmfPlusSetCompositingModeRecord.cs | 23 - .../EmfPlusSetCompositingQualityRecord.cs | 23 - .../EmfPlusSetInterpolationModeRecord.cs | 23 - .../Records/EmfPlusSetPageTransformRecord.cs | 36 - .../EmfPlusSetPixelOffsetModeRecord.cs | 23 - .../EmfPlusSetRenderingOriginRecord.cs | 35 - .../EmfPlus/Records/EmfPlusSetTSClipRecord.cs | 20 - .../Records/EmfPlusSetTSGraphicsRecord.cs | 20 - .../Records/EmfPlusSetTextContrastRecord.cs | 32 - .../EmfPlusSetTextRenderingHintRecord.cs | 23 - .../Records/EmfPlusSetWorldTransformRecord.cs | 47 - .../Records/EmfPlusStrokeFillPathRecord.cs | 32 - .../EmfPlusTranslateWorldTransformRecord.cs | 38 - .../Metafile/EmfPlus/Records/Record.cs | 27 - .../Metafile/EmfPlus/Records/RecordHeader.cs | 40 - .../Drawing/Metafile/MetafileDocument.cs | 56 - .../Drawing/Metafile/MetafileFormat.cs | 28 - .../Drawing/Metafile/MetafileReader.cs | 368 --- .../Drawing/Metafile/MetafileWriter.cs | 272 --- .../Wmf/Enumerations/BinaryRasterOperation.cs | 88 - .../Metafile/Wmf/Enumerations/BitCount.cs | 30 - .../Metafile/Wmf/Enumerations/BrushStyle.cs | 58 - .../Metafile/Wmf/Enumerations/CharacterSet.cs | 54 - .../Metafile/Wmf/Enumerations/ColorUsage.cs | 23 - .../Metafile/Wmf/Enumerations/Compression.cs | 62 - .../Metafile/Wmf/Enumerations/FamilyFont.cs | 42 - .../Metafile/Wmf/Enumerations/FloodFill.cs | 22 - .../Metafile/Wmf/Enumerations/FontQuality.cs | 43 - .../Wmf/Enumerations/GamutMappingIntent.cs | 31 - .../Metafile/Wmf/Enumerations/HatchStyle.cs | 41 - .../Metafile/Wmf/Enumerations/Layout.cs | 26 - .../Wmf/Enumerations/LogicalColorSpace.cs | 26 - .../Wmf/Enumerations/LogicalColorSpaceV5.cs | 23 - .../Metafile/Wmf/Enumerations/MapMode.cs | 54 - .../Wmf/Enumerations/MetafileEscapes.cs | 75 - .../Metafile/Wmf/Enumerations/MetafileType.cs | 21 - .../Wmf/Enumerations/MetafileVersion.cs | 21 - .../Metafile/Wmf/Enumerations/MixMode.cs | 21 - .../Metafile/Wmf/Enumerations/OutPrecision.cs | 61 - .../Wmf/Enumerations/PaletteEntryFlag.cs | 29 - .../Metafile/Wmf/Enumerations/PenStyle.cs | 30 - .../Metafile/Wmf/Enumerations/PitchFont.cs | 26 - .../Metafile/Wmf/Enumerations/PolyFillMode.cs | 21 - .../Wmf/Enumerations/PostScriptCap.cs | 29 - .../Wmf/Enumerations/PostScriptClipping.cs | 26 - .../Enumerations/PostScriptFeatureSetting.cs | 53 - .../Wmf/Enumerations/PostScriptJoin.cs | 28 - .../Metafile/Wmf/Enumerations/RecordType.cs | 102 - .../Metafile/Wmf/Enumerations/StretchMode.cs | 33 - .../Enumerations/TernaryRasterOperation.cs | 269 --- .../Metafile/Wmf/Flags/ClipPrecision.cs | 46 - .../Metafile/Wmf/Flags/ExtTextOutOptions.cs | 52 - .../Metafile/Wmf/Flags/TextAlignmentMode.cs | 52 - .../Wmf/Flags/VerticalTextAlignmentMode.cs | 41 - .../Drawing/Metafile/Wmf/Objects/Bitmap16.cs | 84 - .../Metafile/Wmf/Objects/BitmapCoreHeader.cs | 57 - .../Metafile/Wmf/Objects/BitmapInfoHeader.cs | 101 - .../Metafile/Wmf/Objects/BitmapV4Header.cs | 77 - .../Metafile/Wmf/Objects/BitmapV5Header.cs | 33 - .../Drawing/Metafile/Wmf/Objects/Brush.cs | 27 - .../Drawing/Metafile/Wmf/Objects/CIEXYZ.cs | 49 - .../Metafile/Wmf/Objects/CIEXYZTriple.cs | 42 - .../Drawing/Metafile/Wmf/Objects/ColorRef.cs | 49 - .../Wmf/Objects/DeviceIndependentBitmap.cs | 116 - .../Drawing/Metafile/Wmf/Objects/Font.cs | 130 - .../Drawing/Metafile/Wmf/Objects/LogBrush.cs | 30 - .../Metafile/Wmf/Objects/LogColorSpace.cs | 182 -- .../Metafile/Wmf/Objects/LogColorSpaceW.cs | 119 - .../Drawing/Metafile/Wmf/Objects/Palette.cs | 51 - .../Metafile/Wmf/Objects/PaletteEntry.cs | 52 - .../Drawing/Metafile/Wmf/Objects/Pen.cs | 45 - .../Metafile/Wmf/Objects/PitchAndFamily.cs | 39 - .../Drawing/Metafile/Wmf/Objects/PointL.cs | 35 - .../Drawing/Metafile/Wmf/Objects/PointS.cs | 35 - .../Metafile/Wmf/Objects/PolyPolygon.cs | 26 - .../Drawing/Metafile/Wmf/Objects/RGBQuad.cs | 45 - .../Drawing/Metafile/Wmf/Objects/Rect.cs | 49 - .../Drawing/Metafile/Wmf/Objects/RectL.cs | 49 - .../Drawing/Metafile/Wmf/Objects/Region.cs | 92 - .../Drawing/Metafile/Wmf/Objects/Scan.cs | 83 - .../Drawing/Metafile/Wmf/Objects/SizeL.cs | 35 - .../Wmf/Records/AbstractBitmapRecord.cs | 65 - .../Records/EscapeRecordTypes/MetaEscape.cs | 50 - .../Drawing/Metafile/Wmf/Records/META_ARC.cs | 48 - .../Metafile/Wmf/Records/META_BITBLT.cs | 58 - .../Metafile/Wmf/Records/META_CHORD.cs | 48 - .../Metafile/Wmf/Records/META_DIBBITBLT.cs | 18 - .../Wmf/Records/META_DIBSTRETCHBLT.cs | 81 - .../Metafile/Wmf/Records/META_ELLIPSE.cs | 36 - .../Drawing/Metafile/Wmf/Records/META_EOF.cs | 24 - .../Metafile/Wmf/Records/META_EXTFLOODFILL.cs | 36 - .../Metafile/Wmf/Records/META_EXTTEXTOUT.cs | 124 - .../Metafile/Wmf/Records/META_FILLREGION.cs | 44 - .../Metafile/Wmf/Records/META_FLOODFILL.cs | 54 - .../Metafile/Wmf/Records/META_FRAMEREGION.cs | 58 - .../Metafile/Wmf/Records/META_INVERTREGION.cs | 16 - .../Metafile/Wmf/Records/META_LINETO.cs | 21 - .../Metafile/Wmf/Records/META_PAINTREGION.cs | 28 - .../Metafile/Wmf/Records/META_PATBLT.cs | 63 - .../Drawing/Metafile/Wmf/Records/META_PIE.cs | 52 - .../Metafile/Wmf/Records/META_PLACEABLE.cs | 85 - .../Metafile/Wmf/Records/META_POLYGON.cs | 42 - .../Metafile/Wmf/Records/META_POLYLINE.cs | 55 - .../Metafile/Wmf/Records/META_POLYPOLYGON.cs | 62 - .../Metafile/Wmf/Records/META_RECTANGLE.cs | 58 - .../Metafile/Wmf/Records/META_ROUNDRECT.cs | 73 - .../Metafile/Wmf/Records/META_SETDIBTODEV.cs | 101 - .../Metafile/Wmf/Records/META_SETPIXEL.cs | 54 - .../Metafile/Wmf/Records/META_STRETCHBLT.cs | 113 - .../Metafile/Wmf/Records/META_STRETCHDIB.cs | 114 - .../Metafile/Wmf/Records/META_TEXTOUT.cs | 66 - .../Metafile/Wmf/Records/MetaHeader.cs | 80 - .../META_CREATEFONTINDIRECT.cs | 37 - .../ObjectRecordTypes/META_CREATEPALETTE.cs | 37 - .../META_CREATEPATTERNBRUSH.cs | 58 - .../META_CREATEPENINDIRECT.cs | 39 - .../ObjectRecordTypes/META_CREATEREGION.cs | 39 - .../ObjectRecordTypes/META_DELETEOBJECT.cs | 29 - .../META_DIBCREATEPATTERNBRUSH.cs | 50 - .../META_SELECTCLIPREGION.cs | 28 - .../ObjectRecordTypes/META_SELECTOBJECT.cs | 34 - .../ObjectRecordTypes/META_SELECTPALETTE.cs | 23 - .../MetaCreatebrushindirect.cs | 46 - .../Drawing/Metafile/Wmf/Records/Record.cs | 22 - .../Metafile/Wmf/Records/RecordHeader.cs | 38 - .../StateRecordTypes/META_ANIMATEPALETTE.cs | 39 - .../StateRecordTypes/META_EXCLUDECLIPRECT.cs | 41 - .../META_INTERSECTCLIPRECT.cs | 41 - .../Records/StateRecordTypes/META_MOVETO.cs | 30 - .../StateRecordTypes/META_OFFSETCLIPRGN.cs | 30 - .../META_OFFSETVIEWPORTORG.cs | 30 - .../StateRecordTypes/META_OFFSETWINDOWORG.cs | 30 - .../StateRecordTypes/META_REALIZEPALETTE.cs | 12 - .../StateRecordTypes/META_RESIZEPALETTE.cs | 16 - .../StateRecordTypes/META_RESTOREDC.cs | 28 - .../Records/StateRecordTypes/META_SAVEDC.cs | 25 - .../StateRecordTypes/META_SCALEVIEWPORTEXT.cs | 41 - .../StateRecordTypes/META_SCALEWINDOWEXT.cs | 40 - .../StateRecordTypes/META_SETBKCOLOR.cs | 29 - .../StateRecordTypes/META_SETBKMODE.cs | 28 - .../StateRecordTypes/META_SETLAYOUT.cs | 33 - .../StateRecordTypes/META_SETMAPMODE.cs | 28 - .../StateRecordTypes/META_SETMAPPERFLAGS.cs | 28 - .../StateRecordTypes/META_SETPALENTRIES.cs | 48 - .../StateRecordTypes/META_SETPOLYFILLMODE.cs | 28 - .../StateRecordTypes/META_SETRELABS.cs | 29 - .../Records/StateRecordTypes/META_SETROP2.cs | 29 - .../META_SETSTRETCHBLTMODE.cs | 29 - .../StateRecordTypes/META_SETTEXTALIGN.cs | 30 - .../StateRecordTypes/META_SETTEXTCHAREXTRA.cs | 29 - .../StateRecordTypes/META_SETTEXTCOLOR.cs | 29 - .../META_SETTEXTJUSTIFICATION.cs | 33 - .../StateRecordTypes/META_SETVIEWPORTEXT.cs | 33 - .../StateRecordTypes/META_SETVIEWPORTORG.cs | 33 - .../StateRecordTypes/META_SETWINDOWEXT.cs | 32 - .../StateRecordTypes/META_SETWINDOWORG.cs | 32 - src/MiniPdf/Drawing/Metafile/Wmf/WmfReader.cs | 132 -- src/MiniPdf/Drawing/NOTICE.md | 8 - .../Drawing/Pens/AdjustableArrowCap.cs | 62 - src/MiniPdf/Drawing/Pens/CustomLineCap.cs | 114 - src/MiniPdf/Drawing/Pens/Pen.cs | 391 --- src/MiniPdf/Drawing/Pens/Pens.cs | 727 ------ src/MiniPdf/Drawing/Rendering/ActiveEdge.cs | 10 - src/MiniPdf/Drawing/Rendering/BrushSampler.cs | 32 - src/MiniPdf/Drawing/Rendering/DashExpander.cs | 130 - src/MiniPdf/Drawing/Rendering/EdgeBuilder.cs | 97 - src/MiniPdf/Drawing/Rendering/EmfPlayer.cs | 694 ------ .../Drawing/Rendering/GradientEvaluator.cs | 182 -- .../Drawing/Rendering/GraphicsContainer.cs | 18 - .../Drawing/Rendering/GraphicsState.cs | 94 - .../Drawing/Rendering/HatchRenderer.cs | 56 - .../Drawing/Rendering/ImageInterpolator.cs | 116 - .../Drawing/Rendering/ImageRenderer.cs | 61 - .../Drawing/Rendering/ImageTransformer.cs | 91 - .../Drawing/Rendering/LineCapRenderer.cs | 60 - .../Drawing/Rendering/PixelCompositor.cs | 53 - src/MiniPdf/Drawing/Rendering/Rasterizer.cs | 253 -- .../Drawing/Rendering/ScanlineBuffer.cs | 25 - .../Drawing/Rendering/StrokeExpander.cs | 90 - .../Drawing/Rendering/TextureSampler.cs | 119 - src/MiniPdf/Drawing/Rendering/WmfPlayer.cs | 355 --- .../Drawing/Text/Bidi/BidiAlgorithm.cs | 688 ------ src/MiniPdf/Drawing/Text/Bidi/BidiBrackets.cs | 183 -- .../Drawing/Text/Bidi/BidiCharacterTable.cs | 282 --- .../Drawing/Text/Bidi/BidiCharacterType.cs | 77 - .../Drawing/Text/Bidi/BidiMirroring.cs | 161 -- .../Text/Bidi/BidiParagraphDirection.cs | 17 - src/MiniPdf/Drawing/Text/CharacterRange.cs | 31 - src/MiniPdf/Drawing/Text/Font.cs | 255 -- src/MiniPdf/Drawing/Text/FontCollection.cs | 126 - src/MiniPdf/Drawing/Text/FontFallbackChain.cs | 108 - .../Drawing/Text/FontFallbackResolver.cs | 98 - src/MiniPdf/Drawing/Text/FontFamily.cs | 333 --- src/MiniPdf/Drawing/Text/FontSettings.cs | 80 - .../Drawing/Text/GenericFontFamilies.cs | 23 - src/MiniPdf/Drawing/Text/GlyphRasterizer.cs | 100 - src/MiniPdf/Drawing/Text/HotkeyPrefix.cs | 23 - .../Drawing/Text/InstalledFontCollection.cs | 160 -- .../Drawing/Text/Native/LinuxFontDiscovery.cs | 153 -- .../Drawing/Text/Native/MacFontDiscovery.cs | 245 -- .../Text/Native/NativeFontDiscovery.cs | 63 - .../Drawing/Text/Native/NativeFontInfo.cs | 24 - .../Text/Native/WindowsFontDiscovery.cs | 260 -- src/MiniPdf/Drawing/Text/PathArcLength.cs | 220 -- .../Drawing/Text/PrivateFontCollection.cs | 44 - src/MiniPdf/Drawing/Text/ResolvedRun.cs | 45 - src/MiniPdf/Drawing/Text/RichTextOptions.cs | 51 - src/MiniPdf/Drawing/Text/RichTextRun.cs | 55 - src/MiniPdf/Drawing/Text/RunSegmenter.cs | 179 -- src/MiniPdf/Drawing/Text/StringAlignment.cs | 23 - .../Drawing/Text/StringDigitSubstitute.cs | 28 - src/MiniPdf/Drawing/Text/StringFormat.cs | 133 -- src/MiniPdf/Drawing/Text/StringFormatFlags.cs | 56 - src/MiniPdf/Drawing/Text/StringTrimming.cs | 38 - src/MiniPdf/Drawing/Text/SystemFontScanner.cs | 119 - src/MiniPdf/Drawing/Text/TextLayoutEngine.cs | 658 ------ src/MiniPdf/Drawing/Text/TextLine.cs | 22 - src/MiniPdf/Drawing/Text/TextOnPathLayout.cs | 147 -- src/MiniPdf/Drawing/Text/TextOnPathOptions.cs | 42 - .../Drawing/Text/TextOnPathOverflow.cs | 22 - src/MiniPdf/Drawing/Text/TextRenderingHint.cs | 38 - src/MiniPdf/Drawing/Text/TextRun.cs | 44 - .../Drawing/Vector/Commands/ClearCommand.cs | 32 - .../Drawing/Vector/Commands/ClipCommands.cs | 86 - .../Drawing/Vector/Commands/ImageCommand.cs | 111 - .../Drawing/Vector/Commands/PathCommands.cs | 83 - .../Drawing/Vector/Commands/StateCommands.cs | 183 -- .../Drawing/Vector/Commands/TextCommand.cs | 58 - .../Vector/Commands/TransformCommands.cs | 189 -- src/MiniPdf/Drawing/Vector/DrawingCommand.cs | 22 - .../Drawing/Vector/Emf/EmfDrawingContext.cs | 414 ---- .../Drawing/Vector/Emf/EmfRecordMapper.cs | 355 --- .../Drawing/Vector/Emf/WmfDrawingContext.cs | 132 -- .../Drawing/Vector/Svg/SvgBrushReader.cs | 376 --- .../Drawing/Vector/Svg/SvgBrushWriter.cs | 328 --- .../Drawing/Vector/Svg/SvgClipReader.cs | 53 - .../Drawing/Vector/Svg/SvgClipWriter.cs | 37 - .../Drawing/Vector/Svg/SvgDefCollector.cs | 141 -- src/MiniPdf/Drawing/Vector/Svg/SvgDefTable.cs | 218 -- .../Drawing/Vector/Svg/SvgDrawingContext.cs | 347 --- .../Drawing/Vector/Svg/SvgElementReader.cs | 102 - .../Vector/Svg/SvgEncoderParameters.cs | 53 - .../Drawing/Vector/Svg/SvgImageReader.cs | 115 - .../Drawing/Vector/Svg/SvgImageWriter.cs | 39 - .../Drawing/Vector/Svg/SvgPathParser.cs | 433 ---- .../Drawing/Vector/Svg/SvgPathWriter.cs | 120 - .../Drawing/Vector/Svg/SvgPenWriter.cs | 131 - src/MiniPdf/Drawing/Vector/Svg/SvgReader.cs | 615 ----- .../Drawing/Vector/Svg/SvgShapeReader.cs | 227 -- .../Drawing/Vector/Svg/SvgStyleParser.cs | 180 -- .../Drawing/Vector/Svg/SvgTextReader.cs | 145 -- .../Drawing/Vector/Svg/SvgTextWriter.cs | 176 -- .../Drawing/Vector/Svg/SvgTransformParser.cs | 175 -- .../Drawing/Vector/Svg/SvgTransformWriter.cs | 39 - src/MiniPdf/Drawing/Vector/Svg/SvgWriter.cs | 94 - .../Drawing/Vector/Svg/SvgXmlWriter.cs | 121 - src/MiniPdf/Drawing/Vector/VectorScene.cs | 65 - .../Drawing/Vector/VectorScenePlayer.cs | 25 - src/MiniPdf/EmfVectorRenderer.cs | 1449 ++++++++++++ src/MiniPdf/MiniPdf.csproj | 2 - src/MiniPdf/PdfWriter.cs | 54 +- src/MiniPdf/TrueTypeGlyphReader.cs | 381 +++ src/MiniPdf/WmfVectorAdapter.cs | 173 ++ .../generate_office_pdfs_docx.py | 4 +- tests/MiniPdf.Tests/DocxIssueFileTests.cs | 36 + tests/MiniPdf.Tests/EmfNativePlaybackTests.cs | 332 +++ tests/MiniPdf.Tests/EmfVectorRendererTests.cs | 1579 +++++++++++++ tests/MiniPdf.Tests/RegisteredFontTests.cs | 26 + .../MiniPdf.Tests/TrueTypeGlyphReaderTests.cs | 310 +++ .../MiniPdf.Tests/TrueTypeNativeGlyphTests.cs | 209 ++ tests/MiniPdf.Tests/WmfVectorAdapterTests.cs | 105 + tests/MiniPdf.Tests/XlsxIssueFileTests.cs | 17 +- 691 files changed, 4671 insertions(+), 61258 deletions(-) delete mode 100644 src/MiniPdf/Drawing/Brushes/Brush.cs delete mode 100644 src/MiniPdf/Drawing/Brushes/Brushes.cs delete mode 100644 src/MiniPdf/Drawing/Brushes/SolidBrush.cs delete mode 100644 src/MiniPdf/Drawing/Brushes/TextureBrush.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/BmpCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/CodecRegistry.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/EmfCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/GifCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/IImageCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/IcoCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/CoefficientBuffer.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ColorConverter.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/EntropyDecoder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ExifReader.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ForwardDct.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/FrameComponent.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/FrameHeader.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanEncoder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanTable.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/IdctTransform.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JfifHeader.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JpegDecoder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JpegEncoder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JpegMarker.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JpegReader.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/JpegWriter.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ProgressiveDecoder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/QuantizationTable.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/Quantizer.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ScanComponent.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/ScanHeader.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Jpeg/UpsampleBuffer.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/JpegCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Png/ApngChunkData.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Png/ApngFrameBuilder.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/Png/PngHelpers.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/PngCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/TiffCodec.cs delete mode 100644 src/MiniPdf/Drawing/Codecs/ZlibHelper.cs delete mode 100644 src/MiniPdf/Drawing/Colors/Color.cs delete mode 100644 src/MiniPdf/Drawing/Colors/KnownColor.cs delete mode 100644 src/MiniPdf/Drawing/Colors/KnownColorTable.cs delete mode 100644 src/MiniPdf/Drawing/Colors/SystemColors.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/Blend.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/ColorBlend.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/CombineMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/CompositingMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/CompositingQuality.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/DashCap.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/DashStyle.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/FillMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/FlushIntention.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/GraphicsPath.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/HatchBrush.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/HatchStyle.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/ImageAttributes.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/InterpolationMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/LineCap.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/LineJoin.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/LinearGradientBrush.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/LinearGradientMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/Matrix.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/MatrixOrder.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PathData.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PathGradientBrush.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PathPointType.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PenAlignment.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PenType.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/PixelOffsetMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/Region.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/RegionData.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/RegionNode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/SmoothingMode.cs delete mode 100644 src/MiniPdf/Drawing/Drawing2D/WrapMode.cs delete mode 100644 src/MiniPdf/Drawing/Enums/FontStyle.cs delete mode 100644 src/MiniPdf/Drawing/Enums/GraphicsUnit.cs delete mode 100644 src/MiniPdf/Drawing/Enums/ImageLockMode.cs delete mode 100644 src/MiniPdf/Drawing/Enums/PixelFormat.cs delete mode 100644 src/MiniPdf/Drawing/Enums/RotateFlipType.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffData.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffFont.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffFontReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffFontWriter.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffGlyphAccessor.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffParser.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/CffPrivateDict.cs delete mode 100644 src/MiniPdf/Drawing/Font/Cff/Type2Interpreter.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontFaceCollection.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontFaceStyle.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontMetrics.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontType.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontVariationAxis.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/FontVariationInstance.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/GlyphClass.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/IFont.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/IFontMetrics.cs delete mode 100644 src/MiniPdf/Drawing/Font/Core/LicenseFlags.cs delete mode 100644 src/MiniPdf/Drawing/Font/Encoding/IFontEncoding.cs delete mode 100644 src/MiniPdf/Drawing/Font/Encoding/NullEncoding.cs delete mode 100644 src/MiniPdf/Drawing/Font/Encoding/TtfUnicodeEncoding.cs delete mode 100644 src/MiniPdf/Drawing/Font/FontFactory.cs delete mode 100644 src/MiniPdf/Drawing/Font/Glyphs/Glyph.cs delete mode 100644 src/MiniPdf/Drawing/Font/Glyphs/GlyphBoundingBox.cs delete mode 100644 src/MiniPdf/Drawing/Font/Glyphs/GlyphId.cs delete mode 100644 src/MiniPdf/Drawing/Font/Glyphs/GlyphUInt32Id.cs delete mode 100644 src/MiniPdf/Drawing/Font/Glyphs/IGlyphAccessor.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/FontBinaryReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/FontBinaryWriter.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/FontStreamReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/OpenTypeOffsetTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/OpenTypeTableDirectory.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/OpenTypeTableRecord.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/TtcReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/Woff2Reader.cs delete mode 100644 src/MiniPdf/Drawing/Font/IO/WoffReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/CurveTo.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/GlyphOutlineRenderer.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/IGlyphOutlinePainter.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/LineTo.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/MoveTo.cs delete mode 100644 src/MiniPdf/Drawing/Font/Rendering/TtfOutlineRenderer.cs delete mode 100644 src/MiniPdf/Drawing/Font/Sources/ByteContentStreamSource.cs delete mode 100644 src/MiniPdf/Drawing/Font/Sources/FileSystemStreamSource.cs delete mode 100644 src/MiniPdf/Drawing/Font/Sources/FontDefinition.cs delete mode 100644 src/MiniPdf/Drawing/Font/Sources/FontFileDefinition.cs delete mode 100644 src/MiniPdf/Drawing/Font/Sources/IStreamSource.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Glyphs/GlyphOutlineData.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfCompositeGlyph.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfPoint.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfSimpleGlyph.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfAvarTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat0Table.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat12Table.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat4Table.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormatBaseTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCbdtTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCblcTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfFvarTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGdefTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGlyfTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGposTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGsubTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGvarTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHeadTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHheaTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHmtxTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfKernTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfLocaTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfMaxpTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfNameTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfOs2Table.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfPostTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfSvgTable.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/Tables/TtfTableBase.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/TtfFont.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/TtfFontReader.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/TtfFontWriter.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/TtfGlyphAccessor.cs delete mode 100644 src/MiniPdf/Drawing/Font/Ttf/TtfTables.cs delete mode 100644 src/MiniPdf/Drawing/Font/Type1/Type1CharStringInterpreter.cs delete mode 100644 src/MiniPdf/Drawing/Font/Type1/Type1Data.cs delete mode 100644 src/MiniPdf/Drawing/Font/Type1/Type1Font.cs delete mode 100644 src/MiniPdf/Drawing/Font/Type1/Type1Parser.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/Point.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/PointF.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/PointTransform.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/Rectangle.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/RectangleF.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/Size.cs delete mode 100644 src/MiniPdf/Drawing/Geometry/SizeF.cs delete mode 100644 src/MiniPdf/Drawing/Graphics/Graphics.cs delete mode 100644 src/MiniPdf/Drawing/Graphics/IDrawingContext.cs delete mode 100644 src/MiniPdf/Drawing/Graphics/RecordingGraphics.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/AnimationFrame.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Bitmap.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/BitmapData.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ColorAdjustType.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ColorMap.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ColorMatrix.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ColorMatrixFlag.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ColorPalette.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Cursor.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/EmfType.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Encoder.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/EncoderParameter.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/EncoderParameters.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/FrameAnimator.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/FrameBlendMethod.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/FrameDimension.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/FrameDisposeMethod.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Icon.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Image.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ImageFlags.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/ImageFormat.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/Metafile.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/MetafileFrameUnit.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/MetafileHeader.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/PropertyItem.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/SvgImage.cs delete mode 100644 src/MiniPdf/Drawing/Imaging/SystemIcons.cs delete mode 100644 src/MiniPdf/Drawing/LICENSE.DRIT.Drawing delete mode 100644 src/MiniPdf/Drawing/Metafile/BitUtils.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/EmfReader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArcDirection.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArmStyle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/BackgroundMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorAdjustment.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTarget.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTargetAction.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorSpace.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/Contrast.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/DIBColors.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/EmrComment.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ExtTextOutOptions.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FamilyType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FormatSignature.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GradientFill.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GraphicsMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/HatchStyle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmProfileFlags.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ModifyWorldTransformMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RecordType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RegionMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/ColorAdjustment.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/EmrText.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientRectangle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientTriangle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/Header.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension1.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension2.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/TriVertex.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Objects/XForm.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ALPHABLEND.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ANGLEARC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARCTO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_BITBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_CHORD.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ELLIPSE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EOF.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTFLOODFILL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTA.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_GRADIENTFILL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_LINETO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_MASKBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PIE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PLGBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTA.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_RECTANGLE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ROUNDRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_SETDIBITSTODEVICE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHDIBITS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_TRANSPARENTBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEBRUSHINDIRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEDIBPATTERNBRUSHPT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEMONOBRUSH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEPEN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEFONTINDIRECTW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEPEN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/Record.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/RecordHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ABORTPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_BEGINPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CLOSEFIGURE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORCORRECTPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORMATCHTOTARGETW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COMMENT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACEW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETECOLORSPACE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETEOBJECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DRAWESCAPE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ENDPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXCLUDECLIPRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTESCAPE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTSELECTCLIPRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FLATTENPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FORCEUFIMAPPING.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FRAMERGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSBOUNDEDRECORD.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSRECORD.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_HEADER.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INTERSECTCLIPRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INVERTRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MODIFYWORLDTRANSFORM.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MOVETOEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_NAMEDESCAPE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_OFFSETCLIPRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PAINTRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PIXELFORMAT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_REALIZEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESIZEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESTOREDC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SAVEDC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEVIEWPORTEXTEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEWINDOWEXTEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTCLIPPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTOBJECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETARCDIRECTION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKCOLOR.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBRUSHORGEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORADJUSTMENT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORSPACE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEA.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLAYOUT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLINKEDUFIS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPPERFLAGS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMETARGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMITERLIMIT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPALETTEENTRIES.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPIXELV.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPOLYFILLMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETROP2.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETSTRETCHBLTMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTALIGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTCOLOR.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTJUSTIFICATION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTEXTEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTORGEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWEXTEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWORGEX.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWORLDTRANSFORM.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SMALLTEXTOUT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEANDFILLPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_WIDENPATH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/EmfPlusReader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCombineMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingQuality.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusHeaderFlags.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusInterpolationMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusMatrixOrder.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusPixelOffsetMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusSmoothingMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusTextRenderingHint.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusUnitType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/ObjectType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RecordType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RegionNodeDataType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusGraphicsVersionObject.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRectFObject.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionNodeObject.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionObject.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerNoParamsRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusClearRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusCommentRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawArcRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawBeziersRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawClosedCurveRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawCurveRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawDriverstringRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawEllipseRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImagePointsRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImageRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawLinesRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPathRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPieRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawRectsRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawStringRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndContainerRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndOfFileRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillClosedCurveRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillEllipseRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPathRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPieRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPolygonRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRectsRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRegionRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusGetDCRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusHeaderRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatEndRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatSectionRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatStartRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiplyWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusObjectRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusOffsetClipRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetClipRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRestoreRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRotateWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSaveRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusScaleWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSerializableObjectRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetAntiAliasModeRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipPathRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRectRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRegionRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingModeRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingQualityRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetInterpolationModeRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPageTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPixelOffsetModeRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetRenderingOriginRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSClipRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSGraphicsRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextContrastRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextRenderingHintRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusStrokeFillPathRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusTranslateWorldTransformRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/Record.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/EmfPlus/Records/RecordHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/MetafileDocument.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/MetafileFormat.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/MetafileReader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/MetafileWriter.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BinaryRasterOperation.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BitCount.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BrushStyle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/CharacterSet.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/ColorUsage.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Compression.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FamilyFont.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FloodFill.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FontQuality.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/GamutMappingIntent.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/HatchStyle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Layout.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpace.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpaceV5.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MapMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileEscapes.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileVersion.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MixMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/OutPrecision.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PaletteEntryFlag.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PenStyle.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PitchFont.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PolyFillMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptCap.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptClipping.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptFeatureSetting.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptJoin.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/RecordType.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/StretchMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/TernaryRasterOperation.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Flags/ClipPrecision.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Flags/ExtTextOutOptions.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Flags/TextAlignmentMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Flags/VerticalTextAlignmentMode.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Bitmap16.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapCoreHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapInfoHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV4Header.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV5Header.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Brush.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZ.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZTriple.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/ColorRef.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/DeviceIndependentBitmap.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Font.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogBrush.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpace.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpaceW.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Palette.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/PaletteEntry.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Pen.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/PitchAndFamily.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/PolyPolygon.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/RGBQuad.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Rect.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/RectL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Region.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/Scan.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Objects/SizeL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/AbstractBitmapRecord.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/EscapeRecordTypes/MetaEscape.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ARC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_BITBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_CHORD.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBBITBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBSTRETCHBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ELLIPSE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EOF.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTFLOODFILL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTTEXTOUT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FILLREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FLOODFILL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FRAMEREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_INVERTREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_LINETO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PAINTREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PATBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PIE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PLACEABLE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYGON.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYLINE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYPOLYGON.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_RECTANGLE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ROUNDRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETDIBTODEV.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETPIXEL.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHBLT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHDIB.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/META_TEXTOUT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/MetaHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEFONTINDIRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPATTERNBRUSH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPENINDIRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DELETEOBJECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DIBCREATEPATTERNBRUSH.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTCLIPREGION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTOBJECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/MetaCreatebrushindirect.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/Record.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/RecordHeader.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_ANIMATEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_EXCLUDECLIPRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_INTERSECTCLIPRECT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_MOVETO.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETCLIPRGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETVIEWPORTORG.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETWINDOWORG.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_REALIZEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESIZEPALETTE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESTOREDC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SAVEDC.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEVIEWPORTEXT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEWINDOWEXT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKCOLOR.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETLAYOUT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPPERFLAGS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPALENTRIES.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPOLYFILLMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETRELABS.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETROP2.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETSTRETCHBLTMODE.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTALIGN.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCHAREXTRA.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCOLOR.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTJUSTIFICATION.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTEXT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTORG.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWEXT.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWORG.cs delete mode 100644 src/MiniPdf/Drawing/Metafile/Wmf/WmfReader.cs delete mode 100644 src/MiniPdf/Drawing/NOTICE.md delete mode 100644 src/MiniPdf/Drawing/Pens/AdjustableArrowCap.cs delete mode 100644 src/MiniPdf/Drawing/Pens/CustomLineCap.cs delete mode 100644 src/MiniPdf/Drawing/Pens/Pen.cs delete mode 100644 src/MiniPdf/Drawing/Pens/Pens.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/ActiveEdge.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/BrushSampler.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/DashExpander.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/EdgeBuilder.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/EmfPlayer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/GradientEvaluator.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/GraphicsContainer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/GraphicsState.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/HatchRenderer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/ImageInterpolator.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/ImageRenderer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/ImageTransformer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/LineCapRenderer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/PixelCompositor.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/Rasterizer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/ScanlineBuffer.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/StrokeExpander.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/TextureSampler.cs delete mode 100644 src/MiniPdf/Drawing/Rendering/WmfPlayer.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiAlgorithm.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiBrackets.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiCharacterTable.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiCharacterType.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiMirroring.cs delete mode 100644 src/MiniPdf/Drawing/Text/Bidi/BidiParagraphDirection.cs delete mode 100644 src/MiniPdf/Drawing/Text/CharacterRange.cs delete mode 100644 src/MiniPdf/Drawing/Text/Font.cs delete mode 100644 src/MiniPdf/Drawing/Text/FontCollection.cs delete mode 100644 src/MiniPdf/Drawing/Text/FontFallbackChain.cs delete mode 100644 src/MiniPdf/Drawing/Text/FontFallbackResolver.cs delete mode 100644 src/MiniPdf/Drawing/Text/FontFamily.cs delete mode 100644 src/MiniPdf/Drawing/Text/FontSettings.cs delete mode 100644 src/MiniPdf/Drawing/Text/GenericFontFamilies.cs delete mode 100644 src/MiniPdf/Drawing/Text/GlyphRasterizer.cs delete mode 100644 src/MiniPdf/Drawing/Text/HotkeyPrefix.cs delete mode 100644 src/MiniPdf/Drawing/Text/InstalledFontCollection.cs delete mode 100644 src/MiniPdf/Drawing/Text/Native/LinuxFontDiscovery.cs delete mode 100644 src/MiniPdf/Drawing/Text/Native/MacFontDiscovery.cs delete mode 100644 src/MiniPdf/Drawing/Text/Native/NativeFontDiscovery.cs delete mode 100644 src/MiniPdf/Drawing/Text/Native/NativeFontInfo.cs delete mode 100644 src/MiniPdf/Drawing/Text/Native/WindowsFontDiscovery.cs delete mode 100644 src/MiniPdf/Drawing/Text/PathArcLength.cs delete mode 100644 src/MiniPdf/Drawing/Text/PrivateFontCollection.cs delete mode 100644 src/MiniPdf/Drawing/Text/ResolvedRun.cs delete mode 100644 src/MiniPdf/Drawing/Text/RichTextOptions.cs delete mode 100644 src/MiniPdf/Drawing/Text/RichTextRun.cs delete mode 100644 src/MiniPdf/Drawing/Text/RunSegmenter.cs delete mode 100644 src/MiniPdf/Drawing/Text/StringAlignment.cs delete mode 100644 src/MiniPdf/Drawing/Text/StringDigitSubstitute.cs delete mode 100644 src/MiniPdf/Drawing/Text/StringFormat.cs delete mode 100644 src/MiniPdf/Drawing/Text/StringFormatFlags.cs delete mode 100644 src/MiniPdf/Drawing/Text/StringTrimming.cs delete mode 100644 src/MiniPdf/Drawing/Text/SystemFontScanner.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextLayoutEngine.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextLine.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextOnPathLayout.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextOnPathOptions.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextOnPathOverflow.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextRenderingHint.cs delete mode 100644 src/MiniPdf/Drawing/Text/TextRun.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/ClearCommand.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/ClipCommands.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/ImageCommand.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/PathCommands.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/StateCommands.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/TextCommand.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Commands/TransformCommands.cs delete mode 100644 src/MiniPdf/Drawing/Vector/DrawingCommand.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Emf/EmfDrawingContext.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Emf/EmfRecordMapper.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Emf/WmfDrawingContext.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgBrushReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgBrushWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgClipReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgClipWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgDefCollector.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgDefTable.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgDrawingContext.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgElementReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgEncoderParameters.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgImageReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgImageWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgPathParser.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgPathWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgPenWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgShapeReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgStyleParser.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgTextReader.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgTextWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgTransformParser.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgTransformWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/Svg/SvgXmlWriter.cs delete mode 100644 src/MiniPdf/Drawing/Vector/VectorScene.cs delete mode 100644 src/MiniPdf/Drawing/Vector/VectorScenePlayer.cs create mode 100644 src/MiniPdf/EmfVectorRenderer.cs create mode 100644 src/MiniPdf/TrueTypeGlyphReader.cs create mode 100644 src/MiniPdf/WmfVectorAdapter.cs create mode 100644 tests/MiniPdf.Tests/EmfNativePlaybackTests.cs create mode 100644 tests/MiniPdf.Tests/EmfVectorRendererTests.cs create mode 100644 tests/MiniPdf.Tests/TrueTypeGlyphReaderTests.cs create mode 100644 tests/MiniPdf.Tests/TrueTypeNativeGlyphTests.cs create mode 100644 tests/MiniPdf.Tests/WmfVectorAdapterTests.cs diff --git a/src/MiniPdf/DocxReader.cs b/src/MiniPdf/DocxReader.cs index f095ab21..c54c2254 100644 --- a/src/MiniPdf/DocxReader.cs +++ b/src/MiniPdf/DocxReader.cs @@ -2573,29 +2573,18 @@ private static string GetRelationshipsPath(string partPath) var scale = Math.Min(1d, Math.Min(4096d / requestedWidth, 4096d / requestedHeight)); var targetWidth = Math.Max(32, (int)Math.Round(requestedWidth * scale)); var targetHeight = Math.Max(32, (int)Math.Round(requestedHeight * scale)); - var normalizedBytes = EmfCompatibilityNormalizer.NormalizeForMiniPdfDrawing(sourceBytes, targetWidth, targetHeight); - using var sourceStream = new MemoryStream(normalizedBytes, writable: false); - using var metafile = new global::MiniSoftware.Drawing.Imaging.Metafile(sourceStream); - using var bitmap = metafile.ToBitmap(); - using var outputStream = new MemoryStream(); - if (hasCrop) - { - var cropX = Compat.Clamp((int)Math.Round(bitmap.Width * cropL), 0, bitmap.Width - 1); - var cropY = Compat.Clamp((int)Math.Round(bitmap.Height * cropT), 0, bitmap.Height - 1); - var cropWidth = Compat.Clamp((int)Math.Round(bitmap.Width * (1 - cropL - cropR)), 1, bitmap.Width - cropX); - var cropHeight = Compat.Clamp((int)Math.Round(bitmap.Height * (1 - cropT - cropB)), 1, bitmap.Height - cropY); - using var cropped = bitmap.Clone( - new global::MiniSoftware.Drawing.Geometry.Rectangle(cropX, cropY, cropWidth, cropHeight), bitmap.PixelFormat); - cropped.Save(outputStream, global::MiniSoftware.Drawing.Imaging.ImageFormat.Png); - } - else - { - bitmap.Save(outputStream, global::MiniSoftware.Drawing.Imaging.ImageFormat.Png); - } - return outputStream.ToArray(); + var renderBytes = WmfVectorAdapter.IsWmf(sourceBytes) ? WmfVectorAdapter.Convert(sourceBytes, targetWidth, targetHeight) : sourceBytes; + return EmfVectorRenderer.RenderCropped(renderBytes, targetWidth, targetHeight, PdfWriter.ResolveMetafileFont, + hasCrop ? cropL : 0, hasCrop ? cropT : 0, hasCrop ? cropR : 0, hasCrop ? cropB : 0); } - catch + catch (NotSupportedException error) + { + System.Diagnostics.Trace.TraceWarning("Independent metafile conversion is unsupported: {0}", error.Message); + return null; + } + catch (InvalidDataException error) { + System.Diagnostics.Trace.TraceWarning("Independent metafile conversion rejected invalid data: {0}", error.Message); return null; } } diff --git a/src/MiniPdf/Drawing/Brushes/Brush.cs b/src/MiniPdf/Drawing/Brushes/Brush.cs deleted file mode 100644 index 5fed5773..00000000 --- a/src/MiniPdf/Drawing/Brushes/Brush.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Brushes -{ - /// - /// Defines objects used to fill the interior of shapes, such as rectangles, ellipses, and paths. - /// This is the base class for all brush types including , , - /// , , and . - /// - /// - /// Brushes are used with objects to fill shapes. - /// Derived classes provide different fill patterns such as solid colors, hatching, gradients, and textures. - /// - public abstract class Brush : IDisposable - { - private bool _disposed; - - /// - /// Creates an exact copy of this brush. - /// - /// A new object that is a copy of this instance. - public abstract Brush Clone(); - - /// - /// Releases the unmanaged resources used by the brush and optionally releases the managed resources. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected virtual void Dispose(bool disposing) - { - _disposed = true; - } - - /// - /// Releases all resources used by this brush. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Throws an if this brush has been disposed. - /// - protected void CheckDisposed() - { - if (_disposed) - throw new ObjectDisposedException(GetType().Name); - } - } -} diff --git a/src/MiniPdf/Drawing/Brushes/Brushes.cs b/src/MiniPdf/Drawing/Brushes/Brushes.cs deleted file mode 100644 index 977ff721..00000000 --- a/src/MiniPdf/Drawing/Brushes/Brushes.cs +++ /dev/null @@ -1,727 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Brushes -{ - /// - /// Provides a set of predefined objects representing all colors. - /// - /// - /// Each property returns a cached for efficient reuse. - /// These brushes are commonly used for filling shapes and backgrounds. - /// - public static class Brushes - { - private static readonly SolidBrush?[] s_brushes = new SolidBrush?[141]; - - private static SolidBrush Get(KnownColor kc) - { - int idx = (int)kc - 27; // KnownColor.Transparent == 27 - return s_brushes[idx] ??= new SolidBrush(Color.FromKnownColor(kc)); - } - - /// - /// Gets a with color. - /// - public static SolidBrush Transparent => Get(KnownColor.Transparent); - - /// - /// Gets a with color. - /// - public static SolidBrush AliceBlue => Get(KnownColor.AliceBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush AntiqueWhite => Get(KnownColor.AntiqueWhite); - - /// - /// Gets a with color. - /// - public static SolidBrush Aqua => Get(KnownColor.Aqua); - - /// - /// Gets a with color. - /// - public static SolidBrush Aquamarine => Get(KnownColor.Aquamarine); - - /// - /// Gets a with color. - /// - public static SolidBrush Azure => Get(KnownColor.Azure); - - /// - /// Gets a with color. - /// - public static SolidBrush Beige => Get(KnownColor.Beige); - - /// - /// Gets a with color. - /// - public static SolidBrush Bisque => Get(KnownColor.Bisque); - - /// - /// Gets a with color. - /// - public static SolidBrush Black => Get(KnownColor.Black); - - /// - /// Gets a with color. - /// - public static SolidBrush BlanchedAlmond => Get(KnownColor.BlanchedAlmond); - - /// - /// Gets a with color. - /// - public static SolidBrush Blue => Get(KnownColor.Blue); - - /// - /// Gets a with color. - /// - public static SolidBrush BlueViolet => Get(KnownColor.BlueViolet); - - /// - /// Gets a with color. - /// - public static SolidBrush Brown => Get(KnownColor.Brown); - - /// - /// Gets a with color. - /// - public static SolidBrush BurlyWood => Get(KnownColor.BurlyWood); - - /// - /// Gets a with color. - /// - public static SolidBrush CadetBlue => Get(KnownColor.CadetBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush Chartreuse => Get(KnownColor.Chartreuse); - - /// - /// Gets a with color. - /// - public static SolidBrush Chocolate => Get(KnownColor.Chocolate); - - /// - /// Gets a with color. - /// - public static SolidBrush Coral => Get(KnownColor.Coral); - - /// - /// Gets a with color. - /// - public static SolidBrush CornflowerBlue => Get(KnownColor.CornflowerBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush Cornsilk => Get(KnownColor.Cornsilk); - - /// - /// Gets a with color. - /// - public static SolidBrush Crimson => Get(KnownColor.Crimson); - - /// - /// Gets a with color. - /// - public static SolidBrush Cyan => Get(KnownColor.Cyan); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkBlue => Get(KnownColor.DarkBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkCyan => Get(KnownColor.DarkCyan); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkGoldenrod => Get(KnownColor.DarkGoldenrod); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkGray => Get(KnownColor.DarkGray); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkGreen => Get(KnownColor.DarkGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkKhaki => Get(KnownColor.DarkKhaki); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkMagenta => Get(KnownColor.DarkMagenta); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkOliveGreen => Get(KnownColor.DarkOliveGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkOrange => Get(KnownColor.DarkOrange); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkOrchid => Get(KnownColor.DarkOrchid); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkRed => Get(KnownColor.DarkRed); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkSalmon => Get(KnownColor.DarkSalmon); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkSeaGreen => Get(KnownColor.DarkSeaGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkSlateBlue => Get(KnownColor.DarkSlateBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkSlateGray => Get(KnownColor.DarkSlateGray); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkTurquoise => Get(KnownColor.DarkTurquoise); - - /// - /// Gets a with color. - /// - public static SolidBrush DarkViolet => Get(KnownColor.DarkViolet); - - /// - /// Gets a with color. - /// - public static SolidBrush DeepPink => Get(KnownColor.DeepPink); - - /// - /// Gets a with color. - /// - public static SolidBrush DeepSkyBlue => Get(KnownColor.DeepSkyBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush DimGray => Get(KnownColor.DimGray); - - /// - /// Gets a with color. - /// - public static SolidBrush DodgerBlue => Get(KnownColor.DodgerBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush Firebrick => Get(KnownColor.Firebrick); - - /// - /// Gets a with color. - /// - public static SolidBrush FloralWhite => Get(KnownColor.FloralWhite); - - /// - /// Gets a with color. - /// - public static SolidBrush ForestGreen => Get(KnownColor.ForestGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush Fuchsia => Get(KnownColor.Fuchsia); - - /// - /// Gets a with color. - /// - public static SolidBrush Gainsboro => Get(KnownColor.Gainsboro); - - /// - /// Gets a with color. - /// - public static SolidBrush GhostWhite => Get(KnownColor.GhostWhite); - - /// - /// Gets a with color. - /// - public static SolidBrush Gold => Get(KnownColor.Gold); - - /// - /// Gets a with color. - /// - public static SolidBrush Goldenrod => Get(KnownColor.Goldenrod); - - /// - /// Gets a with color. - /// - public static SolidBrush Gray => Get(KnownColor.Gray); - - /// - /// Gets a with color. - /// - public static SolidBrush Green => Get(KnownColor.Green); - - /// - /// Gets a with color. - /// - public static SolidBrush GreenYellow => Get(KnownColor.GreenYellow); - - /// - /// Gets a with color. - /// - public static SolidBrush Honeydew => Get(KnownColor.Honeydew); - - /// - /// Gets a with color. - /// - public static SolidBrush HotPink => Get(KnownColor.HotPink); - - /// - /// Gets a with color. - /// - public static SolidBrush IndianRed => Get(KnownColor.IndianRed); - - /// - /// Gets a with color. - /// - public static SolidBrush Indigo => Get(KnownColor.Indigo); - - /// - /// Gets a with color. - /// - public static SolidBrush Ivory => Get(KnownColor.Ivory); - - /// - /// Gets a with color. - /// - public static SolidBrush Khaki => Get(KnownColor.Khaki); - - /// - /// Gets a with color. - /// - public static SolidBrush Lavender => Get(KnownColor.Lavender); - - /// - /// Gets a with color. - /// - public static SolidBrush LavenderBlush => Get(KnownColor.LavenderBlush); - - /// - /// Gets a with color. - /// - public static SolidBrush LawnGreen => Get(KnownColor.LawnGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush LemonChiffon => Get(KnownColor.LemonChiffon); - - /// - /// Gets a with color. - /// - public static SolidBrush LightBlue => Get(KnownColor.LightBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush LightCoral => Get(KnownColor.LightCoral); - - /// - /// Gets a with color. - /// - public static SolidBrush LightCyan => Get(KnownColor.LightCyan); - - /// - /// Gets a with color. - /// - public static SolidBrush LightGoldenrodYellow => Get(KnownColor.LightGoldenrodYellow); - - /// - /// Gets a with color. - /// - public static SolidBrush LightGray => Get(KnownColor.LightGray); - - /// - /// Gets a with color. - /// - public static SolidBrush LightGreen => Get(KnownColor.LightGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush LightPink => Get(KnownColor.LightPink); - - /// - /// Gets a with color. - /// - public static SolidBrush LightSalmon => Get(KnownColor.LightSalmon); - - /// - /// Gets a with color. - /// - public static SolidBrush LightSeaGreen => Get(KnownColor.LightSeaGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush LightSkyBlue => Get(KnownColor.LightSkyBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush LightSlateGray => Get(KnownColor.LightSlateGray); - - /// - /// Gets a with color. - /// - public static SolidBrush LightSteelBlue => Get(KnownColor.LightSteelBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush LightYellow => Get(KnownColor.LightYellow); - - /// - /// Gets a with color. - /// - public static SolidBrush Lime => Get(KnownColor.Lime); - - /// - /// Gets a with color. - /// - public static SolidBrush LimeGreen => Get(KnownColor.LimeGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush Linen => Get(KnownColor.Linen); - - /// - /// Gets a with color. - /// - public static SolidBrush Magenta => Get(KnownColor.Magenta); - - /// - /// Gets a with color. - /// - public static SolidBrush Maroon => Get(KnownColor.Maroon); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumAquamarine => Get(KnownColor.MediumAquamarine); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumBlue => Get(KnownColor.MediumBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumOrchid => Get(KnownColor.MediumOrchid); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumPurple => Get(KnownColor.MediumPurple); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumSeaGreen => Get(KnownColor.MediumSeaGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumSlateBlue => Get(KnownColor.MediumSlateBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumSpringGreen => Get(KnownColor.MediumSpringGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumTurquoise => Get(KnownColor.MediumTurquoise); - - /// - /// Gets a with color. - /// - public static SolidBrush MediumVioletRed => Get(KnownColor.MediumVioletRed); - - /// - /// Gets a with color. - /// - public static SolidBrush MidnightBlue => Get(KnownColor.MidnightBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush MintCream => Get(KnownColor.MintCream); - - /// - /// Gets a with color. - /// - public static SolidBrush MistyRose => Get(KnownColor.MistyRose); - - /// - /// Gets a with color. - /// - public static SolidBrush Moccasin => Get(KnownColor.Moccasin); - - /// - /// Gets a with color. - /// - public static SolidBrush NavajoWhite => Get(KnownColor.NavajoWhite); - - /// - /// Gets a with color. - /// - public static SolidBrush Navy => Get(KnownColor.Navy); - - /// - /// Gets a with color. - /// - public static SolidBrush OldLace => Get(KnownColor.OldLace); - - /// - /// Gets a with color. - /// - public static SolidBrush Olive => Get(KnownColor.Olive); - - /// - /// Gets a with color. - /// - public static SolidBrush OliveDrab => Get(KnownColor.OliveDrab); - - /// - /// Gets a with color. - /// - public static SolidBrush Orange => Get(KnownColor.Orange); - - /// - /// Gets a with color. - /// - public static SolidBrush OrangeRed => Get(KnownColor.OrangeRed); - - /// - /// Gets a with color. - /// - public static SolidBrush Orchid => Get(KnownColor.Orchid); - - /// - /// Gets a with color. - /// - public static SolidBrush PaleGoldenrod => Get(KnownColor.PaleGoldenrod); - - /// - /// Gets a with color. - /// - public static SolidBrush PaleGreen => Get(KnownColor.PaleGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush PaleTurquoise => Get(KnownColor.PaleTurquoise); - - /// - /// Gets a with color. - /// - public static SolidBrush PaleVioletRed => Get(KnownColor.PaleVioletRed); - - /// - /// Gets a with color. - /// - public static SolidBrush PapayaWhip => Get(KnownColor.PapayaWhip); - - /// - /// Gets a with color. - /// - public static SolidBrush PeachPuff => Get(KnownColor.PeachPuff); - - /// - /// Gets a with color. - /// - public static SolidBrush Peru => Get(KnownColor.Peru); - - /// - /// Gets a with color. - /// - public static SolidBrush Pink => Get(KnownColor.Pink); - - /// - /// Gets a with color. - /// - public static SolidBrush Plum => Get(KnownColor.Plum); - - /// - /// Gets a with color. - /// - public static SolidBrush PowderBlue => Get(KnownColor.PowderBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush Purple => Get(KnownColor.Purple); - - /// - /// Gets a with color. - /// - public static SolidBrush Red => Get(KnownColor.Red); - - /// - /// Gets a with color. - /// - public static SolidBrush RosyBrown => Get(KnownColor.RosyBrown); - - /// - /// Gets a with color. - /// - public static SolidBrush RoyalBlue => Get(KnownColor.RoyalBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush SaddleBrown => Get(KnownColor.SaddleBrown); - - /// - /// Gets a with color. - /// - public static SolidBrush Salmon => Get(KnownColor.Salmon); - - /// - /// Gets a with color. - /// - public static SolidBrush SandyBrown => Get(KnownColor.SandyBrown); - - /// - /// Gets a with color. - /// - public static SolidBrush SeaGreen => Get(KnownColor.SeaGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush SeaShell => Get(KnownColor.SeaShell); - - /// - /// Gets a with color. - /// - public static SolidBrush Sienna => Get(KnownColor.Sienna); - - /// - /// Gets a with color. - /// - public static SolidBrush Silver => Get(KnownColor.Silver); - - /// - /// Gets a with color. - /// - public static SolidBrush SkyBlue => Get(KnownColor.SkyBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush SlateBlue => Get(KnownColor.SlateBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush SlateGray => Get(KnownColor.SlateGray); - - /// - /// Gets a with color. - /// - public static SolidBrush Snow => Get(KnownColor.Snow); - - /// - /// Gets a with color. - /// - public static SolidBrush SpringGreen => Get(KnownColor.SpringGreen); - - /// - /// Gets a with color. - /// - public static SolidBrush SteelBlue => Get(KnownColor.SteelBlue); - - /// - /// Gets a with color. - /// - public static SolidBrush Tan => Get(KnownColor.Tan); - - /// - /// Gets a with color. - /// - public static SolidBrush Teal => Get(KnownColor.Teal); - - /// - /// Gets a with color. - /// - public static SolidBrush Thistle => Get(KnownColor.Thistle); - - /// - /// Gets a with color. - /// - public static SolidBrush Tomato => Get(KnownColor.Tomato); - - /// - /// Gets a with color. - /// - public static SolidBrush Turquoise => Get(KnownColor.Turquoise); - - /// - /// Gets a with color. - /// - public static SolidBrush Violet => Get(KnownColor.Violet); - - /// - /// Gets a with color. - /// - public static SolidBrush Wheat => Get(KnownColor.Wheat); - - /// - /// Gets a with color. - /// - public static SolidBrush White => Get(KnownColor.White); - - /// - /// Gets a with color. - /// - public static SolidBrush WhiteSmoke => Get(KnownColor.WhiteSmoke); - - /// - /// Gets a with color. - /// - public static SolidBrush Yellow => Get(KnownColor.Yellow); - - /// - /// Gets a with color. - /// - public static SolidBrush YellowGreen => Get(KnownColor.YellowGreen); - } -} diff --git a/src/MiniPdf/Drawing/Brushes/SolidBrush.cs b/src/MiniPdf/Drawing/Brushes/SolidBrush.cs deleted file mode 100644 index 9f718bfb..00000000 --- a/src/MiniPdf/Drawing/Brushes/SolidBrush.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Brushes -{ - /// - /// Defines a brush of a single color. - /// - /// - /// A is the simplest brush that fills shapes with a solid color. - /// It is commonly used for drawing filled rectangles, ellipses, and other shapes. - /// - public sealed class SolidBrush : Brush - { - private Color _color; - - /// - /// Initializes a new object of the specified color. - /// - /// The color of the brush. - public SolidBrush(Color color) - { - _color = color; - } - - /// - /// Gets or sets the color of this brush. - /// - public Color Color - { - get - { - CheckDisposed(); - return _color; - } - set - { - CheckDisposed(); - _color = value; - } - } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same color. - public override Brush Clone() => new SolidBrush(_color); - } -} diff --git a/src/MiniPdf/Drawing/Brushes/TextureBrush.cs b/src/MiniPdf/Drawing/Brushes/TextureBrush.cs deleted file mode 100644 index 59201ac5..00000000 --- a/src/MiniPdf/Drawing/Brushes/TextureBrush.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Brushes -{ - /// - /// Fills the interior of a shape with an image, optionally tiling/wrapping it. - /// - public sealed class TextureBrush : Brush - { - private Image _image; - private WrapMode _wrapMode; - private Matrix _transform; - - // ── Constructors ──────────────────────────────────────────────────────── - - /// - /// Initializes a new with the specified image and default wrap mode. - /// - /// The image to fill the brush with. - public TextureBrush(Image image) - : this(image, WrapMode.Tile) { } - - /// - /// Initializes a new with the specified image and wrap mode. - /// - /// The image to fill the brush with. - /// The wrap mode specifying how the image is tiled. - public TextureBrush(Image image, WrapMode wrapMode) - { - _image = image ?? throw new ArgumentNullException(nameof(image)); - _wrapMode = wrapMode; - _transform = new Matrix(); - } - - /// - /// Initializes a new with the specified image and destination rectangle. - /// - /// The image to fill the brush with. - /// The destination rectangle. - public TextureBrush(Image image, RectangleF dstRect) - : this(image, WrapMode.Tile) { } - - /// - /// Initializes a new with the specified image, destination rectangle, and image attributes. - /// - /// The image to fill the brush with. - /// The destination rectangle. - /// The image attributes. - public TextureBrush(Image image, RectangleF dstRect, Drawing2D.ImageAttributes? imageAttrs) - : this(image, WrapMode.Tile) { } - - // ── Properties ────────────────────────────────────────────────────────── - - /// - /// Gets the image associated with this . - /// - public Image Image => _image; - - /// - /// Gets or sets the wrap mode for tiling the image. - /// - public WrapMode WrapMode - { - get => _wrapMode; - set => _wrapMode = value; - } - - /// - /// Gets or sets the transformation matrix for the brush. - /// - public Matrix Transform - { - get => _transform; - set => _transform = value ?? throw new ArgumentNullException(nameof(value)); - } - - // ── Transform helpers ──────────────────────────────────────────────────── - - /// - /// Resets the transformation matrix to the identity matrix. - /// - public void ResetTransform() => _transform.Reset(); - - /// - /// Multiplies the transformation matrix by the specified matrix. - /// - /// The matrix to multiply. - /// The order of multiplication (prepend or append). - public void MultiplyTransform(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Multiply(matrix, order); - - /// - /// Rotates the transformation matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Rotate(angle, order); - - /// - /// Scales the transformation matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Scale(sx, sy, order); - - /// - /// Translates the transformation matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Translate(dx, dy, order); - - // ── Clone / Dispose ────────────────────────────────────────────────────── - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public override Brush Clone() - => new TextureBrush(_image, _wrapMode) - { - _transform = (Matrix)_transform.Clone(), - }; - - /// - /// Releases the unmanaged resources used by the . - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected override void Dispose(bool disposing) { } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/BmpCodec.cs b/src/MiniPdf/Drawing/Codecs/BmpCodec.cs deleted file mode 100644 index 23f9afb2..00000000 --- a/src/MiniPdf/Drawing/Codecs/BmpCodec.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// BMP / DIB codec (native, no third-party library). - internal sealed class BmpCodec : IImageCodec - { - public bool CanDecode(byte[] header) - => header.Length >= 2 && header[0] == (byte)'B' && header[1] == (byte)'M'; - - public Bitmap Decode(Stream stream) - { - using var br = new BinaryReader(stream, System.Text.Encoding.UTF8, leaveOpen: true); - - // File header (14 bytes) - br.ReadByte(); br.ReadByte(); // 'B','M' - br.ReadUInt32(); // file size - br.ReadUInt16(); br.ReadUInt16(); // reserved - br.ReadUInt32(); // pixelOffset (unused — we rely on sequential read) - - // DIB header (BITMAPINFOHEADER, 40 bytes minimum) - uint headerSize = br.ReadUInt32(); - int width = br.ReadInt32(); - int height = br.ReadInt32(); - bool topDown = height < 0; - if (topDown) height = -height; - - br.ReadUInt16(); // planes - ushort bpp = br.ReadUInt16(); - uint compression = br.ReadUInt32(); - br.ReadUInt32(); // image size - int xPPM = br.ReadInt32(); - int yPPM = br.ReadInt32(); - br.ReadUInt32(); br.ReadUInt32(); // clrUsed, clrImportant - - // Skip any extra header bytes - int extra = (int)headerSize - 40; - if (extra > 0) br.ReadBytes(extra); - - float dpiX = xPPM > 0 ? xPPM * 0.0254f : 96f; - float dpiY = yPPM > 0 ? yPPM * 0.0254f : 96f; - - var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); - bmp._dpiX = dpiX; - bmp._dpiY = dpiY; - bmp._rawFormat = ImageFormat.Bmp; - - int srcBpp = bpp / 8; - int srcStride = ((width * bpp + 31) / 32) * 4; - var rowBuf = new byte[srcStride]; - - for (int yi = 0; yi < height; yi++) - { - int dstY = topDown ? yi : height - 1 - yi; - int read = br.Read(rowBuf, 0, srcStride); - if (read < srcStride && read > 0) - Array.Clear(rowBuf, read, srcStride - read); - - int dstBase = dstY * bmp._stride; - for (int x = 0; x < width; x++) - { - int srcOff = x * srcBpp; - int dstOff = dstBase + x * 4; - bmp._pixels[dstOff] = rowBuf[srcOff]; - bmp._pixels[dstOff + 1] = rowBuf[srcOff + 1]; - bmp._pixels[dstOff + 2] = rowBuf[srcOff + 2]; - bmp._pixels[dstOff + 3] = srcBpp >= 4 ? rowBuf[srcOff + 3] : (byte)255; - } - } - - return bmp; - } - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - int bpp = (bmp._format == PixelFormat.Format32bppArgb - || bmp._format == PixelFormat.Format32bppRgb - || bmp._format == PixelFormat.Format32bppPArgb) ? 32 : 24; - int rowBytes = ((bmp._width * bpp + 31) / 32) * 4; - int dataSize = rowBytes * bmp._height; - - using var bw = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true); - - // File header (14 bytes) - bw.Write((byte)'B'); bw.Write((byte)'M'); - bw.Write((uint)(54 + dataSize)); - bw.Write((ushort)0); bw.Write((ushort)0); - bw.Write((uint)54); - - // DIB header – BITMAPINFOHEADER (40 bytes) - bw.Write((uint)40); - bw.Write((int)bmp._width); - bw.Write((int)bmp._height); // positive = bottom-up - bw.Write((ushort)1); // color planes - bw.Write((ushort)bpp); - bw.Write((uint)0); // BI_RGB - bw.Write((uint)0); // image size (0 for BI_RGB) - bw.Write((int)Math.Round(bmp._dpiX / 0.0254)); - bw.Write((int)Math.Round(bmp._dpiY / 0.0254)); - bw.Write((uint)0); - bw.Write((uint)0); - - // Pixel data – BMP stores rows bottom-up - int srcBpp = Bitmap.GetBytesPerPixel(bmp._format); - int dstBpp = bpp / 8; - var rowBuf = new byte[rowBytes]; - - for (int yi = bmp._height - 1; yi >= 0; yi--) - { - int srcBase = yi * bmp._stride; - for (int x = 0; x < bmp._width; x++) - { - int srcOff = srcBase + x * srcBpp; - int dstOff = x * dstBpp; - rowBuf[dstOff] = bmp._pixels[srcOff]; - rowBuf[dstOff + 1] = bmp._pixels[srcOff + 1]; - rowBuf[dstOff + 2] = bmp._pixels[srcOff + 2]; - if (dstBpp == 4) - rowBuf[dstOff + 3] = srcBpp >= 4 ? bmp._pixels[srcOff + 3] : (byte)255; - } - for (int p = bmp._width * dstBpp; p < rowBytes; p++) rowBuf[p] = 0; - bw.Write(rowBuf, 0, rowBytes); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/CodecRegistry.cs b/src/MiniPdf/Drawing/Codecs/CodecRegistry.cs deleted file mode 100644 index f50e4f05..00000000 --- a/src/MiniPdf/Drawing/Codecs/CodecRegistry.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// - /// Central registry that routes encode/decode operations to the appropriate codec. - /// - internal static class CodecRegistry - { - private static readonly IImageCodec[] Codecs = - { - new BmpCodec(), - new PngCodec(), - new GifCodec(), - new JpegCodec(), - new TiffCodec(), - new IcoCodec(), - new EmfCodec(), - }; - - // ─── Decode ────────────────────────────────────────────────────────────── - - public static Bitmap Decode(Stream stream) - { - // Ensure seekable - Stream seekable; - bool ownStream = false; - if (!stream.CanSeek) - { - var ms = new MemoryStream(); - stream.CopyTo(ms); - ms.Position = 0; - seekable = ms; - ownStream = true; - } - else - { - seekable = stream; - } - - try - { - var header = new byte[12]; - int n = seekable.Read(header, 0, 12); - seekable.Seek(-n, SeekOrigin.Current); - - foreach (var codec in Codecs) - { - if (codec.CanDecode(header)) - return codec.Decode(seekable); - } - - throw new NotSupportedException("Unknown or unsupported image format."); - } - finally - { - if (ownStream) seekable.Dispose(); - } - } - - // ─── Encode ────────────────────────────────────────────────────────────── - - public static void Encode(Bitmap bmp, Stream stream, ImageFormat format, - EncoderParameters? parameters) - { - var codec = FindEncoder(format); - if (codec == null) - throw new NotSupportedException($"No encoder found for format {format?.Name}."); - codec.Encode(bmp, stream, parameters); - } - - private static IImageCodec? FindEncoder(ImageFormat? format) - { - if (format == null) return null; - if (format.Equals(ImageFormat.Bmp) || format.Equals(ImageFormat.MemoryBmp)) - return Codecs[0]; // BmpCodec - if (format.Equals(ImageFormat.Png)) return Codecs[1]; // PngCodec - if (format.Equals(ImageFormat.Gif)) return Codecs[2]; // GifCodec - if (format.Equals(ImageFormat.Jpeg)) return Codecs[3]; // JpegCodec - if (format.Equals(ImageFormat.Tiff)) return Codecs[4]; // TiffCodec - return null; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/EmfCodec.cs b/src/MiniPdf/Drawing/Codecs/EmfCodec.cs deleted file mode 100644 index 9acc0950..00000000 --- a/src/MiniPdf/Drawing/Codecs/EmfCodec.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// EMF/WMF decoder backed by the MiniSoftware.Drawing metafile parser and playback engine. - internal sealed class EmfCodec : IImageCodec - { - public bool CanDecode(byte[] header) - => LooksLikeEmf(header) || LooksLikePlaceableWmf(header) || LooksLikeStandardWmf(header); - - public Bitmap Decode(Stream stream) - { - using var metafile = new MiniSoftware.Drawing.Imaging.Metafile(stream); - return metafile.RenderToBitmap(); - } - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - => throw new NotSupportedException("EMF encoding is not supported."); - - private static bool LooksLikeEmf(byte[] header) - => header.Length >= 4 - && header[0] == 0x01 && header[1] == 0x00 && header[2] == 0x00 && header[3] == 0x00; - - private static bool LooksLikePlaceableWmf(byte[] header) - => header.Length >= 4 - && header[0] == 0xD7 && header[1] == 0xCD && header[2] == 0xC6 && header[3] == 0x9A; - - private static bool LooksLikeStandardWmf(byte[] header) - => header.Length >= 6 - && (header[0] == 0x01 || header[0] == 0x02) - && header[1] == 0x00 - && header[2] == 0x09 - && header[3] == 0x00 - && header[4] == 0x00 - && (header[5] == 0x01 || header[5] == 0x03); - } -} diff --git a/src/MiniPdf/Drawing/Codecs/GifCodec.cs b/src/MiniPdf/Drawing/Codecs/GifCodec.cs deleted file mode 100644 index 6dc22983..00000000 --- a/src/MiniPdf/Drawing/Codecs/GifCodec.cs +++ /dev/null @@ -1,468 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// - /// GIF87a / GIF89a codec — reads first frame; writes indexed colour with LZW. - /// - internal sealed class GifCodec : IImageCodec - { - public bool CanDecode(byte[] header) - => header.Length >= 6 - && header[0] == 'G' && header[1] == 'I' && header[2] == 'F' - && header[3] == '8' && (header[4] == '7' || header[4] == '9') && header[5] == 'a'; - - // ─── Decode ────────────────────────────────────────────────────────────── - - public Bitmap Decode(Stream stream) - { - var data = ReadAll(stream); - int pos = 0; - - // Header (6 bytes) - pos += 6; - - // Logical Screen Descriptor (7 bytes) - int canvasW = data[pos] | (data[pos+1] << 8); pos += 2; - int canvasH = data[pos] | (data[pos+1] << 8); pos += 2; - byte packed = data[pos++]; - bool hasGct = (packed & 0x80) != 0; - int gctSz = hasGct ? 2 << (packed & 0x07) : 0; - /*bgIndex*/ pos++; // background colour index - /*aspect*/ pos++; // aspect ratio - - // Global Colour Table - byte[]? gct = null; - if (hasGct) - { - gct = new byte[gctSz * 3]; - Buffer.BlockCopy(data, pos, gct, 0, gct.Length); - pos += gct.Length; - } - - // GCE fields (set by Graphic Control Extension) - bool transpFlag = false; - int transpIndex = 0; - - // Parse blocks until we find the first image - while (pos < data.Length) - { - byte blockId = data[pos++]; - - if (blockId == 0x3B) break; // trailer - - if (blockId == 0x21) // extension - { - byte extLabel = data[pos++]; - if (extLabel == 0xF9 && pos + 1 < data.Length) // Graphic Control Extension - { - int bsize = data[pos++]; - if (bsize >= 4) - { - byte gceFlags = data[pos]; - transpFlag = (gceFlags & 1) != 0; - transpIndex = data[pos + 3]; - } - } - // Skip sub-blocks - pos = SkipSubBlocks(data, pos); - continue; - } - - if (blockId == 0x2C) // image descriptor - { - int imgLeft = data[pos] | (data[pos+1] << 8); pos += 2; - int imgTop = data[pos] | (data[pos+1] << 8); pos += 2; - int imgW = data[pos] | (data[pos+1] << 8); pos += 2; - int imgH = data[pos] | (data[pos+1] << 8); pos += 2; - byte imgPacked = data[pos++]; - bool hasLct = (imgPacked & 0x80) != 0; - int lctSz = hasLct ? 2 << (imgPacked & 0x07) : 0; - - byte[]? lct = null; - if (hasLct) - { - lct = new byte[lctSz * 3]; - Buffer.BlockCopy(data, pos, lct, 0, lct.Length); - pos += lct.Length; - } - - byte[] palette = lct ?? gct ?? new byte[0]; - - int minCodeSize = data[pos++]; - byte[] lzwData = ReadSubBlocks(data, ref pos); - - // Decompress LZW - var indices = LzwDecode(lzwData, minCodeSize); - - // Build bitmap - int bmpW = canvasW > 0 ? canvasW : imgW; - int bmpH = canvasH > 0 ? canvasH : imgH; - var bmp = new Bitmap(bmpW, bmpH, PixelFormat.Format32bppArgb); - bmp._rawFormat = ImageFormat.Gif; - - for (int y = 0; y < imgH && y < bmpH; y++) - for (int x = 0; x < imgW && x < bmpW; x++) - { - int idx = (y * imgW + x < indices.Length) ? indices[y * imgW + x] : 0; - byte r = 0, g = 0, b = 0; - if (idx * 3 + 2 < palette.Length) - { r = palette[idx*3]; g = palette[idx*3+1]; b = palette[idx*3+2]; } - byte a = (transpFlag && idx == transpIndex) ? (byte)0 : (byte)255; - int off = (imgTop + y) * bmp._stride + (imgLeft + x) * 4; - if (off + 3 < bmp._pixels.Length) - { bmp._pixels[off]=b; bmp._pixels[off+1]=g; bmp._pixels[off+2]=r; bmp._pixels[off+3]=a; } - } - - return bmp; - } - - // Unknown block — try to skip - pos = SkipSubBlocks(data, pos); - } - - throw new InvalidDataException("No image frame found in GIF."); - } - - // ─── Encode ────────────────────────────────────────────────────────────── - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - // Collect unique colours - var colorMap = new Dictionary(); - var colors = new List<(byte r, byte g, byte b)>(); - bool hasTransp = false; - int transpIdx = -1; - - for (int y = 0; y < bmp._height; y++) - for (int x = 0; x < bmp._width; x++) - { - var c = bmp.GetPixel(x, y); - if (c.A < 128) { hasTransp = true; continue; } - int key = (c.R << 16) | (c.G << 8) | c.B; - if (!colorMap.ContainsKey(key)) - { - colorMap[key] = colors.Count; - colors.Add((c.R, c.G, c.B)); - } - } - - // If image is entirely transparent, add one dummy colour - if (colors.Count == 0) colors.Add((0, 0, 0)); - - // Reserve a slot for transparency if needed - if (hasTransp) - { - transpIdx = colors.Count; - colors.Add((0, 0, 0)); - } - - // Quantize to ≤ 256 colours if necessary - if (colors.Count > 256) - { - colors = colors.GetRange(0, hasTransp ? 255 : 256); - if (hasTransp) { transpIdx = 255; colors.Add((0, 0, 0)); } - // Rebuild colorMap - colorMap.Clear(); - for (int i = 0; i < colors.Count - (hasTransp ? 1 : 0); i++) - { - var (r2, g2, b2) = colors[i]; - colorMap[(r2 << 16) | (g2 << 8) | b2] = i; - } - } - - int numColors = colors.Count; - - // GCT size: smallest power-of-2 that fits - int gctPow = 0; - int tableSize = 2; - while (tableSize < numColors && gctPow < 7) { gctPow++; tableSize *= 2; } - - int minCodeSize = Math.Max(2, gctPow + 1); - - // Build index array - var indices = new byte[bmp._width * bmp._height]; - for (int y = 0; y < bmp._height; y++) - for (int x = 0; x < bmp._width; x++) - { - var c = bmp.GetPixel(x, y); - if (c.A < 128) - { indices[y * bmp._width + x] = (byte)(transpIdx >= 0 ? transpIdx : 0); } - else - { - int key = (c.R << 16) | (c.G << 8) | c.B; - indices[y * bmp._width + x] = colorMap.TryGetValue(key, out int idx) - ? (byte)idx : (byte)0; - } - } - - byte[] lzwData = LzwEncode(indices, minCodeSize); - - // ── Write GIF ──────────────────────────────────────────────────────── - var w = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true); - - // Header - stream.Write(System.Text.Encoding.ASCII.GetBytes("GIF89a"), 0, 6); - - // Logical Screen Descriptor - w.Write((ushort)bmp._width); - w.Write((ushort)bmp._height); - byte lsdPacked = (byte)(0x80 | (gctPow & 7) | ((gctPow & 7) << 4)); - w.Write(lsdPacked); - w.Write((byte)0); // background index - w.Write((byte)0); // aspect ratio - - // Global Colour Table (padded to tableSize entries) - for (int i = 0; i < tableSize; i++) - { - if (i < colors.Count) { var (r2,g2,b2) = colors[i]; w.Write(r2); w.Write(g2); w.Write(b2); } - else { w.Write((byte)0); w.Write((byte)0); w.Write((byte)0); } - } - - // Graphic Control Extension (only if transparent) - if (hasTransp && transpIdx >= 0) - { - w.Write((byte)0x21); w.Write((byte)0xF9); w.Write((byte)4); - w.Write((byte)1); // transparent flag - w.Write((ushort)0); // delay - w.Write((byte)transpIdx); - w.Write((byte)0); // block terminator - } - - // Image Descriptor - w.Write((byte)0x2C); - w.Write((ushort)0); w.Write((ushort)0); // left, top - w.Write((ushort)bmp._width); - w.Write((ushort)bmp._height); - w.Write((byte)0); // no local colour table, not interlaced - - // LZW Minimum Code Size - w.Write((byte)minCodeSize); - - // LZW data in sub-blocks - WriteSubBlocks(stream, lzwData); - - // Trailer - w.Write((byte)0x3B); - } - - // ─── Private helpers ───────────────────────────────────────────────────── - - private static byte[] ReadAll(Stream stream) - { - using var ms = new MemoryStream(); - stream.CopyTo(ms); - return ms.ToArray(); - } - - private static int SkipSubBlocks(byte[] data, int pos) - { - while (pos < data.Length) - { - int sz = data[pos++]; - if (sz == 0) break; - pos += sz; - } - return pos; - } - - private static byte[] ReadSubBlocks(byte[] data, ref int pos) - { - var result = new List(); - while (pos < data.Length) - { - int sz = data[pos++]; - if (sz == 0) break; - for (int i = 0; i < sz && pos < data.Length; i++) - result.Add(data[pos++]); - } - return result.ToArray(); - } - - private static void WriteSubBlocks(Stream s, byte[] data) - { - int i = 0; - while (i < data.Length) - { - int sz = Math.Min(255, data.Length - i); - s.WriteByte((byte)sz); - s.Write(data, i, sz); - i += sz; - } - s.WriteByte(0); // block terminator - } - - // ── GIF LZW decoder (LSB-first bit stream) ──────────────────────────── - - private static int[] LzwDecode(byte[] data, int minCodeSize) - { - int clearCode = 1 << minCodeSize; - int eoiCode = clearCode + 1; - int codeSize = minCodeSize + 1; - int codeMask = (1 << codeSize) - 1; - - // String table: code → list of indices - var table = new List(); - - void InitTable() - { - table.Clear(); - for (int i = 0; i <= eoiCode; i++) - table.Add(i < clearCode ? new[] { i } : Array.Empty()); - codeSize = minCodeSize + 1; - codeMask = (1 << codeSize) - 1; - } - - InitTable(); - - var output = new List(); - int bitBuf = 0, bitsLeft = 0, dataPos = 0; - - int ReadCode() - { - while (bitsLeft < codeSize && dataPos < data.Length) - { - bitBuf |= data[dataPos++] << bitsLeft; - bitsLeft += 8; - } - int code = bitBuf & codeMask; - bitBuf >>= codeSize; - bitsLeft -= codeSize; - return code; - } - - int prevCode = -1; - - while (true) - { - int code = ReadCode(); - if (code == eoiCode) break; - - if (code == clearCode) - { - InitTable(); - prevCode = -1; - continue; - } - - int[] entry; - if (code < table.Count && table[code].Length > 0) - { - entry = table[code]; - } - else if (code == table.Count && prevCode >= 0) - { - // Special case: code == next available, entry = prev + prev[0] - var prev2 = table[prevCode]; - entry = new int[prev2.Length + 1]; - Buffer.BlockCopy(prev2, 0, entry, 0, prev2.Length * sizeof(int)); - entry[prev2.Length] = prev2[0]; - } - else - { - break; // corrupt stream - } - - foreach (var idx in entry) output.Add(idx); - - if (prevCode >= 0) - { - var prevEntry = table[prevCode]; - var newEntry = new int[prevEntry.Length + 1]; - Buffer.BlockCopy(prevEntry, 0, newEntry, 0, prevEntry.Length * sizeof(int)); - newEntry[prevEntry.Length] = entry[0]; - table.Add(newEntry); - - if (table.Count == (1 << codeSize) && codeSize < 12) - { - codeSize++; - codeMask = (1 << codeSize) - 1; - } - } - - prevCode = code; - } - - return output.ToArray(); - } - - // ── GIF LZW encoder (LSB-first bit stream) ──────────────────────────── - - private static byte[] LzwEncode(byte[] indices, int minCodeSize) - { - int clearCode = 1 << minCodeSize; - int eoiCode = clearCode + 1; - - var output = new List(); - int bitBuf = 0, bitsLeft = 0; - int codeSize = minCodeSize + 1; - int nextCode = eoiCode + 1; - var dict = new Dictionary<(int prefix, byte suffix), int>(); - - void Flush() - { - while (bitsLeft >= 8) { output.Add((byte)(bitBuf & 0xFF)); bitBuf >>= 8; bitsLeft -= 8; } - } - - void EmitCode(int code) - { - bitBuf |= code << bitsLeft; - bitsLeft += codeSize; - Flush(); - } - - void Reset() - { - dict.Clear(); - nextCode = eoiCode + 1; - codeSize = minCodeSize + 1; - } - - EmitCode(clearCode); - - if (indices.Length == 0) - { - EmitCode(eoiCode); - if (bitsLeft > 0) { output.Add((byte)(bitBuf & 0xFF)); } - return output.ToArray(); - } - - int cur = indices[0]; - - for (int i = 1; i < indices.Length; i++) - { - byte b = indices[i]; - if (dict.TryGetValue((cur, b), out int next)) - { - cur = next; - } - else - { - EmitCode(cur); - if (nextCode < 4096) - { - dict[(cur, b)] = nextCode++; - if (nextCode > (1 << codeSize) && codeSize < 12) - codeSize++; - } - else - { - EmitCode(clearCode); - Reset(); - } - cur = b; - } - } - - EmitCode(cur); - EmitCode(eoiCode); - if (bitsLeft > 0) { output.Add((byte)(bitBuf & 0xFF)); } - - return output.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/IImageCodec.cs b/src/MiniPdf/Drawing/Codecs/IImageCodec.cs deleted file mode 100644 index de4f885e..00000000 --- a/src/MiniPdf/Drawing/Codecs/IImageCodec.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// - /// Contract for a single image format encoder/decoder. - /// CanDecode receives the first 12 bytes of the stream; the stream position - /// is never changed by this call. - /// - internal interface IImageCodec - { - /// Returns true if the supplied magic bytes identify this format. - bool CanDecode(byte[] header); - - /// Decode a complete image stream, returning a Bitmap. - Bitmap Decode(Stream stream); - - /// Encode into . - void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters); - } -} diff --git a/src/MiniPdf/Drawing/Codecs/IcoCodec.cs b/src/MiniPdf/Drawing/Codecs/IcoCodec.cs deleted file mode 100644 index bddcbc91..00000000 --- a/src/MiniPdf/Drawing/Codecs/IcoCodec.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// ICO codec — decode only; selects the largest frame. - internal sealed class IcoCodec : IImageCodec - { - private static readonly byte[] PngSig = { 137, 80, 78, 71, 13, 10, 26, 10 }; - - public bool CanDecode(byte[] header) - => header.Length >= 4 - && header[0] == 0 && header[1] == 0 - && header[2] == 1 && header[3] == 0; - - // ─── Decode ────────────────────────────────────────────────────────────── - - public Bitmap Decode(Stream stream) - { - byte[] file = ReadAll(stream); - - // ICONDIR - int count = file[4] | (file[5] << 8); - if (count == 0) throw new InvalidDataException("ICO contains no images."); - - // Pick best entry: largest area, then highest bit-depth - int bestIdx = 0, bestArea = -1, bestBpp = -1; - for (int i = 0; i < count; i++) - { - int e = 6 + i * 16; - int fw = file[e] == 0 ? 256 : file[e]; - int fh = file[e + 1] == 0 ? 256 : file[e + 1]; - int bpp = file[e + 6] | (file[e + 7] << 8); - int area = fw * fh; - if (area > bestArea || (area == bestArea && bpp > bestBpp)) - { bestArea = area; bestBpp = bpp; bestIdx = i; } - } - - int dirEntry = 6 + bestIdx * 16; - int imgW = file[dirEntry] == 0 ? 256 : file[dirEntry]; - int imgH = file[dirEntry + 1] == 0 ? 256 : file[dirEntry + 1]; - int imgBpp = file[dirEntry + 6] | (file[dirEntry + 7] << 8); - int imgOff = file[dirEntry + 12] | (file[dirEntry + 13] << 8) - | (file[dirEntry + 14] << 16) | (file[dirEntry + 15] << 24); - - // Check if the image data is a PNG - bool isPng = imgOff + 8 <= file.Length; - if (isPng) - { - for (int i = 0; i < 8; i++) - if (file[imgOff + i] != PngSig[i]) { isPng = false; break; } - } - - if (isPng) - { - using var ms = new MemoryStream(file, imgOff, file.Length - imgOff); - return new PngCodec().Decode(ms); - } - - // Parse BMP DIB header (no BM file-header in ICO) - int dibSize = file[imgOff] | (file[imgOff+1] << 8) - | (file[imgOff+2] << 16) | (file[imgOff+3] << 24); - int dibW = file[imgOff+4] | (file[imgOff+5] << 8) - | (file[imgOff+6] << 16) | (file[imgOff+7] << 24); - int rawH = file[imgOff+8] | (file[imgOff+9] << 8) - | (file[imgOff+10]<< 16) | (file[imgOff+11]<< 24); - int actualH = Math.Abs(rawH / 2); // ICO height is doubled - int dibBpp = file[imgOff+14] | (file[imgOff+15] << 8); - if (dibBpp == 0) dibBpp = imgBpp; - - int xorOff = imgOff + dibSize; - int srcBpp = dibBpp / 8; - int xorStride = ((dibW * dibBpp + 31) / 32) * 4; - int andStride = ((dibW * 1 + 31) / 32) * 4; - int andOff = xorOff + xorStride * actualH; - - var bmp = new Bitmap(dibW, actualH, PixelFormat.Format32bppArgb); - bmp._rawFormat = ImageFormat.Icon; - - for (int y = 0; y < actualH; y++) - { - // XOR mask is stored bottom-up - int srcRow = (actualH - 1 - y) * xorStride + xorOff; - for (int x = 0; x < dibW; x++) - { - byte r, g, bl, a; - if (dibBpp == 32) - { - int off = srcRow + x * 4; - bl = file[off]; g = file[off+1]; r = file[off+2]; a = file[off+3]; - } - else if (dibBpp == 24) - { - int off = srcRow + x * 3; - bl = file[off]; g = file[off+1]; r = file[off+2]; - // AND mask: bit=1 → transparent, bit=0 → opaque - int andRow = andOff + (actualH - 1 - y) * andStride; - int andByte = andRow + x / 8; - int andBit = 7 - (x % 8); - a = (andByte < file.Length && ((file[andByte] >> andBit) & 1) != 0) ? (byte)0 : (byte)255; - } - else - { - r = g = bl = 0; a = 255; - } - int dstOff = y * bmp._stride + x * 4; - bmp._pixels[dstOff] = bl; - bmp._pixels[dstOff + 1] = g; - bmp._pixels[dstOff + 2] = r; - bmp._pixels[dstOff + 3] = a; - } - } - - return bmp; - } - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - => throw new NotSupportedException("ICO encoding is not supported."); - - private static byte[] ReadAll(Stream s) - { - using var ms = new MemoryStream(); - s.CopyTo(ms); - return ms.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/CoefficientBuffer.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/CoefficientBuffer.cs deleted file mode 100644 index 041e7e6c..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/CoefficientBuffer.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class CoefficientBuffer - { - private readonly short[][] _componentData; - private readonly int[] _blocksX; - private readonly int[] _blocksY; - - public CoefficientBuffer(FrameHeader frame) - { - if (frame == null) throw new ArgumentNullException(nameof(frame)); - - Frame = frame; - ComponentCount = frame.Components.Length; - - int maxH = 1; - int maxV = 1; - for (int i = 0; i < ComponentCount; i++) - { - maxH = Math.Max(maxH, frame.Components[i].HSampling); - maxV = Math.Max(maxV, frame.Components[i].VSampling); - } - - MaxHorizontalSampling = maxH; - MaxVerticalSampling = maxV; - McuCountX = (frame.Width + (8 * maxH) - 1) / (8 * maxH); - McuCountY = (frame.Height + (8 * maxV) - 1) / (8 * maxV); - - _componentData = new short[ComponentCount][]; - _blocksX = new int[ComponentCount]; - _blocksY = new int[ComponentCount]; - - for (int i = 0; i < ComponentCount; i++) - { - int bx = McuCountX * frame.Components[i].HSampling; - int by = McuCountY * frame.Components[i].VSampling; - _blocksX[i] = bx; - _blocksY[i] = by; - _componentData[i] = new short[bx * by * 64]; - } - } - - public FrameHeader Frame { get; } - public int ComponentCount { get; } - public int MaxHorizontalSampling { get; } - public int MaxVerticalSampling { get; } - public int McuCountX { get; } - public int McuCountY { get; } - - public int GetBlocksX(int componentIndex) => _blocksX[componentIndex]; - public int GetBlocksY(int componentIndex) => _blocksY[componentIndex]; - - public short[] GetComponentData(int componentIndex) => _componentData[componentIndex]; - - public int GetBlockOffset(int componentIndex, int blockX, int blockY) - => ((blockY * _blocksX[componentIndex]) + blockX) * 64; - - public short GetCoefficient(int componentIndex, int blockX, int blockY, int naturalIndex) - { - int offset = GetBlockOffset(componentIndex, blockX, blockY) + naturalIndex; - return _componentData[componentIndex][offset]; - } - - public void SetCoefficient(int componentIndex, int blockX, int blockY, int naturalIndex, short value) - { - int offset = GetBlockOffset(componentIndex, blockX, blockY) + naturalIndex; - _componentData[componentIndex][offset] = value; - } - - public void AddCoefficient(int componentIndex, int blockX, int blockY, int naturalIndex, short delta) - { - int offset = GetBlockOffset(componentIndex, blockX, blockY) + naturalIndex; - _componentData[componentIndex][offset] = (short)(_componentData[componentIndex][offset] + delta); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ColorConverter.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ColorConverter.cs deleted file mode 100644 index a3ffe8ec..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ColorConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal static class ColorConverter - { - public static void YCbCrToRgb(int y, int cb, int cr, out byte r, out byte g, out byte b) - { - int d = cb - 128; - int e = cr - 128; - - int rr = y + ((91881 * e + 32768) >> 16); - int gg = y - ((22554 * d + 46802 * e + 32768) >> 16); - int bb = y + ((116130 * d + 32768) >> 16); - - r = (byte)ClampToByte(rr); - g = (byte)ClampToByte(gg); - b = (byte)ClampToByte(bb); - } - - public static void GrayscaleToRgb(int y, out byte r, out byte g, out byte b) - { - byte v = (byte)ClampToByte(y); - r = v; - g = v; - b = v; - } - - private static int ClampToByte(int value) => Math.Max(0, Math.Min(255, value)); - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/EntropyDecoder.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/EntropyDecoder.cs deleted file mode 100644 index 1002c23a..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/EntropyDecoder.cs +++ /dev/null @@ -1,267 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class EntropyDecoder - { - private readonly FrameHeader _frame; - private readonly ScanHeader _scan; - private readonly QuantizationTable?[] _quantTables; - private readonly HuffmanTable?[] _dcTables; - private readonly HuffmanTable?[] _acTables; - private readonly int _restartInterval; - - public EntropyDecoder( - FrameHeader frame, - ScanHeader scan, - QuantizationTable?[] quantTables, - HuffmanTable?[] dcTables, - HuffmanTable?[] acTables, - int restartInterval) - { - _frame = frame ?? throw new ArgumentNullException(nameof(frame)); - _scan = scan ?? throw new ArgumentNullException(nameof(scan)); - _quantTables = quantTables ?? throw new ArgumentNullException(nameof(quantTables)); - _dcTables = dcTables ?? throw new ArgumentNullException(nameof(dcTables)); - _acTables = acTables ?? throw new ArgumentNullException(nameof(acTables)); - _restartInterval = restartInterval; - } - - public EntropyDecodeResult Decode(BitReader reader) - { - if (reader == null) throw new ArgumentNullException(nameof(reader)); - - int componentCount = _frame.Components.Length; - if (componentCount == 0) - throw new InvalidDataException("Frame has no components."); - - int maxH = 1; - int maxV = 1; - for (int i = 0; i < componentCount; i++) - { - maxH = Math.Max(maxH, _frame.Components[i].HSampling); - maxV = Math.Max(maxV, _frame.Components[i].VSampling); - } - - int mcuWidth = 8 * maxH; - int mcuHeight = 8 * maxV; - int mcuCountX = (_frame.Width + mcuWidth - 1) / mcuWidth; - int mcuCountY = (_frame.Height + mcuHeight - 1) / mcuHeight; - - var planes = new byte[componentCount][]; - var planeWidths = new int[componentCount]; - var planeHeights = new int[componentCount]; - - for (int i = 0; i < componentCount; i++) - { - int h = _frame.Components[i].HSampling; - int v = _frame.Components[i].VSampling; - int width = mcuCountX * h * 8; - int height = mcuCountY * v * 8; - planeWidths[i] = width; - planeHeights[i] = height; - planes[i] = new byte[width * height]; - } - - var scanToFrame = new int[_scan.Components.Length]; - for (int i = 0; i < _scan.Components.Length; i++) - { - byte id = _scan.Components[i].ComponentId; - int found = -1; - for (int j = 0; j < componentCount; j++) - { - if (_frame.Components[j].Id == id) - { - found = j; - break; - } - } - - if (found < 0) - throw new InvalidDataException($"SOS references unknown component id {id}."); - scanToFrame[i] = found; - } - - var dcPredictors = new int[componentCount]; - var coeffs = new int[64]; - var blockPixels = new byte[64]; - int decodedMcus = 0; - - for (int mcuY = 0; mcuY < mcuCountY; mcuY++) - { - for (int mcuX = 0; mcuX < mcuCountX; mcuX++) - { - for (int scanIndex = 0; scanIndex < _scan.Components.Length; scanIndex++) - { - int frameIndex = scanToFrame[scanIndex]; - var frameComponent = _frame.Components[frameIndex]; - var scanComponent = _scan.Components[scanIndex]; - - var quant = _quantTables[frameComponent.QuantizationTableId] - ?? throw new InvalidDataException($"Missing quantization table {frameComponent.QuantizationTableId}."); - var dcTable = _dcTables[scanComponent.DcTableId] - ?? throw new InvalidDataException($"Missing DC Huffman table {scanComponent.DcTableId}."); - var acTable = _acTables[scanComponent.AcTableId] - ?? throw new InvalidDataException($"Missing AC Huffman table {scanComponent.AcTableId}."); - - int hSamples = frameComponent.HSampling; - int vSamples = frameComponent.VSampling; - - for (int v = 0; v < vSamples; v++) - { - for (int h = 0; h < hSamples; h++) - { - DecodeBlock(reader, dcTable, acTable, ref dcPredictors[frameIndex], coeffs); - Dequantize(coeffs, quant.Coefficients); - IdctTransform.TransformBlock(coeffs, blockPixels); - - int dstX = (mcuX * hSamples + h) * 8; - int dstY = (mcuY * vSamples + v) * 8; - WriteBlock( - planes[frameIndex], - planeWidths[frameIndex], - planeHeights[frameIndex], - blockPixels, - dstX, - dstY); - } - } - } - - decodedMcus++; - if (_restartInterval > 0 && (decodedMcus % _restartInterval) == 0) - { - Array.Clear(dcPredictors, 0, dcPredictors.Length); - reader.Flush(); - } - } - } - - return new EntropyDecodeResult( - planes, - planeWidths, - planeHeights, - maxH, - maxV, - mcuCountX, - mcuCountY); - } - - private static void DecodeBlock( - BitReader reader, - HuffmanTable dcTable, - HuffmanTable acTable, - ref int dcPredictor, - int[] coeffs) - { - Array.Clear(coeffs, 0, 64); - - int dcLength = dcTable.Decode(reader); - int dcDiff = ReceiveAndExtend(reader, dcLength); - dcPredictor += dcDiff; - coeffs[0] = dcPredictor; - - int k = 1; - while (k < 64) - { - int rs = acTable.Decode(reader); - int run = (rs >> 4) & 0xF; - int size = rs & 0xF; - - if (size == 0) - { - if (run == 15) - { - k += 16; - continue; - } - - break; - } - - k += run; - if (k >= 64) - break; - - int value = ReceiveAndExtend(reader, size); - coeffs[QuantizationTable.ZigZagOrder[k]] = value; - k++; - } - } - - private static int ReceiveAndExtend(BitReader reader, int bitCount) - { - if (bitCount == 0) - return 0; - - int value = reader.ReadBits(bitCount); - int threshold = 1 << (bitCount - 1); - if (value < threshold) - value -= (1 << bitCount) - 1; - return value; - } - - private static void Dequantize(int[] coeffs, int[] quant) - { - for (int i = 0; i < 64; i++) - coeffs[i] *= quant[i]; - } - - private static void WriteBlock( - byte[] plane, - int planeWidth, - int planeHeight, - byte[] block, - int dstX, - int dstY) - { - for (int y = 0; y < 8; y++) - { - int py = dstY + y; - if ((uint)py >= (uint)planeHeight) - continue; - - int srcRow = y * 8; - int dstRow = py * planeWidth; - for (int x = 0; x < 8; x++) - { - int px = dstX + x; - if ((uint)px >= (uint)planeWidth) - continue; - - plane[dstRow + px] = block[srcRow + x]; - } - } - } - } - - internal sealed class EntropyDecodeResult - { - public EntropyDecodeResult( - byte[][] planes, - int[] planeWidths, - int[] planeHeights, - int maxHorizontalSampling, - int maxVerticalSampling, - int mcuCountX, - int mcuCountY) - { - Planes = planes; - PlaneWidths = planeWidths; - PlaneHeights = planeHeights; - MaxHorizontalSampling = maxHorizontalSampling; - MaxVerticalSampling = maxVerticalSampling; - McuCountX = mcuCountX; - McuCountY = mcuCountY; - } - - public byte[][] Planes { get; } - public int[] PlaneWidths { get; } - public int[] PlaneHeights { get; } - public int MaxHorizontalSampling { get; } - public int MaxVerticalSampling { get; } - public int McuCountX { get; } - public int McuCountY { get; } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ExifReader.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ExifReader.cs deleted file mode 100644 index 7c544e10..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ExifReader.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Reads the Orientation tag from an Exif APP1 payload. - /// All other IFD tags are ignored. - /// - internal static class ExifReader - { - private const ushort TagOrientation = 274; // 0x0112 - - /// - /// Returns the Exif Orientation value (1–8), or 1 (no rotation) if the - /// APP1 payload is not a valid Exif block or the tag is absent. - /// - public static int ReadOrientation(byte[] app1Data) - { - if (app1Data == null || app1Data.Length < 12) return 1; - - // APP1 starts with "Exif\0\0" (6 bytes) - if (app1Data[0] != 0x45 || app1Data[1] != 0x78 || app1Data[2] != 0x69 || - app1Data[3] != 0x66 || app1Data[4] != 0x00 || app1Data[5] != 0x00) - return 1; - - // TIFF header starts at offset 6 - int tiffBase = 6; - if (app1Data.Length < tiffBase + 8) return 1; - - bool le = app1Data[tiffBase] == 0x49 && app1Data[tiffBase + 1] == 0x49; - // Validate TIFF magic (42) - int magic = ReadU16(app1Data, tiffBase + 2, le); - if (magic != 42) return 1; - - // Offset to first IFD - int ifd0Offset = (int)ReadU32(app1Data, tiffBase + 4, le); - int ifd0Abs = tiffBase + ifd0Offset; - if (ifd0Abs + 2 > app1Data.Length) return 1; - - int entryCount = ReadU16(app1Data, ifd0Abs, le); - for (int i = 0; i < entryCount; i++) - { - int entryAbs = ifd0Abs + 2 + i * 12; - if (entryAbs + 12 > app1Data.Length) break; - - int tag = ReadU16(app1Data, entryAbs, le); - int type = ReadU16(app1Data, entryAbs + 2, le); - long count = ReadU32(app1Data, entryAbs + 4, le); - - if (tag == TagOrientation && type == 3 /*SHORT*/ && count == 1) - { - // Value is inline in the 4-byte value/offset field - int value = ReadU16(app1Data, entryAbs + 8, le); - return Math.Max(1, Math.Min(8, value)); - } - } - return 1; - } - - // ── Byte-order-aware helpers ────────────────────────────────────────────── - - private static int ReadU16(byte[] data, int offset, bool le) - { - if (offset + 2 > data.Length) return 0; - return le - ? data[offset] | (data[offset + 1] << 8) - : (data[offset] << 8) | data[offset + 1]; - } - - private static long ReadU32(byte[] data, int offset, bool le) - { - if (offset + 4 > data.Length) return 0; - return le - ? (uint)(data[offset] | (data[offset+1] << 8) | (data[offset+2] << 16) | (data[offset+3] << 24)) - : (uint)((data[offset] << 24) | (data[offset+1] << 16) | (data[offset+2] << 8) | data[offset+3]); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ForwardDct.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ForwardDct.cs deleted file mode 100644 index d952e5ae..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ForwardDct.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal static class ForwardDct - { - private static readonly double InvSqrt2 = 1.0 / Math.Sqrt(2.0); - private static readonly double[,] Cosine = BuildCosineTable(); - - public static void TransformBlock(double[] samples, double[] output) - { - if (samples == null) throw new ArgumentNullException(nameof(samples)); - if (output == null) throw new ArgumentNullException(nameof(output)); - if (samples.Length < 64) throw new ArgumentException("Forward DCT requires 64 samples.", nameof(samples)); - if (output.Length < 64) throw new ArgumentException("Forward DCT output requires 64 values.", nameof(output)); - - for (int v = 0; v < 8; v++) - { - double cv = v == 0 ? InvSqrt2 : 1.0; - for (int u = 0; u < 8; u++) - { - double cu = u == 0 ? InvSqrt2 : 1.0; - double sum = 0.0; - - for (int y = 0; y < 8; y++) - { - for (int x = 0; x < 8; x++) - { - sum += samples[y * 8 + x] * Cosine[x, u] * Cosine[y, v]; - } - } - - output[v * 8 + u] = 0.25 * cu * cv * sum; - } - } - } - - private static double[,] BuildCosineTable() - { - var table = new double[8, 8]; - for (int x = 0; x < 8; x++) - { - for (int u = 0; u < 8; u++) - table[x, u] = Math.Cos(((2.0 * x + 1.0) * u * Math.PI) / 16.0); - } - - return table; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/FrameComponent.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/FrameComponent.cs deleted file mode 100644 index 2a1c33d6..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/FrameComponent.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Describes one image component in a JPEG SOF segment - /// (e.g. Y, Cb, Cr in a YCbCr image). - /// - internal struct FrameComponent - { - /// Component identifier byte (typically 1=Y, 2=Cb, 3=Cr). - public byte Id; - - /// Horizontal sampling factor (1–4). - public byte HSampling; - - /// Vertical sampling factor (1–4). - public byte VSampling; - - /// Quantization table destination id (0–3). - public byte QuantizationTableId; - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/FrameHeader.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/FrameHeader.cs deleted file mode 100644 index b4debec0..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/FrameHeader.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// JPEG Start-of-Frame type. - internal enum SofType - { - Baseline = 0, // SOF0 - ExtendedSequential = 1, // SOF1 - Progressive = 2, // SOF2 - } - - /// - /// Parsed payload of a JPEG SOF0 / SOF1 / SOF2 marker. - /// - internal sealed class FrameHeader - { - /// Sample precision in bits (typically 8). - public int Precision { get; private set; } - - /// Frame height in pixels. - public int Height { get; private set; } - - /// Frame width in pixels. - public int Width { get; private set; } - - /// Image components (1 = grayscale, 3 = YCbCr, 4 = CMYK). - public FrameComponent[] Components { get; private set; } = Array.Empty(); - - /// SOF type that was used to produce this header. - public SofType Type { get; private set; } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Parses a SOF0/SOF1/SOF2 segment payload. - /// determines the . - /// - public static FrameHeader Parse(JpegMarker marker, byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (data.Length < 6) - throw new InvalidDataException("SOF segment too short."); - - var fh = new FrameHeader - { - Type = MarkerToSofType(marker), - Precision = data[0], - Height = (data[1] << 8) | data[2], - Width = (data[3] << 8) | data[4], - }; - - int nf = data[5]; - if (data.Length < 6 + nf * 3) - throw new InvalidDataException("SOF segment component data truncated."); - - fh.Components = new FrameComponent[nf]; - for (int i = 0; i < nf; i++) - { - int off = 6 + i * 3; - byte samp = data[off + 1]; - fh.Components[i] = new FrameComponent - { - Id = data[off], - HSampling = (byte)((samp >> 4) & 0xF), - VSampling = (byte)(samp & 0xF), - QuantizationTableId = data[off + 2], - }; - } - return fh; - } - - private static SofType MarkerToSofType(JpegMarker m) => m switch - { - JpegMarker.SOF0 => SofType.Baseline, - JpegMarker.SOF1 => SofType.ExtendedSequential, - JpegMarker.SOF2 => SofType.Progressive, - _ => SofType.Baseline, - }; - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanEncoder.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanEncoder.cs deleted file mode 100644 index ef339cc1..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanEncoder.cs +++ /dev/null @@ -1,225 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class HuffmanEncoder - { - // Counts for code lengths 1..16. - internal static readonly byte[] DcLuminanceCounts = { 0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0 }; - internal static readonly byte[] DcChrominanceCounts = { 0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 }; - internal static readonly byte[] AcLuminanceCounts = { 0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125 }; - internal static readonly byte[] AcChrominanceCounts = { 0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119 }; - - internal static readonly byte[] DcLuminanceValues = { 0,1,2,3,4,5,6,7,8,9,10,11 }; - internal static readonly byte[] DcChrominanceValues = { 0,1,2,3,4,5,6,7,8,9,10,11 }; - - internal static readonly byte[] AcLuminanceValues = - { - 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07, - 0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0, - 0x24,0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28, - 0x29,0x2A,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49, - 0x4A,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69, - 0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89, - 0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7, - 0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xC2,0xC3,0xC4,0xC5, - 0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xE1,0xE2, - 0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8, - 0xF9,0xFA, - }; - - internal static readonly byte[] AcChrominanceValues = - { - 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, - 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0, - 0x15,0x62,0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26, - 0x27,0x28,0x29,0x2A,0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48, - 0x49,0x4A,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68, - 0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87, - 0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0xA2,0xA3,0xA4,0xA5, - 0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xC2,0xC3, - 0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA, - 0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8, - 0xF9,0xFA, - }; - - private readonly BitWriter _writer; - private readonly HuffmanCode[] _dcLuma; - private readonly HuffmanCode[] _dcChroma; - private readonly HuffmanCode[] _acLuma; - private readonly HuffmanCode[] _acChroma; - - public HuffmanEncoder(Stream stream) - { - _writer = new BitWriter(stream ?? throw new ArgumentNullException(nameof(stream))); - _dcLuma = BuildCodes(DcLuminanceCounts, DcLuminanceValues); - _dcChroma = BuildCodes(DcChrominanceCounts, DcChrominanceValues); - _acLuma = BuildCodes(AcLuminanceCounts, AcLuminanceValues); - _acChroma = BuildCodes(AcChrominanceCounts, AcChrominanceValues); - } - - public void EncodeBlock(int[] blockNatural, ref int previousDc, bool chroma) - { - if (blockNatural == null) throw new ArgumentNullException(nameof(blockNatural)); - if (blockNatural.Length < 64) throw new ArgumentException("Block must contain 64 coefficients.", nameof(blockNatural)); - - HuffmanCode[] dc = chroma ? _dcChroma : _dcLuma; - HuffmanCode[] ac = chroma ? _acChroma : _acLuma; - - int dcDiff = blockNatural[0] - previousDc; - previousDc = blockNatural[0]; - - int dcBits = MagnitudeCategory(dcDiff); - WriteCode(dc, dcBits); - if (dcBits > 0) - _writer.WriteBits(ToAmplitudeBits(dcDiff, dcBits), dcBits); - - int zeroRun = 0; - for (int i = 1; i < 64; i++) - { - int idx = QuantizationTable.ZigZagOrder[i]; - int value = blockNatural[idx]; - if (value == 0) - { - zeroRun++; - continue; - } - - while (zeroRun >= 16) - { - WriteCode(ac, 0xF0); - zeroRun -= 16; - } - - int acBits = MagnitudeCategory(value); - int symbol = (zeroRun << 4) | acBits; - WriteCode(ac, symbol); - _writer.WriteBits(ToAmplitudeBits(value, acBits), acBits); - zeroRun = 0; - } - - if (zeroRun > 0) - WriteCode(ac, 0x00); // EOB - } - - public void Flush() => _writer.Flush(); - - private void WriteCode(HuffmanCode[] table, int symbol) - { - HuffmanCode code = table[symbol & 0xFF]; - if (code.Size == 0) - throw new InvalidDataException($"Missing Huffman code for symbol 0x{symbol:X2}."); - - _writer.WriteBits(code.Code, code.Size); - } - - private static int MagnitudeCategory(int value) - { - int abs = Math.Abs(value); - int bits = 0; - while (abs != 0) - { - abs >>= 1; - bits++; - } - - return bits; - } - - private static int ToAmplitudeBits(int value, int bits) - { - if (value >= 0) - return value; - - return value + ((1 << bits) - 1); - } - - private static HuffmanCode[] BuildCodes(byte[] counts, byte[] values) - { - var table = new HuffmanCode[256]; - int code = 0; - int index = 0; - - for (int bitLength = 1; bitLength <= 16; bitLength++) - { - int count = counts[bitLength - 1]; - for (int i = 0; i < count; i++) - { - int symbol = values[index++]; - table[symbol] = new HuffmanCode((ushort)code, (byte)bitLength); - code++; - } - - code <<= 1; - } - - return table; - } - - private readonly struct HuffmanCode - { - public HuffmanCode(ushort code, byte size) - { - Code = code; - Size = size; - } - - public ushort Code { get; } - public byte Size { get; } - } - - private sealed class BitWriter - { - private readonly Stream _stream; - private uint _bitBuffer; - private int _bitCount; - - public BitWriter(Stream stream) - { - _stream = stream; - } - - public void WriteBits(int bits, int count) - { - if (count <= 0) - return; - - uint valueMask = count == 32 ? uint.MaxValue : (uint)((1u << count) - 1u); - _bitBuffer = (_bitBuffer << count) | ((uint)bits & valueMask); - _bitCount += count; - - while (_bitCount >= 8) - { - int shift = _bitCount - 8; - byte b = (byte)((_bitBuffer >> shift) & 0xFF); - WriteByteStuffed(b); - _bitCount -= 8; - - if (_bitCount == 0) - { - _bitBuffer = 0; - } - else - { - _bitBuffer &= (uint)((1u << _bitCount) - 1u); - } - } - } - - public void Flush() - { - int pad = (8 - (_bitCount & 7)) & 7; - if (pad > 0) - WriteBits((1 << pad) - 1, pad); - } - - private void WriteByteStuffed(byte value) - { - _stream.WriteByte(value); - if (value == 0xFF) - _stream.WriteByte(0x00); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanTable.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanTable.cs deleted file mode 100644 index 0f431899..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/HuffmanTable.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// JPEG Huffman table built from a DHT segment. - /// Uses a 512-entry (9-bit lookahead) fast-decode table for codes ≤ 9 bits; - /// falls back to a linear search for longer codes. - /// - internal sealed class HuffmanTable - { - // Fast-path: 512 entries, indexed by top 9 bits of the bit-stream. - // Entry format: bits[11:8] = code length (0 = slow path), bits[7:0] = symbol. - private readonly int[] _fast = new int[512]; - - // Slow-path data (codes > 9 bits) - private readonly int[] _maxCode = new int[17]; // max code at each length - private readonly int[] _minCode = new int[17]; - private readonly int[] _valPtr = new int[17]; // index into _huffVal - private readonly byte[] _huffVal; // all symbol values in order - - /// Table class: 0 = DC, 1 = AC. - public int Class { get; private set; } - - /// Table destination id (0–3). - public int Id { get; private set; } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Parses one or more Huffman tables from a DHT segment payload. - /// Returns all tables found. - /// - public static HuffmanTable[] ParseDht(byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - var tables = new System.Collections.Generic.List(4); - int pos = 0; - while (pos < data.Length) - { - byte tcTh = data[pos++]; - int tc = (tcTh >> 4) & 0xF; // table class (0=DC,1=AC) - int th = tcTh & 0xF; // table destination id - - // BITS[1..16] — count of codes of each length - int[] bits = new int[17]; - int totalSymbols = 0; - for (int i = 1; i <= 16; i++) - { - bits[i] = data[pos++]; - totalSymbols += bits[i]; - } - - // HUFFVAL — all symbol bytes in code-length order - byte[] huffVal = new byte[totalSymbols]; - for (int i = 0; i < totalSymbols; i++) - huffVal[i] = data[pos++]; - - tables.Add(Build(tc, th, bits, huffVal)); - } - return tables.ToArray(); - } - - /// Decode the next symbol from . - public int Decode(BitReader reader) - { - // Fast path: peek 9 bits - int top9 = reader.PeekBits(9); - int entry = _fast[top9]; - int len = entry >> 8; - if (len > 0 && len <= 9) - { - reader.ConsumeBits(len); - return entry & 0xFF; - } - - // Slow path: iterate lengths 1..16 - int code = 0; - for (int l = 1; l <= 16; l++) - { - code = (code << 1) | reader.ReadBit(); - if (code <= _maxCode[l] && _maxCode[l] != -1) - { - int idx = _valPtr[l] + (code - _minCode[l]); - return _huffVal[idx]; - } - } - throw new InvalidDataException("Invalid Huffman code in JPEG stream."); - } - - // ── Construction ───────────────────────────────────────────────────────── - - private static HuffmanTable Build(int tc, int th, int[] bits, byte[] huffVal) - { - var t = new HuffmanTable(huffVal) { Class = tc, Id = th }; - - // Build canonical codes and min/max/valPtr tables - int code = 0; - int valIdx = 0; - for (int l = 1; l <= 16; l++) - { - if (bits[l] > 0) - { - t._minCode[l] = code; - t._valPtr[l] = valIdx; - code += bits[l]; - valIdx += bits[l]; - t._maxCode[l] = code - 1; - } - else - { - t._maxCode[l] = -1; // no codes of this length - } - code <<= 1; - } - - // Fill fast 9-bit lookup table - code = 0; - valIdx = 0; - for (int l = 1; l <= 9; l++) - { - for (int i = 0; i < bits[l]; i++) - { - // Every 9-bit prefix that starts with this code - int baseIdx = code << (9 - l); - int count = 1 << (9 - l); - int entry = (l << 8) | huffVal[valIdx]; - for (int k = 0; k < count; k++) - t._fast[baseIdx + k] = entry; - code++; - valIdx++; - } - code <<= 1; - } - return t; - } - - private HuffmanTable(byte[] huffVal) => _huffVal = huffVal; - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/IdctTransform.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/IdctTransform.cs deleted file mode 100644 index 22a45be2..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/IdctTransform.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal static class IdctTransform - { - private static readonly double InvSqrt2 = 1.0 / Math.Sqrt(2.0); - private static readonly double[,] Cosine = BuildCosineTable(); - - public static void TransformBlock(int[] coeffs, byte[] destination) - { - if (coeffs == null) throw new ArgumentNullException(nameof(coeffs)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - if (coeffs.Length < 64) throw new ArgumentException("IDCT requires 64 coefficients.", nameof(coeffs)); - if (destination.Length < 64) throw new ArgumentException("IDCT destination must contain at least 64 bytes.", nameof(destination)); - - for (int y = 0; y < 8; y++) - { - for (int x = 0; x < 8; x++) - { - double sum = 0.0; - for (int v = 0; v < 8; v++) - { - double cv = v == 0 ? InvSqrt2 : 1.0; - for (int u = 0; u < 8; u++) - { - double cu = u == 0 ? InvSqrt2 : 1.0; - int c = coeffs[v * 8 + u]; - sum += cu * cv * c * Cosine[x, u] * Cosine[y, v]; - } - } - - int sample = (int)Math.Round(0.25 * sum + 128.0); - destination[y * 8 + x] = (byte)Math.Max(0, Math.Min(255, sample)); - } - } - } - - private static double[,] BuildCosineTable() - { - var table = new double[8, 8]; - for (int x = 0; x < 8; x++) - { - for (int u = 0; u < 8; u++) - { - table[x, u] = Math.Cos(((2.0 * x + 1.0) * u * Math.PI) / 16.0); - } - } - - return table; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JfifHeader.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JfifHeader.cs deleted file mode 100644 index 0845a96b..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JfifHeader.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Parsed JFIF APP0 header (present in most "plain" JPEG files). - /// - internal sealed class JfifHeader - { - /// JFIF major version (e.g. 1). - public byte MajorVersion { get; private set; } - - /// JFIF minor version (e.g. 1 or 2). - public byte MinorVersion { get; private set; } - - /// Density units: 0 = none, 1 = DPI, 2 = dots-per-cm. - public byte DensityUnits { get; private set; } - - /// Horizontal pixel density. - public int XDensity { get; private set; } - - /// Vertical pixel density. - public int YDensity { get; private set; } - - /// Thumbnail width in pixels (0 if absent). - public int ThumbnailWidth { get; private set; } - - /// Thumbnail height in pixels (0 if absent). - public int ThumbnailHeight { get; private set; } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Attempts to parse an APP0 payload as a JFIF header. - /// Returns null if the signature is absent or the payload is malformed. - /// - public static JfifHeader? TryParse(byte[] data) - { - if (data == null || data.Length < 14) return null; - - // Check "JFIF\0" identifier - if (data[0] != 0x4A || data[1] != 0x46 || data[2] != 0x49 || - data[3] != 0x46 || data[4] != 0x00) - return null; - - return new JfifHeader - { - MajorVersion = data[5], - MinorVersion = data[6], - DensityUnits = data[7], - XDensity = (data[8] << 8) | data[9], - YDensity = (data[10] << 8) | data[11], - ThumbnailWidth = data[12], - ThumbnailHeight= data[13], - }; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegDecoder.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JpegDecoder.cs deleted file mode 100644 index 827921d9..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegDecoder.cs +++ /dev/null @@ -1,250 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class JpegDecoder - { - private readonly QuantizationTable?[] _quantTables = new QuantizationTable[4]; - private readonly HuffmanTable?[] _dcTables = new HuffmanTable[4]; - private readonly HuffmanTable?[] _acTables = new HuffmanTable[4]; - - private FrameHeader? _frame; - private JfifHeader? _jfif; - private int _restartInterval; - - public Bitmap Decode(Stream stream) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - - var reader = new JpegReader(stream); - CoefficientBuffer? progressiveBuffer = null; - ProgressiveDecoder? progressiveDecoder = null; - - var (firstMarker, _) = reader.ReadMarker(); - if (firstMarker != JpegMarker.SOI) - throw new InvalidDataException("Invalid JPEG stream: SOI marker missing."); - - while (true) - { - var (marker, payload) = reader.ReadMarker(); - switch (marker) - { - case JpegMarker.APP0: - _jfif = JfifHeader.TryParse(payload); - break; - - case JpegMarker.DQT: - foreach (var table in QuantizationTable.ParseDqt(payload)) - { - if ((uint)table.Id < 4) - _quantTables[table.Id] = table; - } - break; - - case JpegMarker.DHT: - foreach (var table in HuffmanTable.ParseDht(payload)) - { - if ((uint)table.Id >= 4) - continue; - - if (table.Class == 0) - _dcTables[table.Id] = table; - else if (table.Class == 1) - _acTables[table.Id] = table; - } - break; - - case JpegMarker.DRI: - if (payload.Length >= 2) - _restartInterval = (payload[0] << 8) | payload[1]; - break; - - case JpegMarker.SOF0: - case JpegMarker.SOF1: - _frame = FrameHeader.Parse(marker, payload); - progressiveBuffer = null; - progressiveDecoder = null; - break; - - case JpegMarker.SOF2: - _frame = FrameHeader.Parse(marker, payload); - progressiveBuffer = new CoefficientBuffer(_frame); - progressiveDecoder = new ProgressiveDecoder(_frame, _quantTables, _dcTables, _acTables); - break; - - case JpegMarker.SOS: - if (_frame == null) - throw new InvalidDataException("SOS encountered before SOF marker."); - - if (_frame.Type == SofType.Progressive) - { - if (progressiveBuffer == null || progressiveDecoder == null) - throw new InvalidDataException("Progressive decoder state is not initialized."); - - var scan = ScanHeader.Parse(payload); - byte[] entropyData = reader.ReadEntropyData(); - progressiveDecoder.DecodeScan(scan, new BitReader(entropyData), progressiveBuffer, _restartInterval); - break; - } - - return DecodeSequentialScan(reader, payload); - - case JpegMarker.EOI: - if (_frame != null && _frame.Type == SofType.Progressive) - { - if (progressiveBuffer == null || progressiveDecoder == null) - throw new InvalidDataException("Progressive decoder state is not initialized."); - - EntropyDecodeResult imageData = progressiveDecoder.BuildImageData(progressiveBuffer); - Bitmap progressiveBitmap = BuildBitmap(_frame, imageData); - progressiveBitmap._rawFormat = ImageFormat.Jpeg; - ApplyJfifDensity(progressiveBitmap, _jfif); - return progressiveBitmap; - } - - throw new InvalidDataException("Invalid JPEG stream: no SOS marker found."); - } - } - } - - private Bitmap DecodeSequentialScan(JpegReader reader, byte[] sosPayload) - { - if (_frame == null) - throw new InvalidDataException("SOS encountered before SOF marker."); - - var scan = ScanHeader.Parse(sosPayload); - - if (_frame.Components.Length > 1 && scan.Components.Length != _frame.Components.Length) - throw new NotSupportedException("Non-interleaved sequential JPEG scans are not supported yet."); - - var entropyDecoder = new EntropyDecoder( - _frame, - scan, - _quantTables, - _dcTables, - _acTables, - _restartInterval); - - byte[] entropyData = reader.ReadEntropyData(); - EntropyDecodeResult entropy = entropyDecoder.Decode(new BitReader(entropyData)); - Bitmap bitmap = BuildBitmap(_frame, entropy); - bitmap._rawFormat = ImageFormat.Jpeg; - ApplyJfifDensity(bitmap, _jfif); - return bitmap; - } - - private static Bitmap BuildBitmap(FrameHeader frame, EntropyDecodeResult entropy) - { - var bmp = new Bitmap(frame.Width, frame.Height, PixelFormat.Format32bppArgb); - - int componentCount = frame.Components.Length; - if (componentCount == 1) - { - var c = frame.Components[0]; - byte[] yPlane = UpsampleBuffer.UpsampleToFullResolution( - entropy.Planes[0], - entropy.PlaneWidths[0], - entropy.PlaneHeights[0], - frame.Width, - frame.Height, - c.HSampling, - c.VSampling, - entropy.MaxHorizontalSampling, - entropy.MaxVerticalSampling); - - for (int y = 0; y < frame.Height; y++) - { - int srcRow = y * frame.Width; - int dstRow = y * bmp._stride; - for (int x = 0; x < frame.Width; x++) - { - ColorConverter.GrayscaleToRgb(yPlane[srcRow + x], out byte r, out byte g, out byte b); - int o = dstRow + x * 4; - bmp._pixels[o] = b; - bmp._pixels[o + 1] = g; - bmp._pixels[o + 2] = r; - bmp._pixels[o + 3] = 255; - } - } - - return bmp; - } - - if (componentCount < 3) - throw new NotSupportedException("JPEG with two components is not supported."); - - int yIndex = ResolveComponentIndex(frame, 1, 0); - int cbIndex = ResolveComponentIndex(frame, 2, 1); - int crIndex = ResolveComponentIndex(frame, 3, 2); - - byte[] fullY = Upsample(frame, entropy, yIndex, frame.Width, frame.Height); - byte[] fullCb = Upsample(frame, entropy, cbIndex, frame.Width, frame.Height); - byte[] fullCr = Upsample(frame, entropy, crIndex, frame.Width, frame.Height); - - for (int y = 0; y < frame.Height; y++) - { - int srcRow = y * frame.Width; - int dstRow = y * bmp._stride; - for (int x = 0; x < frame.Width; x++) - { - int src = srcRow + x; - ColorConverter.YCbCrToRgb(fullY[src], fullCb[src], fullCr[src], out byte r, out byte g, out byte b); - - int dst = dstRow + x * 4; - bmp._pixels[dst] = b; - bmp._pixels[dst + 1] = g; - bmp._pixels[dst + 2] = r; - bmp._pixels[dst + 3] = 255; - } - } - - return bmp; - } - - private static byte[] Upsample(FrameHeader frame, EntropyDecodeResult entropy, int componentIndex, int width, int height) - { - var component = frame.Components[componentIndex]; - return UpsampleBuffer.UpsampleToFullResolution( - entropy.Planes[componentIndex], - entropy.PlaneWidths[componentIndex], - entropy.PlaneHeights[componentIndex], - width, - height, - component.HSampling, - component.VSampling, - entropy.MaxHorizontalSampling, - entropy.MaxVerticalSampling); - } - - private static int ResolveComponentIndex(FrameHeader frame, byte componentId, int fallbackIndex) - { - for (int i = 0; i < frame.Components.Length; i++) - { - if (frame.Components[i].Id == componentId) - return i; - } - - return Math.Min(frame.Components.Length - 1, Math.Max(0, fallbackIndex)); - } - - private static void ApplyJfifDensity(Bitmap bmp, JfifHeader? jfif) - { - if (jfif == null) - return; - - if (jfif.DensityUnits == 1) - { - if (jfif.XDensity > 0) bmp._dpiX = jfif.XDensity; - if (jfif.YDensity > 0) bmp._dpiY = jfif.YDensity; - } - else if (jfif.DensityUnits == 2) - { - if (jfif.XDensity > 0) bmp._dpiX = (float)(jfif.XDensity * 2.54); - if (jfif.YDensity > 0) bmp._dpiY = (float)(jfif.YDensity * 2.54); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegEncoder.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JpegEncoder.cs deleted file mode 100644 index ddfe1801..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegEncoder.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class JpegEncoder - { - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - if (bmp == null) throw new ArgumentNullException(nameof(bmp)); - if (stream == null) throw new ArgumentNullException(nameof(stream)); - - int quality = GetQuality(parameters); - int width = bmp._width; - int height = bmp._height; - - double[] yPlane = new double[width * height]; - double[] cbPlane = new double[width * height]; - double[] crPlane = new double[width * height]; - BuildYCbCrPlanes(bmp, yPlane, cbPlane, crPlane); - - Quantizer quantizer = Quantizer.Create(quality); - var writer = new JpegWriter(stream); - writer.WriteHeaders(width, height, quantizer); - - var huffman = new HuffmanEncoder(stream); - int blocksX = (width + 7) / 8; - int blocksY = (height + 7) / 8; - - var samples = new double[64]; - var dct = new double[64]; - var quantized = new int[64]; - int previousY = 0; - int previousCb = 0; - int previousCr = 0; - - for (int blockY = 0; blockY < blocksY; blockY++) - { - for (int blockX = 0; blockX < blocksX; blockX++) - { - EncodeBlock(yPlane, width, height, blockX, blockY, quantizer.LuminanceNatural, huffman, ref previousY, false, samples, dct, quantized); - EncodeBlock(cbPlane, width, height, blockX, blockY, quantizer.ChrominanceNatural, huffman, ref previousCb, true, samples, dct, quantized); - EncodeBlock(crPlane, width, height, blockX, blockY, quantizer.ChrominanceNatural, huffman, ref previousCr, true, samples, dct, quantized); - } - } - - huffman.Flush(); - writer.WriteEndOfImage(); - } - - private static int GetQuality(EncoderParameters? parameters) - { - int quality = 75; - if (parameters == null) - return quality; - - foreach (EncoderParameter p in parameters.Param) - { - if (p.Encoder == Encoder.Quality.Guid) - { - quality = (int)Math.Max(1, Math.Min(100, p._valueLong)); - break; - } - } - - return quality; - } - - private static void BuildYCbCrPlanes(Bitmap bmp, double[] yPlane, double[] cbPlane, double[] crPlane) - { - int width = bmp._width; - int height = bmp._height; - - for (int y = 0; y < height; y++) - { - int row = y * width; - for (int x = 0; x < width; x++) - { - Color color = bmp.GetPixel(x, y); - double r = color.R; - double g = color.G; - double b = color.B; - - double yy = 0.299 * r + 0.587 * g + 0.114 * b; - double cb = -0.168736 * r - 0.331264 * g + 0.5 * b + 128.0; - double cr = 0.5 * r - 0.418688 * g - 0.081312 * b + 128.0; - - int index = row + x; - yPlane[index] = Clamp(yy, 0.0, 255.0); - cbPlane[index] = Clamp(cb, 0.0, 255.0); - crPlane[index] = Clamp(cr, 0.0, 255.0); - } - } - } - - private static void EncodeBlock( - double[] plane, - int width, - int height, - int blockX, - int blockY, - ushort[] quantTable, - HuffmanEncoder huffman, - ref int previousDc, - bool chroma, - double[] samples, - double[] dct, - int[] quantized) - { - int baseX = blockX * 8; - int baseY = blockY * 8; - - for (int y = 0; y < 8; y++) - { - int srcY = Math.Min(height - 1, baseY + y); - int srcRow = srcY * width; - int dstRow = y * 8; - - for (int x = 0; x < 8; x++) - { - int srcX = Math.Min(width - 1, baseX + x); - samples[dstRow + x] = plane[srcRow + srcX] - 128.0; - } - } - - ForwardDct.TransformBlock(samples, dct); - - for (int i = 0; i < 64; i++) - quantized[i] = (int)Math.Round(dct[i] / quantTable[i]); - - huffman.EncodeBlock(quantized, ref previousDc, chroma); - } - - private static double Clamp(double value, double min, double max) - { - if (value < min) return min; - if (value > max) return max; - return value; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegMarker.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JpegMarker.cs deleted file mode 100644 index 53079c19..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegMarker.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// JPEG marker codes (second byte of the 0xFF XX pair). - internal enum JpegMarker : byte - { - // ── Start / End ───────────────────────────────────────────────────────── - SOI = 0xD8, // Start of Image - EOI = 0xD9, // End of Image - - // ── Frame headers ──────────────────────────────────────────────────────── - SOF0 = 0xC0, // Baseline DCT - SOF1 = 0xC1, // Extended Sequential DCT - SOF2 = 0xC2, // Progressive DCT - SOF3 = 0xC3, // Lossless Sequential - SOF5 = 0xC5, // Differential Sequential DCT - SOF6 = 0xC6, // Differential Progressive DCT - SOF9 = 0xC9, // Extended Sequential, Arithmetic - SOF10 = 0xCA, // Progressive, Arithmetic - SOF11 = 0xCB, // Lossless Sequential, Arithmetic - - // ── Table / misc markers ───────────────────────────────────────────────── - DHT = 0xC4, // Define Huffman Table - DAC = 0xCC, // Define Arithmetic Coding - DQT = 0xDB, // Define Quantization Table - DRI = 0xDD, // Define Restart Interval - COM = 0xFE, // Comment - - // ── Restart markers ────────────────────────────────────────────────────── - RST0 = 0xD0, - RST1 = 0xD1, - RST2 = 0xD2, - RST3 = 0xD3, - RST4 = 0xD4, - RST5 = 0xD5, - RST6 = 0xD6, - RST7 = 0xD7, - - // ── Scan header ────────────────────────────────────────────────────────── - SOS = 0xDA, // Start of Scan - - // ── Application markers (APPn) ─────────────────────────────────────────── - APP0 = 0xE0, - APP1 = 0xE1, - APP2 = 0xE2, - APP3 = 0xE3, - APP4 = 0xE4, - APP5 = 0xE5, - APP6 = 0xE6, - APP7 = 0xE7, - APP8 = 0xE8, - APP9 = 0xE9, - APP10 = 0xEA, - APP11 = 0xEB, - APP12 = 0xEC, - APP13 = 0xED, - APP14 = 0xEE, - APP15 = 0xEF, - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegReader.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JpegReader.cs deleted file mode 100644 index 50794bea..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegReader.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Reads the JPEG marker stream (SOI … EOI) segment by segment. - /// After positioning the stream at the start of entropy-coded data, - /// obtain a via . - /// - internal sealed class JpegReader - { - private readonly Stream _stream; - - public JpegReader(Stream stream) => - _stream = stream ?? throw new ArgumentNullException(nameof(stream)); - - // ── Public position ────────────────────────────────────────────────────── - - /// Current byte position in the underlying stream. - public long Position => _stream.Position; - - // ── Marker reading ─────────────────────────────────────────────────────── - - /// - /// Reads the next JPEG marker and its payload. - /// Stand-alone markers (SOI, EOI, RSTn) have an empty payload byte[]. - /// Skips any 0xFF fill bytes before the marker byte. - /// - public (JpegMarker marker, byte[] payload) ReadMarker() - { - // Skip padding / find leading 0xFF - int b = ReadByteOrThrow(); - while (b != 0xFF) - b = ReadByteOrThrow(); - - // Skip 0xFF fill bytes - int marker; - do { marker = ReadByteOrThrow(); } - while (marker == 0xFF); - - var m = (JpegMarker)(byte)marker; - - // Stand-alone markers carry no length field - if (IsStandAlone(m)) - return (m, Array.Empty()); - - // Read 2-byte big-endian length (includes the 2 length bytes) - int hi = ReadByteOrThrow(); - int lo = ReadByteOrThrow(); - int length = (hi << 8) | lo; - if (length < 2) - throw new InvalidDataException($"Invalid JPEG segment length {length} for marker 0x{marker:X2}."); - - int dataLen = length - 2; - byte[] payload = new byte[dataLen]; - int read = 0; - while (read < dataLen) - { - int n = _stream.Read(payload, read, dataLen - read); - if (n == 0) throw new EndOfStreamException("Unexpected end of JPEG stream."); - read += n; - } - return (m, payload); - } - - /// - /// Reads entropy-coded bytes after SOS until the next non-restart marker. - /// The returned data is de-stuffed (0xFF 0x00 becomes 0xFF) and restart - /// markers are removed. Stream position is left at the next marker. - /// - public byte[] ReadEntropyData() - { - if (!_stream.CanSeek) - throw new NotSupportedException("Entropy segment reading requires a seekable stream."); - - using var ms = new MemoryStream(); - while (true) - { - int b = _stream.ReadByte(); - if (b < 0) - break; - - if (b != 0xFF) - { - ms.WriteByte((byte)b); - continue; - } - - int next = _stream.ReadByte(); - if (next < 0) - break; - - // Stuffed entropy byte. - if (next == 0x00) - { - ms.WriteByte(0xFF); - continue; - } - - // Fill bytes may appear before a marker. - while (next == 0xFF) - { - next = _stream.ReadByte(); - if (next < 0) - return ms.ToArray(); - } - - // Restart markers belong to entropy coding; skip marker bytes and continue. - if (next >= 0xD0 && next <= 0xD7) - continue; - - // Rewind to the marker prefix so ReadMarker() can consume it. - _stream.Seek(-2, SeekOrigin.Current); - break; - } - - return ms.ToArray(); - } - - /// - /// Returns a that reads entropy-coded data - /// from the stream at its current position (right after a SOS payload). - /// - public BitReader CreateBitReader() => new BitReader(_stream); - - // ── Helpers ────────────────────────────────────────────────────────────── - - private int ReadByteOrThrow() - { - int b = _stream.ReadByte(); - if (b < 0) throw new EndOfStreamException("Unexpected end of JPEG stream."); - return b; - } - - private static bool IsStandAlone(JpegMarker m) => - m == JpegMarker.SOI || m == JpegMarker.EOI || - (m >= JpegMarker.RST0 && m <= JpegMarker.RST7); - } - - // ───────────────────────────────────────────────────────────────────────────── - // BitReader — reads individual bits from a JPEG entropy-coded stream. - // Handles byte-stuffing: 0xFF 0x00 → single 0xFF byte. - // ───────────────────────────────────────────────────────────────────────────── - - /// - /// Bit-level reader for JPEG entropy-coded data. - /// Reads bytes MSB-first; transparently strips 0xFF 0x00 stuffing bytes. - /// - internal sealed class BitReader - { - private readonly Stream? _stream; - private readonly byte[]? _bytes; - private int _byteIndex; - private int _buffer; // up to 32 bits buffered - private int _bitsLeft; // valid bits in _buffer - - public BitReader(Stream stream) => - _stream = stream ?? throw new ArgumentNullException(nameof(stream)); - - public BitReader(byte[] bytes) => - _bytes = bytes ?? throw new ArgumentNullException(nameof(bytes)); - - // ── Bit access ─────────────────────────────────────────────────────────── - - /// Read exactly bits (1–16) MSB-first. - public int ReadBits(int n) - { - EnsureBits(n); - _bitsLeft -= n; - return (_buffer >> _bitsLeft) & ((1 << n) - 1); - } - - /// Peek at the next bits without consuming them. - public int PeekBits(int n) - { - EnsureBits(n); - return (_buffer >> (_bitsLeft - n)) & ((1 << n) - 1); - } - - /// Discard bits that were already peeked. - public void ConsumeBits(int n) => _bitsLeft -= n; - - /// Read a single bit (0 or 1). - public int ReadBit() => ReadBits(1); - - // ── Byte-aligned access (used after restart markers) ───────────────────── - - /// Discard any partial byte; reset buffer. Call after a restart marker. - public void Flush() { _buffer = 0; _bitsLeft = 0; } - - // ── Private ────────────────────────────────────────────────────────────── - - private void EnsureBits(int n) - { - while (_bitsLeft < n) - FillByte(); - } - - private void FillByte() - { - if (_bytes != null) - { - int value = _byteIndex < _bytes.Length ? _bytes[_byteIndex++] : 0; - _buffer = (_buffer << 8) | value; - _bitsLeft += 8; - return; - } - - int b = _stream!.ReadByte(); - if (b < 0) { _buffer = (_buffer << 8) | 0xFF; _bitsLeft += 8; return; } - - if (b == 0xFF) - { - int next = _stream.ReadByte(); - if (next == 0x00) - { - // Byte stuffing: 0xFF 0x00 → 0xFF - b = 0xFF; - } - else if (next >= 0xD0 && next <= 0xD7) - { - // Restart marker — treat as end-of-scan; stuff zeros - b = 0; _buffer = (_buffer << 8) | b; _bitsLeft += 8; return; - } - else if (next == 0xD9 || next == 0xDA) - { - // EOI or next SOS — end of entropy data - b = 0; - } - // else: unknown marker in entropy data; ignore - } - _buffer = (_buffer << 8) | b; - _bitsLeft += 8; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegWriter.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/JpegWriter.cs deleted file mode 100644 index 43059c93..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/JpegWriter.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class JpegWriter - { - private readonly Stream _stream; - - public JpegWriter(Stream stream) - { - _stream = stream ?? throw new ArgumentNullException(nameof(stream)); - } - - public void WriteHeaders(int width, int height, Quantizer quantizer) - { - if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width)); - if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height)); - if (quantizer == null) throw new ArgumentNullException(nameof(quantizer)); - - WriteMarker(JpegMarker.SOI); - WriteApp0Jfif(); - WriteDqt(quantizer); - WriteSof0(width, height); - WriteDht(); - WriteSos(); - } - - public void WriteEndOfImage() => WriteMarker(JpegMarker.EOI); - - private void WriteApp0Jfif() - { - WriteMarker(JpegMarker.APP0); - WriteUInt16(16); - WriteAscii("JFIF"); - _stream.WriteByte(0x00); - _stream.WriteByte(0x01); - _stream.WriteByte(0x01); - _stream.WriteByte(0x01); // units = DPI - WriteUInt16(72); - WriteUInt16(72); - _stream.WriteByte(0x00); // no thumbnail - _stream.WriteByte(0x00); - } - - private void WriteDqt(Quantizer quantizer) - { - WriteMarker(JpegMarker.DQT); - int length = 2 + (1 + 64) + (1 + 64); - WriteUInt16((ushort)length); - - _stream.WriteByte(0x00); // Pq=0, Tq=0 (luma) - _stream.Write(quantizer.LuminanceZigZag, 0, 64); - - _stream.WriteByte(0x01); // Pq=0, Tq=1 (chroma) - _stream.Write(quantizer.ChrominanceZigZag, 0, 64); - } - - private void WriteSof0(int width, int height) - { - WriteMarker(JpegMarker.SOF0); - WriteUInt16(17); - _stream.WriteByte(8); // precision - WriteUInt16((ushort)height); - WriteUInt16((ushort)width); - _stream.WriteByte(3); // component count - - // Y component - _stream.WriteByte(1); // id - _stream.WriteByte(0x11); // sampling 1x1 - _stream.WriteByte(0); // quant table 0 - - // Cb component - _stream.WriteByte(2); - _stream.WriteByte(0x11); - _stream.WriteByte(1); - - // Cr component - _stream.WriteByte(3); - _stream.WriteByte(0x11); - _stream.WriteByte(1); - } - - private void WriteDht() - { - WriteMarker(JpegMarker.DHT); - - int length = 2 - + 1 + 16 + HuffmanEncoder.DcLuminanceValues.Length - + 1 + 16 + HuffmanEncoder.DcChrominanceValues.Length - + 1 + 16 + HuffmanEncoder.AcLuminanceValues.Length - + 1 + 16 + HuffmanEncoder.AcChrominanceValues.Length; - WriteUInt16((ushort)length); - - WriteHuffmanTable(0x00, HuffmanEncoder.DcLuminanceCounts, HuffmanEncoder.DcLuminanceValues); - WriteHuffmanTable(0x01, HuffmanEncoder.DcChrominanceCounts, HuffmanEncoder.DcChrominanceValues); - WriteHuffmanTable(0x10, HuffmanEncoder.AcLuminanceCounts, HuffmanEncoder.AcLuminanceValues); - WriteHuffmanTable(0x11, HuffmanEncoder.AcChrominanceCounts, HuffmanEncoder.AcChrominanceValues); - } - - private void WriteSos() - { - WriteMarker(JpegMarker.SOS); - WriteUInt16(12); - _stream.WriteByte(3); // components in scan - - _stream.WriteByte(1); // Y - _stream.WriteByte(0x00); // DC0/AC0 - - _stream.WriteByte(2); // Cb - _stream.WriteByte(0x11); // DC1/AC1 - - _stream.WriteByte(3); // Cr - _stream.WriteByte(0x11); // DC1/AC1 - - _stream.WriteByte(0x00); // Ss - _stream.WriteByte(0x3F); // Se - _stream.WriteByte(0x00); // Ah/Al - } - - private void WriteHuffmanTable(byte classAndId, byte[] counts, byte[] values) - { - _stream.WriteByte(classAndId); - _stream.Write(counts, 0, 16); - _stream.Write(values, 0, values.Length); - } - - private void WriteMarker(JpegMarker marker) - { - _stream.WriteByte(0xFF); - _stream.WriteByte((byte)marker); - } - - private void WriteUInt16(ushort value) - { - _stream.WriteByte((byte)((value >> 8) & 0xFF)); - _stream.WriteByte((byte)(value & 0xFF)); - } - - private void WriteAscii(string text) - { - for (int i = 0; i < text.Length; i++) - _stream.WriteByte((byte)text[i]); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ProgressiveDecoder.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ProgressiveDecoder.cs deleted file mode 100644 index b9952412..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ProgressiveDecoder.cs +++ /dev/null @@ -1,489 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class ProgressiveDecoder - { - private readonly FrameHeader _frame; - private readonly QuantizationTable?[] _quantTables; - private readonly HuffmanTable?[] _dcTables; - private readonly HuffmanTable?[] _acTables; - - public ProgressiveDecoder( - FrameHeader frame, - QuantizationTable?[] quantTables, - HuffmanTable?[] dcTables, - HuffmanTable?[] acTables) - { - _frame = frame ?? throw new ArgumentNullException(nameof(frame)); - _quantTables = quantTables ?? throw new ArgumentNullException(nameof(quantTables)); - _dcTables = dcTables ?? throw new ArgumentNullException(nameof(dcTables)); - _acTables = acTables ?? throw new ArgumentNullException(nameof(acTables)); - } - - public void DecodeScan( - ScanHeader scan, - BitReader reader, - CoefficientBuffer buffer, - int restartInterval) - { - if (scan == null) throw new ArgumentNullException(nameof(scan)); - if (reader == null) throw new ArgumentNullException(nameof(reader)); - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - - if (scan.Components.Length == 0) - throw new InvalidDataException("SOS scan contains no components."); - - int[] scanToFrame = BuildScanToFrameMap(scan); - int[] dcPredictors = new int[_frame.Components.Length]; - int eobRun = 0; - int processedUnits = 0; - - if (scan.Components.Length == 1) - { - int scanComponentIndex = 0; - int frameComponentIndex = scanToFrame[0]; - int blocksX = buffer.GetBlocksX(frameComponentIndex); - int blocksY = buffer.GetBlocksY(frameComponentIndex); - - for (int by = 0; by < blocksY; by++) - { - for (int bx = 0; bx < blocksX; bx++) - { - DecodeBlock( - scan, - scanComponentIndex, - frameComponentIndex, - bx, - by, - reader, - buffer, - dcPredictors, - ref eobRun); - - processedUnits++; - if (restartInterval > 0 && (processedUnits % restartInterval) == 0) - { - Array.Clear(dcPredictors, 0, dcPredictors.Length); - eobRun = 0; - reader.Flush(); - } - } - } - - return; - } - - for (int mcuY = 0; mcuY < buffer.McuCountY; mcuY++) - { - for (int mcuX = 0; mcuX < buffer.McuCountX; mcuX++) - { - for (int scanComponentIndex = 0; scanComponentIndex < scan.Components.Length; scanComponentIndex++) - { - int frameComponentIndex = scanToFrame[scanComponentIndex]; - var frameComponent = _frame.Components[frameComponentIndex]; - - for (int v = 0; v < frameComponent.VSampling; v++) - { - for (int h = 0; h < frameComponent.HSampling; h++) - { - int bx = mcuX * frameComponent.HSampling + h; - int by = mcuY * frameComponent.VSampling + v; - - DecodeBlock( - scan, - scanComponentIndex, - frameComponentIndex, - bx, - by, - reader, - buffer, - dcPredictors, - ref eobRun); - } - } - } - - processedUnits++; - if (restartInterval > 0 && (processedUnits % restartInterval) == 0) - { - Array.Clear(dcPredictors, 0, dcPredictors.Length); - eobRun = 0; - reader.Flush(); - } - } - } - } - - public EntropyDecodeResult BuildImageData(CoefficientBuffer buffer) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - - int componentCount = _frame.Components.Length; - var planes = new byte[componentCount][]; - var planeWidths = new int[componentCount]; - var planeHeights = new int[componentCount]; - - var dequantized = new int[64]; - var pixels = new byte[64]; - - for (int componentIndex = 0; componentIndex < componentCount; componentIndex++) - { - int blocksX = buffer.GetBlocksX(componentIndex); - int blocksY = buffer.GetBlocksY(componentIndex); - int width = blocksX * 8; - int height = blocksY * 8; - - planeWidths[componentIndex] = width; - planeHeights[componentIndex] = height; - planes[componentIndex] = new byte[width * height]; - - int qtId = _frame.Components[componentIndex].QuantizationTableId; - var quant = _quantTables[qtId] ?? throw new InvalidDataException($"Missing quantization table {qtId}."); - - short[] source = buffer.GetComponentData(componentIndex); - - for (int by = 0; by < blocksY; by++) - { - for (int bx = 0; bx < blocksX; bx++) - { - int offset = buffer.GetBlockOffset(componentIndex, bx, by); - for (int i = 0; i < 64; i++) - dequantized[i] = source[offset + i] * quant.Coefficients[i]; - - IdctTransform.TransformBlock(dequantized, pixels); - WriteBlock(planes[componentIndex], width, height, pixels, bx * 8, by * 8); - } - } - } - - return new EntropyDecodeResult( - planes, - planeWidths, - planeHeights, - buffer.MaxHorizontalSampling, - buffer.MaxVerticalSampling, - buffer.McuCountX, - buffer.McuCountY); - } - - private int[] BuildScanToFrameMap(ScanHeader scan) - { - int[] map = new int[scan.Components.Length]; - for (int i = 0; i < scan.Components.Length; i++) - { - byte id = scan.Components[i].ComponentId; - int found = -1; - for (int j = 0; j < _frame.Components.Length; j++) - { - if (_frame.Components[j].Id == id) - { - found = j; - break; - } - } - - if (found < 0) - throw new InvalidDataException($"SOS references unknown component id {id}."); - - map[i] = found; - } - - return map; - } - - private void DecodeBlock( - ScanHeader scan, - int scanComponentIndex, - int frameComponentIndex, - int blockX, - int blockY, - BitReader reader, - CoefficientBuffer buffer, - int[] dcPredictors, - ref int eobRun) - { - int ss = scan.Ss; - int se = scan.Se; - int ah = scan.Ah; - int al = scan.Al; - - var scanComponent = scan.Components[scanComponentIndex]; - HuffmanTable? dc = (uint)scanComponent.DcTableId < _dcTables.Length ? _dcTables[scanComponent.DcTableId] : null; - HuffmanTable? ac = (uint)scanComponent.AcTableId < _acTables.Length ? _acTables[scanComponent.AcTableId] : null; - - if (ss == 0) - { - if (ah == 0) - DecodeDcInitial(dc, reader, buffer, frameComponentIndex, blockX, blockY, ref dcPredictors[frameComponentIndex], al); - else - DecodeDcRefinement(reader, buffer, frameComponentIndex, blockX, blockY, al); - } - - if (se > 0) - { - if (ah == 0) - DecodeAcInitial(ac, reader, buffer, frameComponentIndex, blockX, blockY, ss, se, al, ref eobRun); - else - DecodeAcRefinement(ac, reader, buffer, frameComponentIndex, blockX, blockY, ss, se, al, ref eobRun); - } - } - - private static void DecodeDcInitial( - HuffmanTable? dcTable, - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - ref int predictor, - int al) - { - if (dcTable == null) - throw new InvalidDataException("Missing DC Huffman table for progressive scan."); - - int size = dcTable.Decode(reader); - int diff = ReceiveAndExtend(reader, size); - predictor += diff; - buffer.SetCoefficient(componentIndex, blockX, blockY, 0, (short)(predictor << al)); - } - - private static void DecodeDcRefinement( - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - int al) - { - int bit = reader.ReadBit(); - if (bit == 0) - return; - - short current = buffer.GetCoefficient(componentIndex, blockX, blockY, 0); - short delta = (short)(1 << al); - - if (current >= 0) - buffer.AddCoefficient(componentIndex, blockX, blockY, 0, delta); - else - buffer.AddCoefficient(componentIndex, blockX, blockY, 0, (short)-delta); - } - - private static void DecodeAcInitial( - HuffmanTable? acTable, - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - int ss, - int se, - int al, - ref int eobRun) - { - if (acTable == null) - throw new InvalidDataException("Missing AC Huffman table for progressive scan."); - - if (eobRun > 0) - { - eobRun--; - return; - } - - int k = ss; - while (k <= se) - { - int rs = acTable.Decode(reader); - int run = (rs >> 4) & 0x0F; - int size = rs & 0x0F; - - if (size == 0) - { - if (run == 15) - { - k += 16; - continue; - } - - eobRun = (1 << run) - 1; - if (run > 0) - eobRun += reader.ReadBits(run); - break; - } - - k += run; - if (k > se) - break; - - int value = ReceiveAndExtend(reader, size) << al; - int idx = QuantizationTable.ZigZagOrder[k]; - buffer.SetCoefficient(componentIndex, blockX, blockY, idx, (short)value); - k++; - } - } - - private static void DecodeAcRefinement( - HuffmanTable? acTable, - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - int ss, - int se, - int al, - ref int eobRun) - { - if (acTable == null) - throw new InvalidDataException("Missing AC Huffman table for progressive scan."); - - short refineDelta = (short)(1 << al); - short negativeRefineDelta = (short)-refineDelta; - int k = ss; - - if (eobRun == 0) - { - while (k <= se) - { - int rs = acTable.Decode(reader); - int run = (rs >> 4) & 0x0F; - int size = rs & 0x0F; - - short newCoefficient = 0; - if (size != 0) - { - if (size != 1) - throw new InvalidDataException("Invalid progressive AC refinement symbol."); - - newCoefficient = reader.ReadBit() != 0 ? refineDelta : negativeRefineDelta; - } - else if (run != 15) - { - eobRun = 1 << run; - if (run > 0) - eobRun += reader.ReadBits(run); - break; - } - - while (k <= se) - { - int idx = QuantizationTable.ZigZagOrder[k]; - short current = buffer.GetCoefficient(componentIndex, blockX, blockY, idx); - - if (current != 0) - { - RefineCoefficient(reader, buffer, componentIndex, blockX, blockY, idx, current, refineDelta, negativeRefineDelta); - } - else - { - if (run == 0) - break; - run--; - } - - k++; - } - - if (newCoefficient != 0) - { - if (k <= se) - { - int idx = QuantizationTable.ZigZagOrder[k]; - buffer.SetCoefficient(componentIndex, blockX, blockY, idx, newCoefficient); - k++; - } - } - } - } - - if (eobRun > 0) - { - ApplyRefinementBits(reader, buffer, componentIndex, blockX, blockY, k, se, refineDelta, negativeRefineDelta); - eobRun--; - } - } - - private static void RefineCoefficient( - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - int naturalIndex, - short current, - short refineDelta, - short negativeRefineDelta) - { - if (reader.ReadBit() == 0) - return; - - if ((current & refineDelta) != 0) - return; - - short delta = current > 0 ? refineDelta : negativeRefineDelta; - buffer.AddCoefficient(componentIndex, blockX, blockY, naturalIndex, delta); - } - - private static void ApplyRefinementBits( - BitReader reader, - CoefficientBuffer buffer, - int componentIndex, - int blockX, - int blockY, - int startK, - int endK, - short refineDelta, - short negativeRefineDelta) - { - for (int k = startK; k <= endK; k++) - { - int idx = QuantizationTable.ZigZagOrder[k]; - short current = buffer.GetCoefficient(componentIndex, blockX, blockY, idx); - if (current == 0) - continue; - - RefineCoefficient(reader, buffer, componentIndex, blockX, blockY, idx, current, refineDelta, negativeRefineDelta); - } - } - - private static int ReceiveAndExtend(BitReader reader, int bitCount) - { - if (bitCount == 0) - return 0; - - int value = reader.ReadBits(bitCount); - int threshold = 1 << (bitCount - 1); - if (value < threshold) - value -= (1 << bitCount) - 1; - return value; - } - - private static void WriteBlock( - byte[] plane, - int planeWidth, - int planeHeight, - byte[] block, - int dstX, - int dstY) - { - for (int y = 0; y < 8; y++) - { - int py = dstY + y; - if ((uint)py >= (uint)planeHeight) - continue; - - int srcRow = y * 8; - int dstRow = py * planeWidth; - for (int x = 0; x < 8; x++) - { - int px = dstX + x; - if ((uint)px >= (uint)planeWidth) - continue; - - plane[dstRow + px] = block[srcRow + x]; - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/QuantizationTable.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/QuantizationTable.cs deleted file mode 100644 index e0f32f8b..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/QuantizationTable.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Holds one JPEG quantization table (64 coefficients in natural 8×8 row-major order). - /// Parsed from a DQT segment; input zigzag order is converted to natural order on load. - /// - internal sealed class QuantizationTable - { - // ── Zigzag → natural-order mapping (JPEG ISO 10918-1 Figure A.6) ───────── - internal static readonly int[] ZigZagOrder = { - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63 - }; - - private readonly int[] _table = new int[64]; // natural row-major order - - /// Table destination identifier (0–3). - public int Id { get; private set; } - - /// Element at zigzag position (0–63) in natural order. - public int this[int naturalIndex] => _table[naturalIndex]; - - /// Raw coefficients in natural row-major order (64 elements). - public int[] Coefficients => _table; - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Parses one or more quantization tables from a DQT segment payload. - /// Returns all tables found (typically 1 or 2 per segment). - /// - public static QuantizationTable[] ParseDqt(byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - var tables = new System.Collections.Generic.List(4); - int pos = 0; - while (pos < data.Length) - { - byte pqTq = data[pos++]; - int precision = (pqTq >> 4) & 0xF; // 0 = 8-bit, 1 = 16-bit - int id = pqTq & 0xF; - - var qt = new QuantizationTable { Id = id }; - for (int z = 0; z < 64; z++) - { - int value = precision == 0 - ? data[pos++] - : (data[pos++] << 8) | data[pos++]; - qt._table[ZigZagOrder[z]] = value; - } - tables.Add(qt); - } - return tables.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/Quantizer.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/Quantizer.cs deleted file mode 100644 index 64aa7e40..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/Quantizer.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal sealed class Quantizer - { - private static readonly byte[] LuminanceBaseTable = - { - 16,11,10,16,24,40,51,61, - 12,12,14,19,26,58,60,55, - 14,13,16,24,40,57,69,56, - 14,17,22,29,51,87,80,62, - 18,22,37,56,68,109,103,77, - 24,35,55,64,81,104,113,92, - 49,64,78,87,103,121,120,101, - 72,92,95,98,112,100,103,99, - }; - - private static readonly byte[] ChrominanceBaseTable = - { - 17,18,24,47,99,99,99,99, - 18,21,26,66,99,99,99,99, - 24,26,56,99,99,99,99,99, - 47,66,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99, - }; - - private Quantizer(ushort[] lumaNatural, ushort[] chromaNatural) - { - LuminanceNatural = lumaNatural; - ChrominanceNatural = chromaNatural; - LuminanceZigZag = ToZigZag(lumaNatural); - ChrominanceZigZag = ToZigZag(chromaNatural); - } - - public ushort[] LuminanceNatural { get; } - public ushort[] ChrominanceNatural { get; } - public byte[] LuminanceZigZag { get; } - public byte[] ChrominanceZigZag { get; } - - public static Quantizer Create(int quality) - { - quality = Math.Max(1, Math.Min(100, quality)); - ushort[] luma = ScaleTable(LuminanceBaseTable, quality); - ushort[] chroma = ScaleTable(ChrominanceBaseTable, quality); - return new Quantizer(luma, chroma); - } - - private static ushort[] ScaleTable(byte[] baseTable, int quality) - { - int scale = quality < 50 ? 5000 / quality : 200 - (2 * quality); - var table = new ushort[64]; - - for (int i = 0; i < 64; i++) - { - int value = (baseTable[i] * scale + 50) / 100; - if (value < 1) value = 1; - if (value > 255) value = 255; - table[i] = (ushort)value; - } - - return table; - } - - private static byte[] ToZigZag(ushort[] naturalTable) - { - var zigzag = new byte[64]; - for (int i = 0; i < 64; i++) - { - int naturalIndex = QuantizationTable.ZigZagOrder[i]; - zigzag[i] = (byte)naturalTable[naturalIndex]; - } - - return zigzag; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ScanComponent.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ScanComponent.cs deleted file mode 100644 index 733fd1b1..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ScanComponent.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Per-component selector inside a JPEG SOS (Start-of-Scan) header. - /// - internal struct ScanComponent - { - /// Component identifier (matches a ). - public byte ComponentId; - - /// DC Huffman table id (0–3). - public byte DcTableId; - - /// AC Huffman table id (0–3). - public byte AcTableId; - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/ScanHeader.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/ScanHeader.cs deleted file mode 100644 index 10edb817..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/ScanHeader.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - /// - /// Parsed payload of a JPEG SOS (Start-of-Scan) marker. - /// - internal sealed class ScanHeader - { - /// Components included in this scan. - public ScanComponent[] Components { get; private set; } = Array.Empty(); - - /// Start of spectral selection (0 for sequential). - public int Ss { get; private set; } - - /// End of spectral selection (63 for sequential). - public int Se { get; private set; } - - /// Successive approximation high (0 for first/only pass). - public int Ah { get; private set; } - - /// Successive approximation low (0 for sequential). - public int Al { get; private set; } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// Parses a SOS segment payload. - public static ScanHeader Parse(byte[] data) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (data.Length < 4) - throw new InvalidDataException("SOS segment too short."); - - int ns = data[0]; - if (data.Length < 1 + ns * 2 + 3) - throw new InvalidDataException("SOS segment truncated."); - - var sh = new ScanHeader(); - sh.Components = new ScanComponent[ns]; - for (int i = 0; i < ns; i++) - { - int off = 1 + i * 2; - byte sel = data[off + 1]; - sh.Components[i] = new ScanComponent - { - ComponentId = data[off], - DcTableId = (byte)((sel >> 4) & 0xF), - AcTableId = (byte)(sel & 0xF), - }; - } - - int tail = 1 + ns * 2; - sh.Ss = data[tail]; - sh.Se = data[tail + 1]; - byte ahAl = data[tail + 2]; - sh.Ah = (ahAl >> 4) & 0xF; - sh.Al = ahAl & 0xF; - return sh; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Jpeg/UpsampleBuffer.cs b/src/MiniPdf/Drawing/Codecs/Jpeg/UpsampleBuffer.cs deleted file mode 100644 index 6f30cf04..00000000 --- a/src/MiniPdf/Drawing/Codecs/Jpeg/UpsampleBuffer.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Codecs.Jpeg -{ - internal static class UpsampleBuffer - { - public static byte[] UpsampleToFullResolution( - byte[] source, - int sourceWidth, - int sourceHeight, - int targetWidth, - int targetHeight, - int horizontalSampling, - int verticalSampling, - int maxHorizontalSampling, - int maxVerticalSampling) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (sourceWidth <= 0 || sourceHeight <= 0) - throw new ArgumentOutOfRangeException(nameof(sourceWidth)); - if (targetWidth <= 0 || targetHeight <= 0) - throw new ArgumentOutOfRangeException(nameof(targetWidth)); - - var upsampled = new byte[targetWidth * targetHeight]; - - for (int y = 0; y < targetHeight; y++) - { - int sy = (y * verticalSampling) / maxVerticalSampling; - if (sy >= sourceHeight) sy = sourceHeight - 1; - - int dstRow = y * targetWidth; - int srcRow = sy * sourceWidth; - for (int x = 0; x < targetWidth; x++) - { - int sx = (x * horizontalSampling) / maxHorizontalSampling; - if (sx >= sourceWidth) sx = sourceWidth - 1; - upsampled[dstRow + x] = source[srcRow + sx]; - } - } - - return upsampled; - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/JpegCodec.cs b/src/MiniPdf/Drawing/Codecs/JpegCodec.cs deleted file mode 100644 index 7597e41c..00000000 --- a/src/MiniPdf/Drawing/Codecs/JpegCodec.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// - /// JPEG codec. - /// Encode and decode use the managed MiniSoftware.Drawing JPEG pipeline. - /// - internal sealed class JpegCodec : IImageCodec - { - public bool CanDecode(byte[] header) - => header.Length >= 3 - && header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF; - - // ─── Decode ────────────────────────────────────────────────────────────── - - public Bitmap Decode(Stream stream) - { - var decoder = new Jpeg.JpegDecoder(); - return decoder.Decode(stream); - } - - // ─── Encode ────────────────────────────────────────────────────────────── - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - var encoder = new Jpeg.JpegEncoder(); - encoder.Encode(bmp, stream, parameters); - } - } -} diff --git a/src/MiniPdf/Drawing/Codecs/Png/ApngChunkData.cs b/src/MiniPdf/Drawing/Codecs/Png/ApngChunkData.cs deleted file mode 100644 index 0667fbd8..00000000 --- a/src/MiniPdf/Drawing/Codecs/Png/ApngChunkData.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs.Png -{ - internal readonly struct ApngFrameControl - { - public uint SequenceNumber { get; } - public int Width { get; } - public int Height { get; } - public int XOffset { get; } - public int YOffset { get; } - public ushort DelayNum { get; } - public ushort DelayDen { get; } - public FrameDisposeMethod DisposeMethod { get; } - public FrameBlendMethod BlendMethod { get; } - - public ApngFrameControl( - uint sequenceNumber, int width, int height, - int xOffset, int yOffset, - ushort delayNum, ushort delayDen, - FrameDisposeMethod disposeMethod, FrameBlendMethod blendMethod) - { - SequenceNumber = sequenceNumber; - Width = width; - Height = height; - XOffset = xOffset; - YOffset = yOffset; - DelayNum = delayNum; - DelayDen = delayDen; - DisposeMethod = disposeMethod; - BlendMethod = blendMethod; - } - - public int DelayMilliseconds - { - get - { - int den = DelayDen == 0 ? 100 : DelayDen; - if (den == 0) den = 100; - return (int)((DelayNum * 1000L) / den); - } - } - - public Rectangle Bounds => new Rectangle(XOffset, YOffset, Width, Height); - - public static ApngFrameControl Parse(byte[] data) - { - if (data == null || data.Length < 26) - throw new System.IO.InvalidDataException("fcTL chunk too short."); - - uint seq = BinaryBE.ReadUInt32(data, 0); - int w = (int)BinaryBE.ReadUInt32(data, 4); - int h = (int)BinaryBE.ReadUInt32(data, 8); - int x = (int)BinaryBE.ReadUInt32(data, 12); - int y = (int)BinaryBE.ReadUInt32(data, 16); - ushort delayNum = BinaryBE.ReadUInt16(data, 20); - ushort delayDen = BinaryBE.ReadUInt16(data, 22); - var dispose = (FrameDisposeMethod)data[24]; - var blend = (FrameBlendMethod)data[25]; - return new ApngFrameControl(seq, w, h, x, y, delayNum, delayDen, dispose, blend); - } - } - - internal readonly struct ApngAnimationControl - { - public int NumFrames { get; } - public int NumPlays { get; } - - public ApngAnimationControl(int numFrames, int numPlays) - { - NumFrames = numFrames; - NumPlays = numPlays; - } - - public static ApngAnimationControl Parse(byte[] data) - { - if (data == null || data.Length < 8) - throw new System.IO.InvalidDataException("acTL chunk too short."); - int n = (int)BinaryBE.ReadUInt32(data, 0); - int p = (int)BinaryBE.ReadUInt32(data, 4); - return new ApngAnimationControl(n, p); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Codecs/Png/ApngFrameBuilder.cs b/src/MiniPdf/Drawing/Codecs/Png/ApngFrameBuilder.cs deleted file mode 100644 index 3a211501..00000000 --- a/src/MiniPdf/Drawing/Codecs/Png/ApngFrameBuilder.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs.Png -{ - internal static class ApngFrameBuilder - { - public static AnimationFrame Build( - ApngFrameControl fc, - byte[] compressed, - int bitDepth, int colorType, - byte[]? palette, byte[]? trns) - { - byte[] raw = ZlibHelper.Decompress(compressed); - - int channels = PngHelpers.GetChannels(colorType); - int stride = (fc.Width * bitDepth * channels + 7) / 8; - int bpp = System.Math.Max(1, (bitDepth * channels) / 8); - - byte[] pixels = PngHelpers.ReconstructFilters(raw, fc.Width, fc.Height, stride, bpp); - - var bgra = new byte[fc.Width * fc.Height * 4]; - for (int y = 0; y < fc.Height; y++) - for (int x = 0; x < fc.Width; x++) - { - PngHelpers.GetPixelRgba(pixels, x, y, stride, bitDepth, colorType, - palette, trns, out byte r, out byte g, out byte b, out byte a); - int off = y * fc.Width * 4 + x * 4; - bgra[off] = b; - bgra[off + 1] = g; - bgra[off + 2] = r; - bgra[off + 3] = a; - } - - var frame = new AnimationFrame(fc.Bounds, bgra) - { - DelayMilliseconds = fc.DelayMilliseconds, - DisposeMethod = fc.DisposeMethod, - BlendMethod = fc.BlendMethod - }; - return frame; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Codecs/Png/PngHelpers.cs b/src/MiniPdf/Drawing/Codecs/Png/PngHelpers.cs deleted file mode 100644 index eb4848af..00000000 --- a/src/MiniPdf/Drawing/Codecs/Png/PngHelpers.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Codecs.Png -{ - internal static class PngHelpers - { - public static int GetChannels(int colorType) - { - switch (colorType) - { - case 0: return 1; - case 2: return 3; - case 3: return 1; - case 4: return 2; - case 6: return 4; - default: return 3; - } - } - - public static byte[] ReconstructFilters(byte[] raw, int width, int height, int stride, int bpp) - { - var result = new byte[height * stride]; - var prev = new byte[stride]; - - for (int y = 0; y < height; y++) - { - int rowOff = y * (stride + 1); - int filterType = raw[rowOff]; - int dstOff = y * stride; - - switch (filterType) - { - case 0: - Buffer.BlockCopy(raw, rowOff + 1, result, dstOff, stride); - break; - case 1: - for (int i = 0; i < stride; i++) - { - byte a = i >= bpp ? result[dstOff + i - bpp] : (byte)0; - result[dstOff + i] = (byte)(raw[rowOff + 1 + i] + a); - } - break; - case 2: - for (int i = 0; i < stride; i++) - result[dstOff + i] = (byte)(raw[rowOff + 1 + i] + prev[i]); - break; - case 3: - for (int i = 0; i < stride; i++) - { - byte a = i >= bpp ? result[dstOff + i - bpp] : (byte)0; - byte b = prev[i]; - result[dstOff + i] = (byte)(raw[rowOff + 1 + i] + (a + b) / 2); - } - break; - case 4: - for (int i = 0; i < stride; i++) - { - byte a = i >= bpp ? result[dstOff + i - bpp] : (byte)0; - byte b = prev[i]; - byte c = i >= bpp ? prev[i - bpp] : (byte)0; - result[dstOff + i] = (byte)(raw[rowOff + 1 + i] + PaethPredictor(a, b, c)); - } - break; - default: - Buffer.BlockCopy(raw, rowOff + 1, result, dstOff, stride); - break; - } - - Buffer.BlockCopy(result, dstOff, prev, 0, stride); - } - - return result; - } - - public static byte PaethPredictor(byte a, byte b, byte c) - { - int p = a + b - c; - int pa = Math.Abs(p - a); - int pb = Math.Abs(p - b); - int pc = Math.Abs(p - c); - if (pa <= pb && pa <= pc) return a; - if (pb <= pc) return b; - return c; - } - - public static void GetPixelRgba(byte[] pixels, int x, int y, - int stride, int bitDepth, int colorType, - byte[]? palette, byte[]? trns, - out byte r, out byte g, out byte b, out byte a) - { - int rowOff = y * stride; - r = g = b = 0; a = 255; - - switch (colorType) - { - case 0: - { - byte grey; - if (bitDepth == 8) - { - grey = pixels[rowOff + x]; - } - else if (bitDepth == 16) - { - grey = pixels[rowOff + x * 2]; - } - else - { - int samplesPerByte = 8 / bitDepth; - int byteIdx = x / samplesPerByte; - int bitShift = 8 - bitDepth - (x % samplesPerByte) * bitDepth; - int mask = (1 << bitDepth) - 1; - int raw = (pixels[rowOff + byteIdx] >> bitShift) & mask; - grey = (byte)(raw * 255 / mask); - } - r = g = b = grey; - if (trns != null && trns.Length >= 2) - { - int trnsVal = (trns[0] << 8) | trns[1]; - a = (grey == (byte)(trnsVal >> (bitDepth == 8 ? 0 : 8))) ? (byte)0 : (byte)255; - } - break; - } - case 2: - { - if (bitDepth == 8) - { - int off = rowOff + x * 3; - r = pixels[off]; g = pixels[off + 1]; b = pixels[off + 2]; - } - else - { - int off = rowOff + x * 6; - r = pixels[off]; g = pixels[off + 2]; b = pixels[off + 4]; - } - if (trns != null && trns.Length >= 6) - { - if (r == trns[1] && g == trns[3] && b == trns[5]) a = 0; - } - break; - } - case 3: - { - int idx; - if (bitDepth == 8) - { - idx = pixels[rowOff + x]; - } - else - { - int samplesPerByte = 8 / bitDepth; - int byteIdx = x / samplesPerByte; - int bitShift = 8 - bitDepth - (x % samplesPerByte) * bitDepth; - int mask = (1 << bitDepth) - 1; - idx = (pixels[rowOff + byteIdx] >> bitShift) & mask; - } - if (palette != null && idx * 3 + 2 < palette.Length) - { - r = palette[idx * 3]; - g = palette[idx * 3 + 1]; - b = palette[idx * 3 + 2]; - } - a = (trns != null && idx < trns.Length) ? trns[idx] : (byte)255; - break; - } - case 4: - { - if (bitDepth == 8) - { - int off = rowOff + x * 2; - r = g = b = pixels[off]; a = pixels[off + 1]; - } - else - { - int off = rowOff + x * 4; - r = g = b = pixels[off]; a = pixels[off + 2]; - } - break; - } - case 6: - { - if (bitDepth == 8) - { - int off = rowOff + x * 4; - r = pixels[off]; g = pixels[off + 1]; b = pixels[off + 2]; a = pixels[off + 3]; - } - else - { - int off = rowOff + x * 8; - r = pixels[off]; g = pixels[off + 2]; b = pixels[off + 4]; a = pixels[off + 6]; - } - break; - } - } - } - - public static void ReadFull(Stream s, byte[] buf, int offset, int count) - { - int total = 0; - while (total < count) - { - int n = s.Read(buf, offset + total, count - total); - if (n <= 0) throw new EndOfStreamException("Unexpected end of PNG stream."); - total += n; - } - } - - public static void WriteChunk(Stream s, string type, byte[] data) - { - var typeBuf = System.Text.Encoding.ASCII.GetBytes(type); - - var lenBuf = new byte[4]; - BinaryBE.WriteUInt32(lenBuf, 0, (uint)data.Length); - s.Write(lenBuf, 0, 4); - s.Write(typeBuf, 0, 4); - if (data.Length > 0) s.Write(data, 0, data.Length); - - var combined = new byte[4 + data.Length]; - Buffer.BlockCopy(typeBuf, 0, combined, 0, 4); - if (data.Length > 0) Buffer.BlockCopy(data, 0, combined, 4, data.Length); - uint crc = Crc32.Compute(combined, 0, combined.Length); - - s.WriteByte((byte)(crc >> 24)); - s.WriteByte((byte)(crc >> 16)); - s.WriteByte((byte)(crc >> 8)); - s.WriteByte((byte)crc); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Codecs/PngCodec.cs b/src/MiniPdf/Drawing/Codecs/PngCodec.cs deleted file mode 100644 index d8f3e62f..00000000 --- a/src/MiniPdf/Drawing/Codecs/PngCodec.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Codecs.Png; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - internal sealed class PngCodec : IImageCodec - { - private static readonly byte[] Signature = { 137, 80, 78, 71, 13, 10, 26, 10 }; - - public bool CanDecode(byte[] header) - { - if (header.Length < 8) return false; - for (int i = 0; i < 8; i++) - if (header[i] != Signature[i]) return false; - return true; - } - - // ─── Decode ────────────────────────────────────────────────────────────── - - public Bitmap Decode(Stream stream) - { - var sig = new byte[8]; - PngHelpers.ReadFull(stream, sig, 0, 8); - - int width = 0, height = 0, bitDepth = 0, colorType = 0, interlace = 0; - byte[]? palette = null; - byte[]? trnsData = null; - int dpiX = 0, dpiY = 0; - var idatBuffer = new List(); - - ApngAnimationControl? acTL = null; - ApngFrameControl? pendingFC = null; - ApngFrameControl? defaultImageFC = null; - var frameDataList = new List<(ApngFrameControl fc, List data)>(); - bool defaultImageIsFrame0 = false; - bool sawFirstIdat = false; - - while (true) - { - var lenBuf = new byte[8]; - PngHelpers.ReadFull(stream, lenBuf, 0, 8); - int chunkLen = (int)BinaryBE.ReadUInt32(lenBuf, 0); - string chunkType = System.Text.Encoding.ASCII.GetString(lenBuf, 4, 4); - - byte[] chunkData = new byte[chunkLen]; - if (chunkLen > 0) PngHelpers.ReadFull(stream, chunkData, 0, chunkLen); - - var crcBuf = new byte[4]; - PngHelpers.ReadFull(stream, crcBuf, 0, 4); - - switch (chunkType) - { - case "IHDR": - width = (int)BinaryBE.ReadUInt32(chunkData, 0); - height = (int)BinaryBE.ReadUInt32(chunkData, 4); - bitDepth = chunkData[8]; - colorType = chunkData[9]; - interlace = chunkData[12]; - if (interlace != 0) - throw new NotSupportedException("Interlaced PNG is not supported."); - break; - - case "PLTE": - palette = chunkData; - break; - - case "tRNS": - trnsData = chunkData; - break; - - case "pHYs": - if (chunkLen >= 9 && chunkData[8] == 1) - { - dpiX = (int)(BinaryBE.ReadUInt32(chunkData, 0) * 0.0254f); - dpiY = (int)(BinaryBE.ReadUInt32(chunkData, 4) * 0.0254f); - } - break; - - case "acTL": - acTL = ApngAnimationControl.Parse(chunkData); - break; - - case "fcTL": - pendingFC = ApngFrameControl.Parse(chunkData); - if (!sawFirstIdat && defaultImageFC == null) - { - defaultImageFC = pendingFC; - defaultImageIsFrame0 = true; - } - break; - - case "IDAT": - idatBuffer.AddRange(chunkData); - if (!sawFirstIdat) - sawFirstIdat = true; - break; - - case "fdAT": - if (pendingFC.HasValue) - { - var data = new List(chunkLen - 4); - for (int i = 4; i < chunkLen; i++) - data.Add(chunkData[i]); - frameDataList.Add((pendingFC.Value, data)); - pendingFC = null; - } - break; - - case "IEND": - goto done; - } - } - done: - - byte[] compressed = idatBuffer.ToArray(); - byte[] raw = ZlibHelper.Decompress(compressed); - - int channels = PngHelpers.GetChannels(colorType); - int stride = (width * bitDepth * channels + 7) / 8; - int bppFilter = Math.Max(1, (bitDepth * channels) / 8); - - byte[] pixels = PngHelpers.ReconstructFilters(raw, width, height, stride, bppFilter); - - var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); - bmp._rawFormat = ImageFormat.Png; - if (dpiX > 0) bmp._dpiX = dpiX; - if (dpiY > 0) bmp._dpiY = dpiY; - - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) - { - PngHelpers.GetPixelRgba(pixels, x, y, stride, bitDepth, colorType, - palette, trnsData, out byte r, out byte g, out byte b, out byte a); - int off = y * bmp._stride + x * 4; - bmp._pixels[off] = b; - bmp._pixels[off + 1] = g; - bmp._pixels[off + 2] = r; - bmp._pixels[off + 3] = a; - } - - if (acTL.HasValue && acTL.Value.NumFrames > 0) - { - var frames = new List(); - - if (defaultImageIsFrame0 && defaultImageFC.HasValue) - { - frames.Add(ApngFrameBuilder.Build( - defaultImageFC.Value, compressed, bitDepth, colorType, palette, trnsData)); - } - - foreach (var (fc, data) in frameDataList) - { - frames.Add(ApngFrameBuilder.Build( - fc, data.ToArray(), bitDepth, colorType, palette, trnsData)); - } - - bmp.SetAnimationFrames(frames, acTL.Value.NumPlays); - } - - return bmp; - } - - // ─── Encode ────────────────────────────────────────────────────────────── - - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - int frameCount = bmp.GetFrameCount(FrameDimension.Time); - if (frameCount > 1) - { - EncodeApng(bmp, stream, frameCount); - return; - } - - EncodeStatic(bmp, stream); - } - - private static void EncodeStatic(Bitmap bmp, Stream stream) - { - bool hasAlpha = bmp._format == PixelFormat.Format32bppArgb - || bmp._format == PixelFormat.Format32bppPArgb; - int channels = hasAlpha ? 4 : 3; - int colorTypeOut = hasAlpha ? 6 : 2; - - int rawStride = bmp._width * channels; - var rawData = new byte[(rawStride + 1) * bmp._height]; - for (int y = 0; y < bmp._height; y++) - { - int rawRow = y * (rawStride + 1); - rawData[rawRow] = 0; - for (int x = 0; x < bmp._width; x++) - { - int srcOff = y * bmp._stride + x * Bitmap.GetBytesPerPixel(bmp._format); - byte b = bmp._pixels[srcOff]; - byte g = bmp._pixels[srcOff + 1]; - byte r = bmp._pixels[srcOff + 2]; - byte a = Bitmap.GetBytesPerPixel(bmp._format) >= 4 ? bmp._pixels[srcOff + 3] : (byte)255; - - int dst = rawRow + 1 + x * channels; - rawData[dst] = r; - rawData[dst + 1] = g; - rawData[dst + 2] = b; - if (hasAlpha) rawData[dst + 3] = a; - } - } - - byte[] idatData = ZlibHelper.Compress(rawData); - - uint ppmX = (uint)Math.Round(bmp._dpiX / 0.0254); - uint ppmY = (uint)Math.Round(bmp._dpiY / 0.0254); - - stream.Write(Signature, 0, 8); - - var ihdr = new byte[13]; - BinaryBE.WriteUInt32(ihdr, 0, (uint)bmp._width); - BinaryBE.WriteUInt32(ihdr, 4, (uint)bmp._height); - ihdr[8] = 8; - ihdr[9] = (byte)colorTypeOut; - ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; - PngHelpers.WriteChunk(stream, "IHDR", ihdr); - - var phys = new byte[9]; - BinaryBE.WriteUInt32(phys, 0, ppmX); - BinaryBE.WriteUInt32(phys, 4, ppmY); - phys[8] = 1; - PngHelpers.WriteChunk(stream, "pHYs", phys); - - PngHelpers.WriteChunk(stream, "IDAT", idatData); - PngHelpers.WriteChunk(stream, "IEND", Array.Empty()); - } - - private static void EncodeApng(Bitmap bmp, Stream stream, int frameCount) - { - int canvasW = bmp._width; - int canvasH = bmp._height; - - uint ppmX = (uint)Math.Round(bmp._dpiX / 0.0254); - uint ppmY = (uint)Math.Round(bmp._dpiY / 0.0254); - - stream.Write(Signature, 0, 8); - - var ihdr = new byte[13]; - BinaryBE.WriteUInt32(ihdr, 0, (uint)canvasW); - BinaryBE.WriteUInt32(ihdr, 4, (uint)canvasH); - ihdr[8] = 8; - ihdr[9] = 6; - ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; - PngHelpers.WriteChunk(stream, "IHDR", ihdr); - - var phys = new byte[9]; - BinaryBE.WriteUInt32(phys, 0, ppmX); - BinaryBE.WriteUInt32(phys, 4, ppmY); - phys[8] = 1; - PngHelpers.WriteChunk(stream, "pHYs", phys); - - var actl = new byte[8]; - BinaryBE.WriteUInt32(actl, 0, (uint)frameCount); - BinaryBE.WriteUInt32(actl, 4, 0); - PngHelpers.WriteChunk(stream, "acTL", actl); - - uint seq = 0; - for (int i = 0; i < frameCount; i++) - { - bmp.SelectActiveFrame(FrameDimension.Time, i); - byte[] framePixels = bmp._pixels; - - int rawStride = canvasW * 4; - var rawData = new byte[(rawStride + 1) * canvasH]; - for (int y = 0; y < canvasH; y++) - { - int rawRow = y * (rawStride + 1); - rawData[rawRow] = 0; - int srcOff = y * bmp._stride; - for (int x = 0; x < canvasW; x++) - { - int dst = rawRow + 1 + x * 4; - rawData[dst] = framePixels[srcOff + x * 4 + 2]; - rawData[dst + 1] = framePixels[srcOff + x * 4 + 1]; - rawData[dst + 2] = framePixels[srcOff + x * 4]; - rawData[dst + 3] = framePixels[srcOff + x * 4 + 3]; - } - } - - byte[] compressed = ZlibHelper.Compress(rawData); - - var fctl = new byte[26]; - BinaryBE.WriteUInt32(fctl, 0, seq++); - BinaryBE.WriteUInt32(fctl, 4, (uint)canvasW); - BinaryBE.WriteUInt32(fctl, 8, (uint)canvasH); - BinaryBE.WriteUInt32(fctl, 12, 0); - BinaryBE.WriteUInt32(fctl, 16, 0); - BinaryBE.WriteUInt16(fctl, 20, 10); - BinaryBE.WriteUInt16(fctl, 22, 100); - fctl[24] = 0; - fctl[25] = 0; - PngHelpers.WriteChunk(stream, "fcTL", fctl); - - if (i == 0) - { - PngHelpers.WriteChunk(stream, "IDAT", compressed); - } - else - { - var fdat = new byte[4 + compressed.Length]; - BinaryBE.WriteUInt32(fdat, 0, seq++); - Buffer.BlockCopy(compressed, 0, fdat, 4, compressed.Length); - PngHelpers.WriteChunk(stream, "fdAT", fdat); - } - } - - PngHelpers.WriteChunk(stream, "IEND", Array.Empty()); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Codecs/TiffCodec.cs b/src/MiniPdf/Drawing/Codecs/TiffCodec.cs deleted file mode 100644 index 09194ed9..00000000 --- a/src/MiniPdf/Drawing/Codecs/TiffCodec.cs +++ /dev/null @@ -1,214 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Codecs -{ - /// - /// TIFF codec — write/read uncompressed baseline TIFF (little-endian). - /// Supports RGB (samples-per-pixel = 3) and RGBA (spp = 4). - /// - internal sealed class TiffCodec : IImageCodec - { - public bool CanDecode(byte[] header) - => header.Length >= 4 - && ((header[0] == 0x49 && header[1] == 0x49 && header[2] == 0x2A && header[3] == 0x00) // LE - || (header[0] == 0x4D && header[1] == 0x4D && header[2] == 0x00 && header[3] == 0x2A)); // BE - - // ─── Decode ────────────────────────────────────────────────────────────── - - public Bitmap Decode(Stream stream) - { - byte[] file = ReadAll(stream); - bool isLE = file[0] == 0x49; - - uint ifdOff = ReadU32(file, 4, isLE); - uint ifdCount = ReadU16(file, (int)ifdOff, isLE); - - uint imageWidth = 0, imageHeight = 0; - uint compression = 1; - uint photoInterp = 2; - uint spp = 3; - uint bitsPerSamp = 8; - uint stripOff = 0; - uint stripBytes = 0; - uint extraSamples = 0; - - int entryBase = (int)ifdOff + 2; - for (int i = 0; i < ifdCount; i++) - { - int e = entryBase + i * 12; - uint tag = ReadU16(file, e, isLE); - uint type = ReadU16(file, e + 2, isLE); - uint count = ReadU32(file, e + 4, isLE); - uint valOff = ReadU32(file, e + 8, isLE); - - // If value fits in 4 bytes it's stored inline (LE: LSB first) - switch (tag) - { - case 256: imageWidth = GetU32Val(file, e, type, count, valOff, isLE); break; - case 257: imageHeight = GetU32Val(file, e, type, count, valOff, isLE); break; - case 258: bitsPerSamp = GetU16InlineVal(file, e, isLE); break; - case 259: compression = GetU16InlineVal(file, e, isLE); break; - case 262: photoInterp = GetU16InlineVal(file, e, isLE); break; - case 273: stripOff = GetU32Val(file, e, type, count, valOff, isLE); break; - case 277: spp = GetU16InlineVal(file, e, isLE); break; - case 279: stripBytes = GetU32Val(file, e, type, count, valOff, isLE); break; - case 338: extraSamples = GetU16InlineVal(file, e, isLE); break; - } - } - - if (compression != 1) - throw new NotSupportedException("Only uncompressed TIFF (compression=1) is supported."); - - int w = (int)imageWidth, h = (int)imageHeight; - bool hasAlpha = (spp == 4 && extraSamples == 1) - || (spp == 4 && photoInterp == 2); - - var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb); - bmp._rawFormat = ImageFormat.Tiff; - - int srcSpp = (int)spp; - for (int y = 0; y < h; y++) - for (int x = 0; x < w; x++) - { - int srcOff = (int)stripOff + (y * w + x) * srcSpp; - byte r = file[srcOff]; - byte g = file[srcOff + 1]; - byte bl = file[srcOff + 2]; - byte a = (srcSpp >= 4) ? file[srcOff + 3] : (byte)255; - int dstOff = y * bmp._stride + x * 4; - bmp._pixels[dstOff] = bl; - bmp._pixels[dstOff + 1] = g; - bmp._pixels[dstOff + 2] = r; - bmp._pixels[dstOff + 3] = a; - } - - return bmp; - } - - // ─── Encode ────────────────────────────────────────────────────────────── - // - // Layout (LE, uncompressed): - // [8 header] [IFD: 2+12*n+4] [BitsPerSample array] [XRes RATIONAL] [YRes RATIONAL] [pixels] - // - public void Encode(Bitmap bmp, Stream stream, EncoderParameters? parameters) - { - bool hasAlpha = bmp._format == PixelFormat.Format32bppArgb - || bmp._format == PixelFormat.Format32bppPArgb; - int spp = hasAlpha ? 4 : 3; - int w = bmp._width, h = bmp._height; - int pixelSize = w * h * spp; - int numTags = hasAlpha ? 13 : 12; - - // Offsets (all relative to file start) - // header=8, IFD=8, ifd size = 2 + 12*numTags + 4 - int ifdOff = 8; - int ifdSize = 2 + 12 * numTags + 4; - int bpsOff = ifdOff + ifdSize; // BitsPerSample SHORT[spp] - int bpsSize = spp * 2; - int xResOff = bpsOff + bpsSize; // XResolution RATIONAL - int yResOff = xResOff + 8; // YResolution RATIONAL - int pixelOff = yResOff + 8; - - // Build IFD entries (sorted by tag) - var tags = new List<(ushort tag, ushort type, uint count, uint val)>(); - - void AddTag(ushort tag, ushort type, uint count, uint val) - => tags.Add((tag, type, count, val)); - - const ushort SHORT = 3; - const ushort LONG = 4; - const ushort RATIONAL = 5; - - AddTag(256, LONG, 1, (uint)w); - AddTag(257, LONG, 1, (uint)h); - AddTag(258, SHORT, (uint)spp, (uint)bpsOff); // offset to BPS array - AddTag(259, SHORT, 1, 1); // Compression = none - AddTag(262, SHORT, 1, 2); // RGB - AddTag(273, LONG, 1, (uint)pixelOff); - AddTag(277, SHORT, 1, (uint)spp); - AddTag(278, LONG, 1, (uint)h); - AddTag(279, LONG, 1, (uint)pixelSize); - AddTag(282, RATIONAL, 1, (uint)xResOff); - AddTag(283, RATIONAL, 1, (uint)yResOff); - AddTag(296, SHORT, 1, 2); // ResolutionUnit = inch - if (hasAlpha) - AddTag(338, SHORT, 1, 1); // ExtraSamples = unassociated alpha - - // ── Write ──────────────────────────────────────────────────────────── - using var bw = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true); - - // Header - bw.Write((byte)'I'); bw.Write((byte)'I'); // little-endian - bw.Write((ushort)42); - bw.Write((uint)ifdOff); - - // IFD - bw.Write((ushort)numTags); - foreach (var (tag, type, count, val) in tags) - { - bw.Write(tag); bw.Write(type); bw.Write(count); bw.Write(val); - } - bw.Write((uint)0); // next IFD offset = 0 - - // BitsPerSample array (8,8,8 or 8,8,8,8) - for (int i = 0; i < spp; i++) bw.Write((ushort)8); - - // XResolution and YResolution RATIONALs (96 dpi = 96/1) - uint dpiN = (uint)Math.Round(bmp._dpiX); - bw.Write(dpiN); bw.Write((uint)1); - uint dpiNy = (uint)Math.Round(bmp._dpiY); - bw.Write(dpiNy); bw.Write((uint)1); - - // Pixel data: top-down, RGB or RGBA (not BGRA) - for (int y = 0; y < h; y++) - for (int x = 0; x < w; x++) - { - int srcOff = y * bmp._stride + x * Bitmap.GetBytesPerPixel(bmp._format); - byte b = bmp._pixels[srcOff]; - byte g = bmp._pixels[srcOff + 1]; - byte r = bmp._pixels[srcOff + 2]; - byte a = Bitmap.GetBytesPerPixel(bmp._format) >= 4 ? bmp._pixels[srcOff + 3] : (byte)255; - bw.Write(r); bw.Write(g); bw.Write(b); - if (hasAlpha) bw.Write(a); - } - } - - // ─── Private helpers ───────────────────────────────────────────────────── - - private static byte[] ReadAll(Stream s) - { - using var ms = new MemoryStream(); - s.CopyTo(ms); - return ms.ToArray(); - } - - private static uint ReadU32(byte[] d, int off, bool isLE) - => isLE - ? (uint)(d[off] | (d[off+1]<<8) | (d[off+2]<<16) | (d[off+3]<<24)) - : (uint)((d[off]<<24) | (d[off+1]<<16) | (d[off+2]<<8) | d[off+3]); - - private static uint ReadU16(byte[] d, int off, bool isLE) - => isLE ? (uint)(d[off] | (d[off+1] << 8)) - : (uint)((d[off] << 8) | d[off+1]); - - // Return the 32-bit value for an IFD entry, handling inline vs. offset storage - private static uint GetU32Val(byte[] file, int entryBase, uint type, uint count, uint valOff, bool isLE) - { - // LONG (4) × 1 → inline; SHORT (3) × 1 → inline (low 2 bytes) - if (type == 4 && count == 1) return ReadU32(file, entryBase + 8, isLE); - if (type == 3 && count == 1) return ReadU16(file, entryBase + 8, isLE); - // Offset case (e.g. multiple strips — just return first) - if (type == 4) return ReadU32(file, (int)valOff, isLE); - if (type == 3) return ReadU16(file, (int)valOff, isLE); - return valOff; - } - - // Return inline SHORT value (first 2 bytes of value/offset field) - private static uint GetU16InlineVal(byte[] file, int entryBase, bool isLE) - => ReadU16(file, entryBase + 8, isLE); - } -} diff --git a/src/MiniPdf/Drawing/Codecs/ZlibHelper.cs b/src/MiniPdf/Drawing/Codecs/ZlibHelper.cs deleted file mode 100644 index dc5d3dff..00000000 --- a/src/MiniPdf/Drawing/Codecs/ZlibHelper.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.IO; -using System.IO.Compression; - -namespace MiniSoftware.Drawing.Codecs -{ - // ───────────────────────────────────────────────────────────────────────── - // CRC-32 (ISO 3309 / PNG use) - // ───────────────────────────────────────────────────────────────────────── - internal static class Crc32 - { - private static readonly uint[] _table = BuildTable(); - - private static uint[] BuildTable() - { - var t = new uint[256]; - for (uint n = 0; n < 256; n++) - { - uint c = n; - for (int k = 0; k < 8; k++) - c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : (c >> 1); - t[n] = c; - } - return t; - } - - public static uint Compute(byte[] buf, int offset, int length) - { - uint crc = 0xFFFFFFFF; - for (int i = offset; i < offset + length; i++) - crc = _table[(crc ^ buf[i]) & 0xFF] ^ (crc >> 8); - return ~crc; - } - } - - // ───────────────────────────────────────────────────────────────────────── - // Zlib helpers (wrap DeflateStream, add 2-byte header and Adler-32 tail) - // ───────────────────────────────────────────────────────────────────────── - internal static class ZlibHelper - { - /// - /// Decompress a zlib-framed deflate block (2-byte header + deflate + 4-byte Adler32). - /// - public static byte[] Decompress(byte[] zlibData) - { - if (zlibData == null || zlibData.Length < 6) - throw new InvalidDataException("Zlib stream too short."); - - // Skip the 2-byte zlib header; ignore the 4-byte Adler32 trailer - int deflateLength = zlibData.Length - 6; - if (deflateLength < 0) deflateLength = 0; - - using var input = new MemoryStream(zlibData, 2, deflateLength); - using var ds = new DeflateStream(input, CompressionMode.Decompress); - using var output = new MemoryStream(); - ds.CopyTo(output); - return output.ToArray(); - } - - /// - /// Compress into a zlib-framed deflate block. - /// - public static byte[] Compress(byte[] data) - { - using var output = new MemoryStream(); - - // zlib header: CMF = 0x78 (deflate, window 32 K), FLG = 0x9C (default, no dict) - // 0x789C is divisible by 31, as required by the spec. - output.WriteByte(0x78); - output.WriteByte(0x9C); - - using (var ds = new DeflateStream(output, CompressionMode.Compress, leaveOpen: true)) - ds.Write(data, 0, data.Length); - - // Adler-32 checksum of original data, big-endian - uint adler = ComputeAdler32(data, 0, data.Length); - output.WriteByte((byte)(adler >> 24)); - output.WriteByte((byte)(adler >> 16)); - output.WriteByte((byte)(adler >> 8)); - output.WriteByte((byte) adler); - - return output.ToArray(); - } - - internal static uint ComputeAdler32(byte[] data, int offset, int length) - { - const uint ModAdler = 65521; - uint a = 1, b = 0; - for (int i = offset; i < offset + length; i++) - { - a = (a + data[i]) % ModAdler; - b = (b + a) % ModAdler; - } - return (b << 16) | a; - } - } - - // ───────────────────────────────────────────────────────────────────────── - // Big-endian read helpers shared by PNG / TIFF - // ───────────────────────────────────────────────────────────────────────── - internal static class BinaryBE - { - public static uint ReadUInt32(byte[] buf, int off) - => ((uint)buf[off] << 24) | ((uint)buf[off+1] << 16) - | ((uint)buf[off+2] << 8) | buf[off+3]; - - public static ushort ReadUInt16(byte[] buf, int off) - => (ushort)(((ushort)buf[off] << 8) | buf[off+1]); - - public static void WriteUInt32(byte[] buf, int off, uint v) - { - buf[off] = (byte)(v >> 24); buf[off+1] = (byte)(v >> 16); - buf[off+2] = (byte)(v >> 8); buf[off+3] = (byte) v; - } - - public static void WriteUInt16(byte[] buf, int off, ushort v) - { buf[off] = (byte)(v >> 8); buf[off+1] = (byte)v; } - } -} diff --git a/src/MiniPdf/Drawing/Colors/Color.cs b/src/MiniPdf/Drawing/Colors/Color.cs deleted file mode 100644 index 2b324a79..00000000 --- a/src/MiniPdf/Drawing/Colors/Color.cs +++ /dev/null @@ -1,985 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Colors -{ - /// - /// Represents an ARGB color, mirroring the System.Drawing.Color API. - /// - public readonly struct Color : IEquatable - { - // _state == 0 → Empty (default-constructed) - // _state == 1 → raw ARGB value - // _state == 2 → KnownColor - private readonly uint _argb; - private readonly short _knownColor; // cast of KnownColor; 0 when _state != 2 - private readonly short _state; - - // ── Constructors ──────────────────────────────────────────────────────── - - private Color(uint argb) - { - _argb = argb; - _knownColor = 0; - _state = 1; - } - - private Color(KnownColor kc) - { - _argb = KnownColorTable.ArgbFromKnownColor(kc); - _knownColor = (short)kc; - _state = 2; - } - - // ── Well-known singleton ───────────────────────────────────────────────── - - /// - /// Gets a structure that has ARGB values of (0, 0, 0, 0). - /// - public static readonly Color Empty = default; - - // ── Channel properties ─────────────────────────────────────────────────── - - /// - /// Gets the alpha channel component of this structure. - /// - public byte A => (byte)((_argb >> 24) & 0xFF); - - /// - /// Gets the red channel component of this structure. - /// - public byte R => (byte)((_argb >> 16) & 0xFF); - - /// - /// Gets the green channel component of this structure. - /// - public byte G => (byte)((_argb >> 8) & 0xFF); - - /// - /// Gets the blue channel component of this structure. - /// - public byte B => (byte)( _argb & 0xFF); - - // ── State properties ───────────────────────────────────────────────────── - - /// - /// Gets a value indicating whether this is empty. - /// - public bool IsEmpty => _state == 0; - - /// - /// Gets a value indicating whether this is a known color. - /// - public bool IsKnownColor => _state == 2; - - /// - /// Gets a value indicating whether this is a named color. - /// - public bool IsNamedColor => _state == 2; - - /// - /// Gets a value indicating whether this is a system color. - /// - public bool IsSystemColor => _state == 2 && KnownColorTable.IsSystemColor((KnownColor)_knownColor); - - /// - /// Gets the name of this . - /// - public string Name - { - get - { - if (_state == 2) return ((KnownColor)_knownColor).ToString(); - if (_state == 0) return "0"; - return _argb.ToString("x8"); - } - } - - // ── Factory methods ────────────────────────────────────────────────────── - - /// - /// Creates a from a 32-bit ARGB value. - /// - /// A 32-bit ARGB value. - /// A structure. - public static Color FromArgb(int argb) - => new Color((uint)argb); - - /// - /// Creates a from the specified ARGB component values. - /// - /// The alpha channel value (0-255). - /// The red channel value (0-255). - /// The green channel value (0-255). - /// The blue channel value (0-255). - /// A structure. - /// Thrown when any component is outside 0-255. - public static Color FromArgb(int alpha, int red, int green, int blue) - { - if ((uint)alpha > 255) throw new ArgumentOutOfRangeException(nameof(alpha), "Value must be 0-255."); - if ((uint)red > 255) throw new ArgumentOutOfRangeException(nameof(red), "Value must be 0-255."); - if ((uint)green > 255) throw new ArgumentOutOfRangeException(nameof(green), "Value must be 0-255."); - if ((uint)blue > 255) throw new ArgumentOutOfRangeException(nameof(blue), "Value must be 0-255."); - return new Color(((uint)alpha << 24) | ((uint)red << 16) | ((uint)green << 8) | (uint)blue); - } - - /// - /// Creates a from the specified alpha and base color. - /// - /// The alpha channel value (0-255). - /// The base color to use for RGB components. - /// A structure. - public static Color FromArgb(int alpha, Color baseColor) - => FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B); - - /// - /// Creates a from the specified RGB component values with full opacity. - /// - /// The red channel value (0-255). - /// The green channel value (0-255). - /// The blue channel value (0-255). - /// A structure. - public static Color FromArgb(int red, int green, int blue) - => FromArgb(255, red, green, blue); - - /// - /// Creates a from the specified known color. - /// - /// The known color to create. - /// A structure. - public static Color FromKnownColor(KnownColor color) - => new Color(color); - - /// - /// Creates a from the specified color name. - /// - /// The name of the color. - /// A structure. - public static Color FromName(string name) - { - if (Enum.TryParse(name, ignoreCase: true, out KnownColor kc)) - return FromKnownColor(kc); - // Unknown name: return an ARGB-zero color (not Empty, but unnamed) - return new Color(0u); - } - - // ── Conversion ────────────────────────────────────────────────────────── - - /// - /// Gets the 32-bit ARGB value of this . - /// - /// A 32-bit ARGB value. - public int ToArgb() => (int)_argb; - - /// - /// Gets the value of this . - /// - /// The known color value. - public KnownColor ToKnownColor() => (KnownColor)_knownColor; - - // ── HSB ───────────────────────────────────────────────────────────────── - - /// - /// Gets the hue component of this , in degrees (0-360). - /// - /// The hue value in degrees. - public float GetHue() - { - if (R == G && G == B) return 0f; - float r = R / 255f, g = G / 255f, b = B / 255f; - float max = Math.Max(r, Math.Max(g, b)); - float min = Math.Min(r, Math.Min(g, b)); - float delta = max - min; - float hue; - if (max == r) hue = ((g - b) / delta) % 6f * 60f; - else if (max == g) hue = ((b - r) / delta + 2f) * 60f; - else hue = ((r - g) / delta + 4f) * 60f; - return hue < 0f ? hue + 360f : hue; - } - - /// - /// Gets the saturation component of this (0.0-1.0). - /// - /// The saturation value. - public float GetSaturation() - { - float r = R / 255f, g = G / 255f, b = B / 255f; - float max = Math.Max(r, Math.Max(g, b)); - float min = Math.Min(r, Math.Min(g, b)); - if (max == min) return 0f; - float l = (max + min) / 2f; - float delta = max - min; - return l <= 0.5f ? delta / (max + min) : delta / (2f - max - min); - } - - /// - /// Gets the brightness (lightness) component of this (0.0-1.0). - /// - /// The brightness value. - public float GetBrightness() - { - float r = R / 255f, g = G / 255f, b = B / 255f; - return (Math.Max(r, Math.Max(g, b)) + Math.Min(r, Math.Min(g, b))) / 2f; - } - - // ── Equality ───────────────────────────────────────────────────────────── - - /// - /// Indicates whether this is equal to another . - /// - /// The color to compare with. - /// True if the colors are equal; otherwise, false. - public bool Equals(Color other) - => _argb == other._argb && _knownColor == other._knownColor && _state == other._state; - - /// - /// Indicates whether this is equal to the specified object. - /// - /// The object to compare with. - /// True if the colors are equal; otherwise, false. - public override bool Equals(object? obj) => obj is Color c && Equals(c); - - /// - /// Gets the hash code for this . - /// - /// The hash code. - public override int GetHashCode() - { - unchecked - { - int h = (int)_argb; - h = h * 397 ^ _knownColor; - h = h * 397 ^ _state; - return h; - } - } - - /// - /// Determines whether two structures are equal. - /// - /// The first color. - /// The second color. - /// True if the colors are equal; otherwise, false. - public static bool operator ==(Color left, Color right) => left.Equals(right); - - /// - /// Determines whether two structures are not equal. - /// - /// The first color. - /// The second color. - /// True if the colors are not equal; otherwise, false. - public static bool operator !=(Color left, Color right) => !left.Equals(right); - - /// - /// Converts this to its string representation. - /// - /// A string representation of the color. - public override string ToString() => $"Color [A={A}, R={R}, G={G}, B={B}]"; - - // ── Named color static properties ──────────────────────────────────────── - - /// - /// Gets a representing transparent (ARGB = 0x00FFFFFF). - /// - public static Color Transparent => FromKnownColor(KnownColor.Transparent); - - /// - /// Gets a representing AliceBlue. - /// - public static Color AliceBlue => FromKnownColor(KnownColor.AliceBlue); - - /// - /// Gets a representing AntiqueWhite. - /// - public static Color AntiqueWhite => FromKnownColor(KnownColor.AntiqueWhite); - - /// - /// Gets a representing Aqua. - /// - public static Color Aqua => FromKnownColor(KnownColor.Aqua); - - /// - /// Gets a representing Aquamarine. - /// - public static Color Aquamarine => FromKnownColor(KnownColor.Aquamarine); - - /// - /// Gets a representing Azure. - /// - public static Color Azure => FromKnownColor(KnownColor.Azure); - - /// - /// Gets a representing Beige. - /// - public static Color Beige => FromKnownColor(KnownColor.Beige); - - /// - /// Gets a representing Bisque. - /// - public static Color Bisque => FromKnownColor(KnownColor.Bisque); - - /// - /// Gets a representing Black. - /// - public static Color Black => FromKnownColor(KnownColor.Black); - - /// - /// Gets a representing BlanchedAlmond. - /// - public static Color BlanchedAlmond => FromKnownColor(KnownColor.BlanchedAlmond); - - /// - /// Gets a representing Blue. - /// - public static Color Blue => FromKnownColor(KnownColor.Blue); - - /// - /// Gets a representing BlueViolet. - /// - public static Color BlueViolet => FromKnownColor(KnownColor.BlueViolet); - - /// - /// Gets a representing Brown. - /// - public static Color Brown => FromKnownColor(KnownColor.Brown); - - /// - /// Gets a representing BurlyWood. - /// - public static Color BurlyWood => FromKnownColor(KnownColor.BurlyWood); - - /// - /// Gets a representing CadetBlue. - /// - public static Color CadetBlue => FromKnownColor(KnownColor.CadetBlue); - - /// - /// Gets a representing Chartreuse. - /// - public static Color Chartreuse => FromKnownColor(KnownColor.Chartreuse); - - /// - /// Gets a representing Chocolate. - /// - public static Color Chocolate => FromKnownColor(KnownColor.Chocolate); - - /// - /// Gets a representing Coral. - /// - public static Color Coral => FromKnownColor(KnownColor.Coral); - - /// - /// Gets a representing CornflowerBlue. - /// - public static Color CornflowerBlue => FromKnownColor(KnownColor.CornflowerBlue); - - /// - /// Gets a representing Cornsilk. - /// - public static Color Cornsilk => FromKnownColor(KnownColor.Cornsilk); - - /// - /// Gets a representing Crimson. - /// - public static Color Crimson => FromKnownColor(KnownColor.Crimson); - - /// - /// Gets a representing Cyan. - /// - public static Color Cyan => FromKnownColor(KnownColor.Cyan); - - /// - /// Gets a representing DarkBlue. - /// - public static Color DarkBlue => FromKnownColor(KnownColor.DarkBlue); - - /// - /// Gets a representing DarkCyan. - /// - public static Color DarkCyan => FromKnownColor(KnownColor.DarkCyan); - - /// - /// Gets a representing DarkGoldenrod. - /// - public static Color DarkGoldenrod => FromKnownColor(KnownColor.DarkGoldenrod); - - /// - /// Gets a representing DarkGray. - /// - public static Color DarkGray => FromKnownColor(KnownColor.DarkGray); - - /// - /// Gets a representing DarkGreen. - /// - public static Color DarkGreen => FromKnownColor(KnownColor.DarkGreen); - - /// - /// Gets a representing DarkKhaki. - /// - public static Color DarkKhaki => FromKnownColor(KnownColor.DarkKhaki); - - /// - /// Gets a representing DarkMagenta. - /// - public static Color DarkMagenta => FromKnownColor(KnownColor.DarkMagenta); - - /// - /// Gets a representing DarkOliveGreen. - /// - public static Color DarkOliveGreen => FromKnownColor(KnownColor.DarkOliveGreen); - - /// - /// Gets a representing DarkOrange. - /// - public static Color DarkOrange => FromKnownColor(KnownColor.DarkOrange); - - /// - /// Gets a representing DarkOrchid. - /// - public static Color DarkOrchid => FromKnownColor(KnownColor.DarkOrchid); - - /// - /// Gets a representing DarkRed. - /// - public static Color DarkRed => FromKnownColor(KnownColor.DarkRed); - - /// - /// Gets a representing DarkSalmon. - /// - public static Color DarkSalmon => FromKnownColor(KnownColor.DarkSalmon); - - /// - /// Gets a representing DarkSeaGreen. - /// - public static Color DarkSeaGreen => FromKnownColor(KnownColor.DarkSeaGreen); - - /// - /// Gets a representing DarkSlateBlue. - /// - public static Color DarkSlateBlue => FromKnownColor(KnownColor.DarkSlateBlue); - - /// - /// Gets a representing DarkSlateGray. - /// - public static Color DarkSlateGray => FromKnownColor(KnownColor.DarkSlateGray); - - /// - /// Gets a representing DarkTurquoise. - /// - public static Color DarkTurquoise => FromKnownColor(KnownColor.DarkTurquoise); - - /// - /// Gets a representing DarkViolet. - /// - public static Color DarkViolet => FromKnownColor(KnownColor.DarkViolet); - - /// - /// Gets a representing DeepPink. - /// - public static Color DeepPink => FromKnownColor(KnownColor.DeepPink); - - /// - /// Gets a representing DeepSkyBlue. - /// - public static Color DeepSkyBlue => FromKnownColor(KnownColor.DeepSkyBlue); - - /// - /// Gets a representing DimGray. - /// - public static Color DimGray => FromKnownColor(KnownColor.DimGray); - - /// - /// Gets a representing DodgerBlue. - /// - public static Color DodgerBlue => FromKnownColor(KnownColor.DodgerBlue); - - /// - /// Gets a representing Firebrick. - /// - public static Color Firebrick => FromKnownColor(KnownColor.Firebrick); - - /// - /// Gets a representing FloralWhite. - /// - public static Color FloralWhite => FromKnownColor(KnownColor.FloralWhite); - - /// - /// Gets a representing ForestGreen. - /// - public static Color ForestGreen => FromKnownColor(KnownColor.ForestGreen); - - /// - /// Gets a representing Fuchsia. - /// - public static Color Fuchsia => FromKnownColor(KnownColor.Fuchsia); - - /// - /// Gets a representing Gainsboro. - /// - public static Color Gainsboro => FromKnownColor(KnownColor.Gainsboro); - - /// - /// Gets a representing GhostWhite. - /// - public static Color GhostWhite => FromKnownColor(KnownColor.GhostWhite); - - /// - /// Gets a representing Gold. - /// - public static Color Gold => FromKnownColor(KnownColor.Gold); - - /// - /// Gets a representing Goldenrod. - /// - public static Color Goldenrod => FromKnownColor(KnownColor.Goldenrod); - - /// - /// Gets a representing Gray. - /// - public static Color Gray => FromKnownColor(KnownColor.Gray); - - /// - /// Gets a representing Green. - /// - public static Color Green => FromKnownColor(KnownColor.Green); - - /// - /// Gets a representing GreenYellow. - /// - public static Color GreenYellow => FromKnownColor(KnownColor.GreenYellow); - - /// - /// Gets a representing Honeydew. - /// - public static Color Honeydew => FromKnownColor(KnownColor.Honeydew); - - /// - /// Gets a representing HotPink. - /// - public static Color HotPink => FromKnownColor(KnownColor.HotPink); - - /// - /// Gets a representing IndianRed. - /// - public static Color IndianRed => FromKnownColor(KnownColor.IndianRed); - - /// - /// Gets a representing Indigo. - /// - public static Color Indigo => FromKnownColor(KnownColor.Indigo); - - /// - /// Gets a representing Ivory. - /// - public static Color Ivory => FromKnownColor(KnownColor.Ivory); - - /// - /// Gets a representing Khaki. - /// - public static Color Khaki => FromKnownColor(KnownColor.Khaki); - - /// - /// Gets a representing Lavender. - /// - public static Color Lavender => FromKnownColor(KnownColor.Lavender); - - /// - /// Gets a representing LavenderBlush. - /// - public static Color LavenderBlush => FromKnownColor(KnownColor.LavenderBlush); - - /// - /// Gets a representing LawnGreen. - /// - public static Color LawnGreen => FromKnownColor(KnownColor.LawnGreen); - - /// - /// Gets a representing LemonChiffon. - /// - public static Color LemonChiffon => FromKnownColor(KnownColor.LemonChiffon); - - /// - /// Gets a representing LightBlue. - /// - public static Color LightBlue => FromKnownColor(KnownColor.LightBlue); - - /// - /// Gets a representing LightCoral. - /// - public static Color LightCoral => FromKnownColor(KnownColor.LightCoral); - - /// - /// Gets a representing LightCyan. - /// - public static Color LightCyan => FromKnownColor(KnownColor.LightCyan); - - /// - /// Gets a representing LightGoldenrodYellow. - /// - public static Color LightGoldenrodYellow => FromKnownColor(KnownColor.LightGoldenrodYellow); - - /// - /// Gets a representing LightGray. - /// - public static Color LightGray => FromKnownColor(KnownColor.LightGray); - - /// - /// Gets a representing LightGreen. - /// - public static Color LightGreen => FromKnownColor(KnownColor.LightGreen); - - /// - /// Gets a representing LightPink. - /// - public static Color LightPink => FromKnownColor(KnownColor.LightPink); - - /// - /// Gets a representing LightSalmon. - /// - public static Color LightSalmon => FromKnownColor(KnownColor.LightSalmon); - - /// - /// Gets a representing LightSeaGreen. - /// - public static Color LightSeaGreen => FromKnownColor(KnownColor.LightSeaGreen); - - /// - /// Gets a representing LightSkyBlue. - /// - public static Color LightSkyBlue => FromKnownColor(KnownColor.LightSkyBlue); - - /// - /// Gets a representing LightSlateGray. - /// - public static Color LightSlateGray => FromKnownColor(KnownColor.LightSlateGray); - - /// - /// Gets a representing LightSteelBlue. - /// - public static Color LightSteelBlue => FromKnownColor(KnownColor.LightSteelBlue); - - /// - /// Gets a representing LightYellow. - /// - public static Color LightYellow => FromKnownColor(KnownColor.LightYellow); - - /// - /// Gets a representing Lime. - /// - public static Color Lime => FromKnownColor(KnownColor.Lime); - - /// - /// Gets a representing LimeGreen. - /// - public static Color LimeGreen => FromKnownColor(KnownColor.LimeGreen); - - /// - /// Gets a representing Linen. - /// - public static Color Linen => FromKnownColor(KnownColor.Linen); - - /// - /// Gets a representing Magenta. - /// - public static Color Magenta => FromKnownColor(KnownColor.Magenta); - - /// - /// Gets a representing Maroon. - /// - public static Color Maroon => FromKnownColor(KnownColor.Maroon); - - /// - /// Gets a representing MediumAquamarine. - /// - public static Color MediumAquamarine => FromKnownColor(KnownColor.MediumAquamarine); - - /// - /// Gets a representing MediumBlue. - /// - public static Color MediumBlue => FromKnownColor(KnownColor.MediumBlue); - - /// - /// Gets a representing MediumOrchid. - /// - public static Color MediumOrchid => FromKnownColor(KnownColor.MediumOrchid); - - /// - /// Gets a representing MediumPurple. - /// - public static Color MediumPurple => FromKnownColor(KnownColor.MediumPurple); - - /// - /// Gets a representing MediumSeaGreen. - /// - public static Color MediumSeaGreen => FromKnownColor(KnownColor.MediumSeaGreen); - - /// - /// Gets a representing MediumSlateBlue. - /// - public static Color MediumSlateBlue => FromKnownColor(KnownColor.MediumSlateBlue); - - /// - /// Gets a representing MediumSpringGreen. - /// - public static Color MediumSpringGreen => FromKnownColor(KnownColor.MediumSpringGreen); - - /// - /// Gets a representing MediumTurquoise. - /// - public static Color MediumTurquoise => FromKnownColor(KnownColor.MediumTurquoise); - - /// - /// Gets a representing MediumVioletRed. - /// - public static Color MediumVioletRed => FromKnownColor(KnownColor.MediumVioletRed); - - /// - /// Gets a representing MidnightBlue. - /// - public static Color MidnightBlue => FromKnownColor(KnownColor.MidnightBlue); - - /// - /// Gets a representing MintCream. - /// - public static Color MintCream => FromKnownColor(KnownColor.MintCream); - - /// - /// Gets a representing MistyRose. - /// - public static Color MistyRose => FromKnownColor(KnownColor.MistyRose); - - /// - /// Gets a representing Moccasin. - /// - public static Color Moccasin => FromKnownColor(KnownColor.Moccasin); - - /// - /// Gets a representing NavajoWhite. - /// - public static Color NavajoWhite => FromKnownColor(KnownColor.NavajoWhite); - - /// - /// Gets a representing Navy. - /// - public static Color Navy => FromKnownColor(KnownColor.Navy); - - /// - /// Gets a representing OldLace. - /// - public static Color OldLace => FromKnownColor(KnownColor.OldLace); - - /// - /// Gets a representing Olive. - /// - public static Color Olive => FromKnownColor(KnownColor.Olive); - - /// - /// Gets a representing OliveDrab. - /// - public static Color OliveDrab => FromKnownColor(KnownColor.OliveDrab); - - /// - /// Gets a representing Orange. - /// - public static Color Orange => FromKnownColor(KnownColor.Orange); - - /// - /// Gets a representing OrangeRed. - /// - public static Color OrangeRed => FromKnownColor(KnownColor.OrangeRed); - - /// - /// Gets a representing Orchid. - /// - public static Color Orchid => FromKnownColor(KnownColor.Orchid); - - /// - /// Gets a representing PaleGoldenrod. - /// - public static Color PaleGoldenrod => FromKnownColor(KnownColor.PaleGoldenrod); - - /// - /// Gets a representing PaleGreen. - /// - public static Color PaleGreen => FromKnownColor(KnownColor.PaleGreen); - - /// - /// Gets a representing PaleTurquoise. - /// - public static Color PaleTurquoise => FromKnownColor(KnownColor.PaleTurquoise); - - /// - /// Gets a representing PaleVioletRed. - /// - public static Color PaleVioletRed => FromKnownColor(KnownColor.PaleVioletRed); - - /// - /// Gets a representing PapayaWhip. - /// - public static Color PapayaWhip => FromKnownColor(KnownColor.PapayaWhip); - - /// - /// Gets a representing PeachPuff. - /// - public static Color PeachPuff => FromKnownColor(KnownColor.PeachPuff); - - /// - /// Gets a representing Peru. - /// - public static Color Peru => FromKnownColor(KnownColor.Peru); - - /// - /// Gets a representing Pink. - /// - public static Color Pink => FromKnownColor(KnownColor.Pink); - - /// - /// Gets a representing Plum. - /// - public static Color Plum => FromKnownColor(KnownColor.Plum); - - /// - /// Gets a representing PowderBlue. - /// - public static Color PowderBlue => FromKnownColor(KnownColor.PowderBlue); - - /// - /// Gets a representing Purple. - /// - public static Color Purple => FromKnownColor(KnownColor.Purple); - - /// - /// Gets a representing Red. - /// - public static Color Red => FromKnownColor(KnownColor.Red); - - /// - /// Gets a representing RosyBrown. - /// - public static Color RosyBrown => FromKnownColor(KnownColor.RosyBrown); - - /// - /// Gets a representing RoyalBlue. - /// - public static Color RoyalBlue => FromKnownColor(KnownColor.RoyalBlue); - - /// - /// Gets a representing SaddleBrown. - /// - public static Color SaddleBrown => FromKnownColor(KnownColor.SaddleBrown); - - /// - /// Gets a representing Salmon. - /// - public static Color Salmon => FromKnownColor(KnownColor.Salmon); - - /// - /// Gets a representing SandyBrown. - /// - public static Color SandyBrown => FromKnownColor(KnownColor.SandyBrown); - - /// - /// Gets a representing SeaGreen. - /// - public static Color SeaGreen => FromKnownColor(KnownColor.SeaGreen); - - /// - /// Gets a representing SeaShell. - /// - public static Color SeaShell => FromKnownColor(KnownColor.SeaShell); - - /// - /// Gets a representing Sienna. - /// - public static Color Sienna => FromKnownColor(KnownColor.Sienna); - - /// - /// Gets a representing Silver. - /// - public static Color Silver => FromKnownColor(KnownColor.Silver); - - /// - /// Gets a representing SkyBlue. - /// - public static Color SkyBlue => FromKnownColor(KnownColor.SkyBlue); - - /// - /// Gets a representing SlateBlue. - /// - public static Color SlateBlue => FromKnownColor(KnownColor.SlateBlue); - - /// - /// Gets a representing SlateGray. - /// - public static Color SlateGray => FromKnownColor(KnownColor.SlateGray); - - /// - /// Gets a representing Snow. - /// - public static Color Snow => FromKnownColor(KnownColor.Snow); - - /// - /// Gets a representing SpringGreen. - /// - public static Color SpringGreen => FromKnownColor(KnownColor.SpringGreen); - - /// - /// Gets a representing SteelBlue. - /// - public static Color SteelBlue => FromKnownColor(KnownColor.SteelBlue); - - /// - /// Gets a representing Tan. - /// - public static Color Tan => FromKnownColor(KnownColor.Tan); - - /// - /// Gets a representing Teal. - /// - public static Color Teal => FromKnownColor(KnownColor.Teal); - - /// - /// Gets a representing Thistle. - /// - public static Color Thistle => FromKnownColor(KnownColor.Thistle); - - /// - /// Gets a representing Tomato. - /// - public static Color Tomato => FromKnownColor(KnownColor.Tomato); - - /// - /// Gets a representing Turquoise. - /// - public static Color Turquoise => FromKnownColor(KnownColor.Turquoise); - - /// - /// Gets a representing Violet. - /// - public static Color Violet => FromKnownColor(KnownColor.Violet); - - /// - /// Gets a representing Wheat. - /// - public static Color Wheat => FromKnownColor(KnownColor.Wheat); - - /// - /// Gets a representing White. - /// - public static Color White => FromKnownColor(KnownColor.White); - - /// - /// Gets a representing WhiteSmoke. - /// - public static Color WhiteSmoke => FromKnownColor(KnownColor.WhiteSmoke); - - /// - /// Gets a representing Yellow. - /// - public static Color Yellow => FromKnownColor(KnownColor.Yellow); - - /// - /// Gets a representing YellowGreen. - /// - public static Color YellowGreen => FromKnownColor(KnownColor.YellowGreen); - } -} diff --git a/src/MiniPdf/Drawing/Colors/KnownColor.cs b/src/MiniPdf/Drawing/Colors/KnownColor.cs deleted file mode 100644 index c2866a4e..00000000 --- a/src/MiniPdf/Drawing/Colors/KnownColor.cs +++ /dev/null @@ -1,190 +0,0 @@ -#pragma warning disable CS1591 -namespace MiniSoftware.Drawing.Colors -{ - /// - /// Specifies known system and web colors, matching GDI+ KnownColor values exactly. - /// Values 1-26 are system colors; 27-167 are web/named colors; 168-174 are additional system colors. - /// - public enum KnownColor - { - // System colors (1-26) - ActiveBorder = 1, - ActiveCaption = 2, - ActiveCaptionText = 3, - AppWorkspace = 4, - Control = 5, - ControlDark = 6, - ControlDarkDark = 7, - ControlLight = 8, - ControlLightLight = 9, - ControlText = 10, - Desktop = 11, - GrayText = 12, - Highlight = 13, - HighlightText = 14, - HotTrack = 15, - InactiveBorder = 16, - InactiveCaption = 17, - InactiveCaptionText = 18, - Info = 19, - InfoText = 20, - Menu = 21, - MenuText = 22, - ScrollBar = 23, - Window = 24, - WindowFrame = 25, - WindowText = 26, - - // Web / named colors (27-167) - Transparent = 27, - AliceBlue = 28, - AntiqueWhite = 29, - Aqua = 30, - Aquamarine = 31, - Azure = 32, - Beige = 33, - Bisque = 34, - Black = 35, - BlanchedAlmond = 36, - Blue = 37, - BlueViolet = 38, - Brown = 39, - BurlyWood = 40, - CadetBlue = 41, - Chartreuse = 42, - Chocolate = 43, - Coral = 44, - CornflowerBlue = 45, - Cornsilk = 46, - Crimson = 47, - Cyan = 48, - DarkBlue = 49, - DarkCyan = 50, - DarkGoldenrod = 51, - DarkGray = 52, - DarkGreen = 53, - DarkKhaki = 54, - DarkMagenta = 55, - DarkOliveGreen = 56, - DarkOrange = 57, - DarkOrchid = 58, - DarkRed = 59, - DarkSalmon = 60, - DarkSeaGreen = 61, - DarkSlateBlue = 62, - DarkSlateGray = 63, - DarkTurquoise = 64, - DarkViolet = 65, - DeepPink = 66, - DeepSkyBlue = 67, - DimGray = 68, - DodgerBlue = 69, - Firebrick = 70, - FloralWhite = 71, - ForestGreen = 72, - Fuchsia = 73, - Gainsboro = 74, - GhostWhite = 75, - Gold = 76, - Goldenrod = 77, - Gray = 78, - Green = 79, - GreenYellow = 80, - Honeydew = 81, - HotPink = 82, - IndianRed = 83, - Indigo = 84, - Ivory = 85, - Khaki = 86, - Lavender = 87, - LavenderBlush = 88, - LawnGreen = 89, - LemonChiffon = 90, - LightBlue = 91, - LightCoral = 92, - LightCyan = 93, - LightGoldenrodYellow = 94, - LightGray = 95, - LightGreen = 96, - LightPink = 97, - LightSalmon = 98, - LightSeaGreen = 99, - LightSkyBlue = 100, - LightSlateGray = 101, - LightSteelBlue = 102, - LightYellow = 103, - Lime = 104, - LimeGreen = 105, - Linen = 106, - Magenta = 107, - Maroon = 108, - MediumAquamarine = 109, - MediumBlue = 110, - MediumOrchid = 111, - MediumPurple = 112, - MediumSeaGreen = 113, - MediumSlateBlue = 114, - MediumSpringGreen = 115, - MediumTurquoise = 116, - MediumVioletRed = 117, - MidnightBlue = 118, - MintCream = 119, - MistyRose = 120, - Moccasin = 121, - NavajoWhite = 122, - Navy = 123, - OldLace = 124, - Olive = 125, - OliveDrab = 126, - Orange = 127, - OrangeRed = 128, - Orchid = 129, - PaleGoldenrod = 130, - PaleGreen = 131, - PaleTurquoise = 132, - PaleVioletRed = 133, - PapayaWhip = 134, - PeachPuff = 135, - Peru = 136, - Pink = 137, - Plum = 138, - PowderBlue = 139, - Purple = 140, - Red = 141, - RosyBrown = 142, - RoyalBlue = 143, - SaddleBrown = 144, - Salmon = 145, - SandyBrown = 146, - SeaGreen = 147, - SeaShell = 148, - Sienna = 149, - Silver = 150, - SkyBlue = 151, - SlateBlue = 152, - SlateGray = 153, - Snow = 154, - SpringGreen = 155, - SteelBlue = 156, - Tan = 157, - Teal = 158, - Thistle = 159, - Tomato = 160, - Turquoise = 161, - Violet = 162, - Wheat = 163, - White = 164, - WhiteSmoke = 165, - Yellow = 166, - YellowGreen = 167, - - // Additional system colors (168-174) - ButtonFace = 168, - ButtonHighlight = 169, - ButtonShadow = 170, - GradientActiveCaption = 171, - GradientInactiveCaption = 172, - MenuBar = 173, - MenuHighlight = 174, - } -} diff --git a/src/MiniPdf/Drawing/Colors/KnownColorTable.cs b/src/MiniPdf/Drawing/Colors/KnownColorTable.cs deleted file mode 100644 index b6000119..00000000 --- a/src/MiniPdf/Drawing/Colors/KnownColorTable.cs +++ /dev/null @@ -1,204 +0,0 @@ -namespace MiniSoftware.Drawing.Colors -{ - /// - /// Provides ARGB values for all entries. - /// System color entries (1-26, 168-174) use reasonable static defaults; - /// web/named color entries (27-167) use the standard HTML/CSS ARGB values. - /// - internal static class KnownColorTable - { - // Index 0 is unused; valid range is 1-174. - private static readonly uint[] s_colorTable = new uint[175] - { - /* 0 unused */ 0x00000000, - /* 1 ActiveBorder */ 0xFFD4D0C8, - /* 2 ActiveCaption */ 0xFF0054E3, - /* 3 ActiveCaptionText */ 0xFFFFFFFF, - /* 4 AppWorkspace */ 0xFF808080, - /* 5 Control */ 0xFFECE9D8, - /* 6 ControlDark */ 0xFFACA899, - /* 7 ControlDarkDark */ 0xFF716F64, - /* 8 ControlLight */ 0xFFF7F6F3, - /* 9 ControlLightLight */ 0xFFFFFFFF, - /* 10 ControlText */ 0xFF000000, - /* 11 Desktop */ 0xFF004E98, - /* 12 GrayText */ 0xFF808080, - /* 13 Highlight */ 0xFF316AC5, - /* 14 HighlightText */ 0xFFFFFFFF, - /* 15 HotTrack */ 0xFF0066CC, - /* 16 InactiveBorder */ 0xFFD4D0C8, - /* 17 InactiveCaption */ 0xFF7A96DF, - /* 18 InactiveCaptionTx */ 0xFFD8E4F8, - /* 19 Info */ 0xFFFFFFE1, - /* 20 InfoText */ 0xFF000000, - /* 21 Menu */ 0xFFF0F0F0, - /* 22 MenuText */ 0xFF000000, - /* 23 ScrollBar */ 0xFFD4D0C8, - /* 24 Window */ 0xFFFFFFFF, - /* 25 WindowFrame */ 0xFF000000, - /* 26 WindowText */ 0xFF000000, - /* 27 Transparent */ 0x00FFFFFF, - /* 28 AliceBlue */ 0xFFF0F8FF, - /* 29 AntiqueWhite */ 0xFFFAEBD7, - /* 30 Aqua */ 0xFF00FFFF, - /* 31 Aquamarine */ 0xFF7FFFD4, - /* 32 Azure */ 0xFFF0FFFF, - /* 33 Beige */ 0xFFF5F5DC, - /* 34 Bisque */ 0xFFFFE4C4, - /* 35 Black */ 0xFF000000, - /* 36 BlanchedAlmond */ 0xFFFFEBCD, - /* 37 Blue */ 0xFF0000FF, - /* 38 BlueViolet */ 0xFF8A2BE2, - /* 39 Brown */ 0xFFA52A2A, - /* 40 BurlyWood */ 0xFFDEB887, - /* 41 CadetBlue */ 0xFF5F9EA0, - /* 42 Chartreuse */ 0xFF7FFF00, - /* 43 Chocolate */ 0xFFD2691E, - /* 44 Coral */ 0xFFFF7F50, - /* 45 CornflowerBlue */ 0xFF6495ED, - /* 46 Cornsilk */ 0xFFFFF8DC, - /* 47 Crimson */ 0xFFDC143C, - /* 48 Cyan */ 0xFF00FFFF, - /* 49 DarkBlue */ 0xFF00008B, - /* 50 DarkCyan */ 0xFF008B8B, - /* 51 DarkGoldenrod */ 0xFFB8860B, - /* 52 DarkGray */ 0xFFA9A9A9, - /* 53 DarkGreen */ 0xFF006400, - /* 54 DarkKhaki */ 0xFFBDB76B, - /* 55 DarkMagenta */ 0xFF8B008B, - /* 56 DarkOliveGreen */ 0xFF556B2F, - /* 57 DarkOrange */ 0xFFFF8C00, - /* 58 DarkOrchid */ 0xFF9932CC, - /* 59 DarkRed */ 0xFF8B0000, - /* 60 DarkSalmon */ 0xFFE9967A, - /* 61 DarkSeaGreen */ 0xFF8FBC8F, - /* 62 DarkSlateBlue */ 0xFF483D8B, - /* 63 DarkSlateGray */ 0xFF2F4F4F, - /* 64 DarkTurquoise */ 0xFF00CED1, - /* 65 DarkViolet */ 0xFF9400D3, - /* 66 DeepPink */ 0xFFFF1493, - /* 67 DeepSkyBlue */ 0xFF00BFFF, - /* 68 DimGray */ 0xFF696969, - /* 69 DodgerBlue */ 0xFF1E90FF, - /* 70 Firebrick */ 0xFFB22222, - /* 71 FloralWhite */ 0xFFFFFAF0, - /* 72 ForestGreen */ 0xFF228B22, - /* 73 Fuchsia */ 0xFFFF00FF, - /* 74 Gainsboro */ 0xFFDCDCDC, - /* 75 GhostWhite */ 0xFFF8F8FF, - /* 76 Gold */ 0xFFFFD700, - /* 77 Goldenrod */ 0xFFDAA520, - /* 78 Gray */ 0xFF808080, - /* 79 Green */ 0xFF008000, - /* 80 GreenYellow */ 0xFFADFF2F, - /* 81 Honeydew */ 0xFFF0FFF0, - /* 82 HotPink */ 0xFFFF69B4, - /* 83 IndianRed */ 0xFFCD5C5C, - /* 84 Indigo */ 0xFF4B0082, - /* 85 Ivory */ 0xFFFFFFF0, - /* 86 Khaki */ 0xFFF0E68C, - /* 87 Lavender */ 0xFFE6E6FA, - /* 88 LavenderBlush */ 0xFFFFF0F5, - /* 89 LawnGreen */ 0xFF7CFC00, - /* 90 LemonChiffon */ 0xFFFFFACD, - /* 91 LightBlue */ 0xFFADD8E6, - /* 92 LightCoral */ 0xFFF08080, - /* 93 LightCyan */ 0xFFE0FFFF, - /* 94 LightGoldenrodYlw */ 0xFFFAFAD2, - /* 95 LightGray */ 0xFFD3D3D3, - /* 96 LightGreen */ 0xFF90EE90, - /* 97 LightPink */ 0xFFFFB6C1, - /* 98 LightSalmon */ 0xFFFFA07A, - /* 99 LightSeaGreen */ 0xFF20B2AA, - /* 100 LightSkyBlue */ 0xFF87CEFA, - /* 101 LightSlateGray */ 0xFF778899, - /* 102 LightSteelBlue */ 0xFFB0C4DE, - /* 103 LightYellow */ 0xFFFFFFE0, - /* 104 Lime */ 0xFF00FF00, - /* 105 LimeGreen */ 0xFF32CD32, - /* 106 Linen */ 0xFFFAF0E6, - /* 107 Magenta */ 0xFFFF00FF, - /* 108 Maroon */ 0xFF800000, - /* 109 MediumAquamarine */ 0xFF66CDAA, - /* 110 MediumBlue */ 0xFF0000CD, - /* 111 MediumOrchid */ 0xFFBA55D3, - /* 112 MediumPurple */ 0xFF9370DB, - /* 113 MediumSeaGreen */ 0xFF3CB371, - /* 114 MediumSlateBlue */ 0xFF7B68EE, - /* 115 MediumSpringGrn */ 0xFF00FA9A, - /* 116 MediumTurquoise */ 0xFF48D1CC, - /* 117 MediumVioletRed */ 0xFFC71585, - /* 118 MidnightBlue */ 0xFF191970, - /* 119 MintCream */ 0xFFF5FFFA, - /* 120 MistyRose */ 0xFFFFE4E1, - /* 121 Moccasin */ 0xFFFFE4B5, - /* 122 NavajoWhite */ 0xFFFFDEAD, - /* 123 Navy */ 0xFF000080, - /* 124 OldLace */ 0xFFFDF5E6, - /* 125 Olive */ 0xFF808000, - /* 126 OliveDrab */ 0xFF6B8E23, - /* 127 Orange */ 0xFFFFA500, - /* 128 OrangeRed */ 0xFFFF4500, - /* 129 Orchid */ 0xFFDA70D6, - /* 130 PaleGoldenrod */ 0xFFEEE8AA, - /* 131 PaleGreen */ 0xFF98FB98, - /* 132 PaleTurquoise */ 0xFFAFEEEE, - /* 133 PaleVioletRed */ 0xFFDB7093, - /* 134 PapayaWhip */ 0xFFFFEFD5, - /* 135 PeachPuff */ 0xFFFFDAB9, - /* 136 Peru */ 0xFFCD853F, - /* 137 Pink */ 0xFFFFC0CB, - /* 138 Plum */ 0xFFDDA0DD, - /* 139 PowderBlue */ 0xFFB0E0E6, - /* 140 Purple */ 0xFF800080, - /* 141 Red */ 0xFFFF0000, - /* 142 RosyBrown */ 0xFFBC8F8F, - /* 143 RoyalBlue */ 0xFF4169E1, - /* 144 SaddleBrown */ 0xFF8B4513, - /* 145 Salmon */ 0xFFFA8072, - /* 146 SandyBrown */ 0xFFF4A460, - /* 147 SeaGreen */ 0xFF2E8B57, - /* 148 SeaShell */ 0xFFFFF5EE, - /* 149 Sienna */ 0xFFA0522D, - /* 150 Silver */ 0xFFC0C0C0, - /* 151 SkyBlue */ 0xFF87CEEB, - /* 152 SlateBlue */ 0xFF6A5ACD, - /* 153 SlateGray */ 0xFF708090, - /* 154 Snow */ 0xFFFFFAFA, - /* 155 SpringGreen */ 0xFF00FF7F, - /* 156 SteelBlue */ 0xFF4682B4, - /* 157 Tan */ 0xFFD2B48C, - /* 158 Teal */ 0xFF008080, - /* 159 Thistle */ 0xFFD8BFD8, - /* 160 Tomato */ 0xFFFF6347, - /* 161 Turquoise */ 0xFF40E0D0, - /* 162 Violet */ 0xFFEE82EE, - /* 163 Wheat */ 0xFFF5DEB3, - /* 164 White */ 0xFFFFFFFF, - /* 165 WhiteSmoke */ 0xFFF5F5F5, - /* 166 Yellow */ 0xFFFFFF00, - /* 167 YellowGreen */ 0xFF9ACD32, - /* 168 ButtonFace */ 0xFFF0F0F0, - /* 169 ButtonHighlight */ 0xFFFFFFFF, - /* 170 ButtonShadow */ 0xFFA0A0A0, - /* 171 GradActiveCap */ 0xFFB9D1EA, - /* 172 GradInactiveCap */ 0xFFD7E4F2, - /* 173 MenuBar */ 0xFFF0F0F0, - /* 174 MenuHighlight */ 0xFF0078D7, - }; - - public static uint ArgbFromKnownColor(KnownColor color) - { - int idx = (int)color; - if (idx < 1 || idx > 174) - return 0xFF000000; - return s_colorTable[idx]; - } - - public static bool IsSystemColor(KnownColor color) - { - int idx = (int)color; - return (idx >= 1 && idx <= 26) || (idx >= 168 && idx <= 174); - } - } -} diff --git a/src/MiniPdf/Drawing/Colors/SystemColors.cs b/src/MiniPdf/Drawing/Colors/SystemColors.cs deleted file mode 100644 index bb16e42a..00000000 --- a/src/MiniPdf/Drawing/Colors/SystemColors.cs +++ /dev/null @@ -1,174 +0,0 @@ -namespace MiniSoftware.Drawing.Colors -{ - /// - /// Provides system-defined colors, mirroring System.Drawing.SystemColors. - /// Values are static defaults; they do not track the live OS theme. - /// - public static class SystemColors - { - /// - /// Gets the color of the active window border. - /// - public static Color ActiveBorder => Color.FromKnownColor(KnownColor.ActiveBorder); - - /// - /// Gets the color of the active window title bar. - /// - public static Color ActiveCaption => Color.FromKnownColor(KnownColor.ActiveCaption); - - /// - /// Gets the color of the text in the active window title bar. - /// - public static Color ActiveCaptionText => Color.FromKnownColor(KnownColor.ActiveCaptionText); - - /// - /// Gets the color of the application workspace. - /// - public static Color AppWorkspace => Color.FromKnownColor(KnownColor.AppWorkspace); - - /// - /// Gets the color of the face of a 3-D element. - /// - public static Color ButtonFace => Color.FromKnownColor(KnownColor.ButtonFace); - - /// - /// Gets the color of the highlight of a 3-D element. - /// - public static Color ButtonHighlight => Color.FromKnownColor(KnownColor.ButtonHighlight); - - /// - /// Gets the color of the shadow of a 3-D element. - /// - public static Color ButtonShadow => Color.FromKnownColor(KnownColor.ButtonShadow); - - /// - /// Gets the color of the control background. - /// - public static Color Control => Color.FromKnownColor(KnownColor.Control); - - /// - /// Gets the color of the shadow of a 3-D control. - /// - public static Color ControlDark => Color.FromKnownColor(KnownColor.ControlDark); - - /// - /// Gets the color of the dark shadow of a 3-D control. - /// - public static Color ControlDarkDark => Color.FromKnownColor(KnownColor.ControlDarkDark); - - /// - /// Gets the color of the light of a 3-D control. - /// - public static Color ControlLight => Color.FromKnownColor(KnownColor.ControlLight); - - /// - /// Gets the color of the highlight of a 3-D control. - /// - public static Color ControlLightLight => Color.FromKnownColor(KnownColor.ControlLightLight); - - /// - /// Gets the color of the text in a control. - /// - public static Color ControlText => Color.FromKnownColor(KnownColor.ControlText); - - /// - /// Gets the color of the desktop. - /// - public static Color Desktop => Color.FromKnownColor(KnownColor.Desktop); - - /// - /// Gets the color of the gradient in the active window title bar. - /// - public static Color GradientActiveCaption => Color.FromKnownColor(KnownColor.GradientActiveCaption); - - /// - /// Gets the color of the gradient in the inactive window title bar. - /// - public static Color GradientInactiveCaption => Color.FromKnownColor(KnownColor.GradientInactiveCaption); - - /// - /// Gets the color of the text that is dimmed. - /// - public static Color GrayText => Color.FromKnownColor(KnownColor.GrayText); - - /// - /// Gets the color of the highlighted item. - /// - public static Color Highlight => Color.FromKnownColor(KnownColor.Highlight); - - /// - /// Gets the color of the text in a highlighted item. - /// - public static Color HighlightText => Color.FromKnownColor(KnownColor.HighlightText); - - /// - /// Gets the color used to identify hot-tracked items. - /// - public static Color HotTrack => Color.FromKnownColor(KnownColor.HotTrack); - - /// - /// Gets the color of the inactive window border. - /// - public static Color InactiveBorder => Color.FromKnownColor(KnownColor.InactiveBorder); - - /// - /// Gets the color of the inactive window title bar. - /// - public static Color InactiveCaption => Color.FromKnownColor(KnownColor.InactiveCaption); - - /// - /// Gets the color of the text in the inactive window title bar. - /// - public static Color InactiveCaptionText => Color.FromKnownColor(KnownColor.InactiveCaptionText); - - /// - /// Gets the color of the tooltip background. - /// - public static Color Info => Color.FromKnownColor(KnownColor.Info); - - /// - /// Gets the color of the tooltip text. - /// - public static Color InfoText => Color.FromKnownColor(KnownColor.InfoText); - - /// - /// Gets the color of the menu background. - /// - public static Color Menu => Color.FromKnownColor(KnownColor.Menu); - - /// - /// Gets the color of the menu bar. - /// - public static Color MenuBar => Color.FromKnownColor(KnownColor.MenuBar); - - /// - /// Gets the color of the highlighted menu item. - /// - public static Color MenuHighlight => Color.FromKnownColor(KnownColor.MenuHighlight); - - /// - /// Gets the color of the text in a menu. - /// - public static Color MenuText => Color.FromKnownColor(KnownColor.MenuText); - - /// - /// Gets the color of the scroll bar. - /// - public static Color ScrollBar => Color.FromKnownColor(KnownColor.ScrollBar); - - /// - /// Gets the color of the window background. - /// - public static Color Window => Color.FromKnownColor(KnownColor.Window); - - /// - /// Gets the color of the window frame. - /// - public static Color WindowFrame => Color.FromKnownColor(KnownColor.WindowFrame); - - /// - /// Gets the color of the text in a window. - /// - public static Color WindowText => Color.FromKnownColor(KnownColor.WindowText); - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/Blend.cs b/src/MiniPdf/Drawing/Drawing2D/Blend.cs deleted file mode 100644 index 1bc144f2..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/Blend.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Stores the blend definition for gradient brushes including position and factor arrays. - /// - public sealed class Blend - { - /// - /// Initializes a new with empty factor and position arrays. - /// - public Blend() - { - Factors = System.Array.Empty(); - Positions = System.Array.Empty(); - } - - /// - /// Initializes a new with the specified number of elements. - /// - /// The number of blend positions and factors. - public Blend(int count) - { - Factors = new float[count]; - Positions = new float[count]; - } - - /// - /// Gets or sets the array of blend factors. - /// - public float[] Factors { get; set; } - - /// - /// Gets or sets the array of blend positions. - /// - public float[] Positions { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/ColorBlend.cs b/src/MiniPdf/Drawing/Drawing2D/ColorBlend.cs deleted file mode 100644 index 421509bc..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/ColorBlend.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Stores color and position information for gradient interpolation. - /// - public sealed class ColorBlend - { - /// - /// Initializes a new with empty color and position arrays. - /// - public ColorBlend() - { - Colors = System.Array.Empty(); - Positions = System.Array.Empty(); - } - - /// - /// Initializes a new with the specified number of colors. - /// - /// The number of colors and positions. - public ColorBlend(int count) - { - Colors = new Color[count]; - Positions = new float[count]; - } - - /// - /// Gets or sets the array of colors for gradient interpolation. - /// - public Color[] Colors { get; set; } - - /// - /// Gets or sets the array of positions corresponding to each color. - /// - public float[] Positions { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/CombineMode.cs b/src/MiniPdf/Drawing/Drawing2D/CombineMode.cs deleted file mode 100644 index dd7d22cb..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/CombineMode.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the combine mode for region operations. - /// - public enum CombineMode - { - /// - /// Replace the existing region. - /// - Replace = 0, - - /// - /// Intersect with the existing region. - /// - Intersect = 1, - - /// - /// Union with the existing region. - /// - Union = 2, - - /// - /// Exclusive OR with the existing region. - /// - Xor = 3, - - /// - /// Exclude from the existing region. - /// - Exclude = 4, - - /// - /// Complement the existing region. - /// - Complement = 5 - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/CompositingMode.cs b/src/MiniPdf/Drawing/Drawing2D/CompositingMode.cs deleted file mode 100644 index b6a800ed..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/CompositingMode.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies how pixels are composited during rendering. - /// - public enum CompositingMode - { - /// - /// Source pixels are blended with destination pixels based on alpha values. - /// - SourceOver = 0, - - /// - /// Source pixels replace destination pixels. - /// - SourceCopy = 1, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/CompositingQuality.cs b/src/MiniPdf/Drawing/Drawing2D/CompositingQuality.cs deleted file mode 100644 index 643cd796..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/CompositingQuality.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the quality level for compositing operations. - /// - public enum CompositingQuality - { - /// - /// Invalid quality setting. - /// - Invalid = -1, - - /// - /// Default quality (balanced speed and quality). - /// - Default = 0, - - /// - /// High speed, lower quality compositing. - /// - HighSpeed = 1, - - /// - /// High quality, slower compositing. - /// - HighQuality = 2, - - /// - /// Gamma-corrected compositing. - /// - GammaCorrected = 3, - - /// - /// Assume linear color space for compositing. - /// - AssumeLinear = 4, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/DashCap.cs b/src/MiniPdf/Drawing/Drawing2D/DashCap.cs deleted file mode 100644 index 0c9aee2f..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/DashCap.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the dash cap style for lines drawn with a . - /// - public enum DashCap - { - /// - /// Square cap with the same width as the line. - /// - Flat = 0, - - /// - /// Round cap with a semicircular arc. - /// - Round = 2, - - /// - /// Triangular cap pointing inward. - /// - Triangle = 3, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/DashStyle.cs b/src/MiniPdf/Drawing/Drawing2D/DashStyle.cs deleted file mode 100644 index aa7c23c0..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/DashStyle.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the style of dashed lines drawn with a . - /// - public enum DashStyle - { - /// - /// Solid line. - /// - Solid = 0, - - /// - /// Dashed line. - /// - Dash = 1, - - /// - /// Dotted line. - /// - Dot = 2, - - /// - /// Dash-dot line. - /// - DashDot = 3, - - /// - /// Dash-dot-dot line. - /// - DashDotDot = 4, - - /// - /// Custom dash pattern. - /// - Custom = 5, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/FillMode.cs b/src/MiniPdf/Drawing/Drawing2D/FillMode.cs deleted file mode 100644 index 671a62be..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/FillMode.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies how the interior of a shape defined by a is filled. - /// - public enum FillMode - { - /// - /// Alternate fill mode (default). - /// - Alternate = 0, - - /// - /// Winding fill mode. - /// - Winding = 1, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/FlushIntention.cs b/src/MiniPdf/Drawing/Drawing2D/FlushIntention.cs deleted file mode 100644 index a57e3dbf..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/FlushIntention.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies whether to flush immediately or synchronize before flushing. - /// - public enum FlushIntention - { - /// - /// Flush immediately. - /// - Flush = 0, - - /// - /// Synchronize before flushing. - /// - Sync = 1 - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/GraphicsPath.cs b/src/MiniPdf/Drawing/Drawing2D/GraphicsPath.cs deleted file mode 100644 index 1b65911d..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/GraphicsPath.cs +++ /dev/null @@ -1,1243 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Rendering; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Text; -using MiniSoftware.Drawing.Text.Bidi; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Represents a series of connected lines and curves that form a closed or open shape. - /// - /// - /// A can be used to draw and fill complex shapes. - /// It supports lines, arcs, Bézier curves, rectangles, and ellipses. - /// - public sealed class GraphicsPath : IDisposable - { - private readonly List _points; - private readonly List _types; - private FillMode _fillMode; - private bool _newFigure = true; - - private const float EllipseKappa = 0.5522847498f; - private const float DefaultFlatness = 0.25f; - - // ----------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------- - - /// - /// Initializes a new with the default fill mode. - /// - public GraphicsPath() : this(FillMode.Alternate) { } - - /// - /// Initializes a new with the specified fill mode. - /// - /// The fill mode that determines how the interior of the path is filled. - public GraphicsPath(FillMode fillMode) - { - _fillMode = fillMode; - _points = new List(); - _types = new List(); - } - - /// - /// Initializes a new from an array of points and types. - /// - /// The array of points that define the path. - /// The array of point types that define the corresponding point types. - /// The fill mode that determines how the interior of the path is filled. - public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode = FillMode.Alternate) - { - if (pts == null) throw new ArgumentNullException(nameof(pts)); - if (types == null) throw new ArgumentNullException(nameof(types)); - if (pts.Length != types.Length) - throw new ArgumentException("pts and types must be the same length."); - _fillMode = fillMode; - _points = new List(pts); - _types = new List(types); - _newFigure = _types.Count == 0 - || (_types[_types.Count - 1] & (byte)PathPointType.CloseSubpath) != 0; - } - - // ----------------------------------------------------------------------- - // Properties - // ----------------------------------------------------------------------- - - /// - /// Gets or sets the fill mode for this path. - /// - public FillMode FillMode { get => _fillMode; set => _fillMode = value; } - - /// - /// Gets the number of points in this path. - /// - public int PointCount => _points.Count; - - /// - /// Gets the array of points in this path. - /// - public PointF[] PathPoints => _points.ToArray(); - - /// - /// Gets the array of point types in this path. - /// - public byte[] PathTypes => _types.ToArray(); - - /// - /// Gets the path data for this path. - /// - public PathData PathData => new PathData { Points = _points.ToArray(), Types = _types.ToArray() }; - - // ----------------------------------------------------------------------- - // Figure control - // ----------------------------------------------------------------------- - - /// - /// Starts a new figure in this path. - /// - public void StartFigure() => _newFigure = true; - - /// - /// Closes the current figure by connecting a line from the current point to the start point. - /// - public void CloseFigure() - { - if (_types.Count > 0 && !_newFigure) - _types[_types.Count - 1] |= (byte)PathPointType.CloseSubpath; - _newFigure = true; - } - - /// - /// Closes all open figures in this path. - /// - public void CloseAllFigures() - { - for (int i = 1; i < _types.Count; i++) - if ((_types[i] & 0x07) == (byte)PathPointType.Start) - _types[i - 1] |= (byte)PathPointType.CloseSubpath; - - if (_types.Count > 0) - _types[_types.Count - 1] |= (byte)PathPointType.CloseSubpath; - - _newFigure = true; - } - - // ----------------------------------------------------------------------- - // Lines - // ----------------------------------------------------------------------- - - /// - /// Adds a line to this path. - /// - /// The x-coordinate of the start point. - /// The y-coordinate of the start point. - /// The x-coordinate of the end point. - /// The y-coordinate of the end point. - public void AddLine(float x1, float y1, float x2, float y2) - => AddLine(new PointF(x1, y1), new PointF(x2, y2)); - - /// - /// Adds a line to this path. - /// - /// The start point of the line. - /// The end point of the line. - public void AddLine(PointF pt1, PointF pt2) - { - _points.Add(pt1); - _types.Add(_newFigure ? (byte)PathPointType.Start : (byte)PathPointType.Line); - _newFigure = false; - - _points.Add(pt2); - _types.Add((byte)PathPointType.Line); - } - - /// - /// Adds a series of connected lines to this path. - /// - /// The array of points that define the lines. - public void AddLines(PointF[] points) - { - if (points == null || points.Length == 0) return; - - for (int i = 0; i < points.Length; i++) - { - _points.Add(points[i]); - _types.Add(i == 0 && _newFigure - ? (byte)PathPointType.Start - : (byte)PathPointType.Line); - } - _newFigure = false; - } - - // ----------------------------------------------------------------------- - // Rectangles - // ----------------------------------------------------------------------- - - /// - /// Adds a rectangle to this path. - /// - /// The rectangle to add. - public void AddRectangle(RectangleF rect) - { - _points.Add(new PointF(rect.X, rect.Y)); - _types.Add((byte)PathPointType.Start); - - _points.Add(new PointF(rect.X + rect.Width, rect.Y)); - _types.Add((byte)PathPointType.Line); - - _points.Add(new PointF(rect.X + rect.Width, rect.Y + rect.Height)); - _types.Add((byte)PathPointType.Line); - - _points.Add(new PointF(rect.X, rect.Y + rect.Height)); - _types.Add((byte)((byte)PathPointType.Line | (byte)PathPointType.CloseSubpath)); - - _newFigure = true; - } - - /// - /// Adds a rectangle to this path. - /// - /// The rectangle to add. - public void AddRectangle(Rectangle rect) - => AddRectangle(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - /// - /// Adds a series of rectangles to this path. - /// - /// The array of rectangles to add. - public void AddRectangles(RectangleF[] rects) - { - if (rects == null) return; - foreach (var r in rects) AddRectangle(r); - } - - /// - /// Adds a series of rectangles to this path. - /// - /// The array of rectangles to add. - public void AddRectangles(Rectangle[] rects) - { - if (rects == null) return; - foreach (var r in rects) AddRectangle(r); - } - - // ----------------------------------------------------------------------- - // Ellipse (4 cubic Béziers, kappa = 0.5522847498) - // ----------------------------------------------------------------------- - - /// - /// Adds an ellipse to this path. - /// - /// The x-coordinate of the upper-left corner of the bounding rectangle. - /// The y-coordinate of the upper-left corner of the bounding rectangle. - /// The width of the ellipse. - /// The height of the ellipse. - public void AddEllipse(float x, float y, float width, float height) - => AddEllipseCore(x + width * 0.5f, y + height * 0.5f, width * 0.5f, height * 0.5f); - - /// - /// Adds an ellipse to this path. - /// - /// The bounding rectangle of the ellipse. - public void AddEllipse(RectangleF rect) - => AddEllipseCore(rect.X + rect.Width * 0.5f, rect.Y + rect.Height * 0.5f, - rect.Width * 0.5f, rect.Height * 0.5f); - - /// - /// Adds an ellipse to this path. - /// - /// The bounding rectangle of the ellipse. - public void AddEllipse(Rectangle rect) - => AddEllipse(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - private void AddEllipseCore(float cx, float cy, float rx, float ry) - { - float k = EllipseKappa; - - _points.Add(new PointF(cx + rx, cy)); _types.Add((byte)PathPointType.Start); - - // Segment 0 → (cx, cy+ry) - AddBez(cx + rx, cy + k * ry, cx + k * rx, cy + ry, cx, cy + ry); - // Segment 1 → (cx-rx, cy) - AddBez(cx - k * rx, cy + ry, cx - rx, cy + k * ry, cx - rx, cy); - // Segment 2 → (cx, cy-ry) - AddBez(cx - rx, cy - k * ry, cx - k * rx, cy - ry, cx, cy - ry); - // Segment 3 → (cx+rx, cy) — close - AddBez(cx + k * rx, cy - ry, cx + rx, cy - k * ry, cx + rx, cy, close: true); - - _newFigure = true; - } - - private void AddBez(float c1x, float c1y, float c2x, float c2y, float ex, float ey, - bool close = false) - { - _points.Add(new PointF(c1x, c1y)); _types.Add((byte)PathPointType.Bezier); - _points.Add(new PointF(c2x, c2y)); _types.Add((byte)PathPointType.Bezier); - _points.Add(new PointF(ex, ey)); - _types.Add(close - ? (byte)((byte)PathPointType.Bezier | (byte)PathPointType.CloseSubpath) - : (byte)PathPointType.Bezier); - } - - // ----------------------------------------------------------------------- - // Arc (up to 4 Bézier segments, split at 90° boundaries) - // ----------------------------------------------------------------------- - - /// - /// Adds an arc to this path. - /// - /// The x-coordinate of the upper-left corner of the bounding rectangle. - /// The y-coordinate of the upper-left corner of the bounding rectangle. - /// The width of the bounding rectangle. - /// The height of the bounding rectangle. - /// The starting angle of the arc in degrees. - /// The sweep angle of the arc in degrees. - public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle) - => AddArcCore(x + width * 0.5f, y + height * 0.5f, width * 0.5f, height * 0.5f, - startAngle, sweepAngle); - - /// - /// Adds an arc to this path. - /// - /// The bounding rectangle of the arc. - /// The starting angle of the arc in degrees. - /// The sweep angle of the arc in degrees. - public void AddArc(RectangleF rect, float startAngle, float sweepAngle) - => AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); - - /// - /// Adds an arc to this path. - /// - /// The bounding rectangle of the arc. - /// The starting angle of the arc in degrees. - /// The sweep angle of the arc in degrees. - public void AddArc(Rectangle rect, float startAngle, float sweepAngle) - => AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); - - private void AddArcCore(float cx, float cy, float rx, float ry, - float startAngle, float sweepAngle) - { - if (sweepAngle == 0f) return; - if (sweepAngle > 360f) sweepAngle = 360f; - if (sweepAngle < -360f) sweepAngle = -360f; - - int sign = sweepAngle >= 0 ? 1 : -1; - float remaining = Math.Abs(sweepAngle); - float cur = startAngle; - bool isFirst = true; - - while (remaining > 0f) - { - float seg = Math.Min(remaining, 90f) * sign; - AddArcSegment(cx, cy, rx, ry, cur, seg, isFirst); - isFirst = false; - cur += seg; - remaining -= Math.Abs(seg); - } - } - - private void AddArcSegment(float cx, float cy, float rx, float ry, - float startDeg, float sweepDeg, bool isFirst) - { - double a0 = startDeg * (Math.PI / 180.0); - double a1 = (startDeg + sweepDeg) * (Math.PI / 180.0); - double da = a1 - a0; - double k = (4.0 / 3.0) * Math.Tan(da / 4.0); - - float cos0 = (float)Math.Cos(a0), sin0 = (float)Math.Sin(a0); - float cos1 = (float)Math.Cos(a1), sin1 = (float)Math.Sin(a1); - - var p0 = new PointF(cx + rx * cos0, cy + ry * sin0); - var c1 = new PointF(cx + rx * (cos0 - (float)(k * sin0)), - cy + ry * (sin0 + (float)(k * cos0))); - var c2 = new PointF(cx + rx * (cos1 + (float)(k * sin1)), - cy + ry * (sin1 - (float)(k * cos1))); - var p1 = new PointF(cx + rx * cos1, cy + ry * sin1); - - if (isFirst) - { - _points.Add(p0); - _types.Add(_newFigure ? (byte)PathPointType.Start : (byte)PathPointType.Line); - _newFigure = false; - } - - _points.Add(c1); _types.Add((byte)PathPointType.Bezier); - _points.Add(c2); _types.Add((byte)PathPointType.Bezier); - _points.Add(p1); _types.Add((byte)PathPointType.Bezier); - } - - // ----------------------------------------------------------------------- - // Béziers - // ----------------------------------------------------------------------- - - /// - /// Adds a cubic Bézier curve to this path. - /// - /// The starting point of the curve. - /// The first control point for the curve. - /// The second control point for the curve. - /// The ending point of the curve. - public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4) - { - _points.Add(pt1); - _types.Add(_newFigure ? (byte)PathPointType.Start : (byte)PathPointType.Line); - _newFigure = false; - _points.Add(pt2); _types.Add((byte)PathPointType.Bezier); - _points.Add(pt3); _types.Add((byte)PathPointType.Bezier); - _points.Add(pt4); _types.Add((byte)PathPointType.Bezier); - } - - /// - /// Adds a cubic Bézier curve to this path. - /// - /// The x-coordinate of the starting point. - /// The y-coordinate of the starting point. - /// The x-coordinate of the first control point. - /// The y-coordinate of the first control point. - /// The x-coordinate of the second control point. - /// The y-coordinate of the second control point. - /// The x-coordinate of the ending point. - /// The y-coordinate of the ending point. - public void AddBezier(float x1, float y1, float x2, float y2, - float x3, float y3, float x4, float y4) - => AddBezier(new PointF(x1, y1), new PointF(x2, y2), - new PointF(x3, y3), new PointF(x4, y4)); - - /// - /// Adds a series of connected Bézier curves to this path. - /// - /// The array of points that define the curves. Must have length 1 + 3n. - public void AddBeziers(PointF[] points) - { - if (points == null || points.Length < 4) return; - if ((points.Length - 1) % 3 != 0) - throw new ArgumentException("Length must be 1 + 3n.", nameof(points)); - - _points.Add(points[0]); - _types.Add(_newFigure ? (byte)PathPointType.Start : (byte)PathPointType.Line); - _newFigure = false; - - for (int i = 1; i < points.Length; i++) - { - _points.Add(points[i]); - _types.Add((byte)PathPointType.Bezier); - } - } - - // ----------------------------------------------------------------------- - // Polygon - // ----------------------------------------------------------------------- - - /// - /// Adds a polygon to this path. - /// - /// The array of points that define the polygon. - public void AddPolygon(PointF[] points) - { - if (points == null || points.Length < 2) return; - - _points.Add(points[0]); _types.Add((byte)PathPointType.Start); - for (int i = 1; i < points.Length; i++) - { - _points.Add(points[i]); _types.Add((byte)PathPointType.Line); - } - _types[_types.Count - 1] |= (byte)PathPointType.CloseSubpath; - _newFigure = true; - } - - /// - /// Adds a polygon to this path. - /// - /// The array of points that define the polygon. - public void AddPolygon(Point[] points) - { - if (points == null) return; - var f = new PointF[points.Length]; - for (int i = 0; i < points.Length; i++) f[i] = new PointF(points[i].X, points[i].Y); - AddPolygon(f); - } - - // ----------------------------------------------------------------------- - // Cardinal spline (Catmull-Rom → Bézier conversion) - // c1 = p[i] + t*(p[i+1]-p[i-1])/3 c2 = p[i+1] - t*(p[i+2]-p[i])/3 - // ----------------------------------------------------------------------- - - /// - /// Adds a cardinal spline curve to this path. - /// - /// The array of points that define the curve. - public void AddCurve(PointF[] points) => AddCurve(points, 0.5f); - - /// - /// Adds a cardinal spline curve to this path with the specified tension. - /// - /// The array of points that define the curve. - /// The tension of the curve (0.0 to 1.0). - public void AddCurve(PointF[] points, float tension) - { - if (points == null || points.Length < 2) - throw new ArgumentException("Need ≥ 2 points.", nameof(points)); - AddCurve(points, 0, points.Length - 1, tension); - } - - /// - /// Adds a cardinal spline curve to this path with the specified offset, number of segments, and tension. - /// - /// The array of points that define the curve. - /// The offset in the points array where the curve begins. - /// The number of segments in the curve. - /// The tension of the curve (0.0 to 1.0). - public void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension) - { - if (points == null) throw new ArgumentNullException(nameof(points)); - if (numberOfSegments < 1) - throw new ArgumentException("numberOfSegments ≥ 1 required."); - if (offset < 0 || offset + numberOfSegments >= points.Length) - throw new ArgumentOutOfRangeException(nameof(offset)); - - _points.Add(points[offset]); - _types.Add(_newFigure ? (byte)PathPointType.Start : (byte)PathPointType.Line); - _newFigure = false; - - for (int i = offset; i < offset + numberOfSegments; i++) - { - PointF p0 = points[i]; - PointF p1 = points[i + 1]; - PointF pm1 = i > 0 ? points[i - 1] : points[i]; - PointF pp2 = i + 2 < points.Length ? points[i + 2] : points[i + 1]; - - var c1 = new PointF(p0.X + tension * (p1.X - pm1.X) / 3f, - p0.Y + tension * (p1.Y - pm1.Y) / 3f); - var c2 = new PointF(p1.X - tension * (pp2.X - p0.X) / 3f, - p1.Y - tension * (pp2.Y - p0.Y) / 3f); - - _points.Add(c1); _types.Add((byte)PathPointType.Bezier); - _points.Add(c2); _types.Add((byte)PathPointType.Bezier); - _points.Add(p1); _types.Add((byte)PathPointType.Bezier); - } - } - - /// - /// Adds a closed curve to this path. - /// - /// The array of points that define the curve. - /// The tension of the curve (0.0 to 1.0). - public void AddClosedCurve(PointF[] points, float tension = 0.5f) - { - if (points == null || points.Length < 3) - throw new ArgumentException("Need ≥ 3 points.", nameof(points)); - - int n = points.Length; - _points.Add(points[0]); _types.Add((byte)PathPointType.Start); - - for (int i = 0; i < n; i++) - { - PointF p0 = points[i]; - PointF p1 = points[(i + 1) % n]; - PointF pm1 = points[(i + n - 1) % n]; - PointF pp2 = points[(i + 2) % n]; - - var c1 = new PointF(p0.X + tension * (p1.X - pm1.X) / 3f, - p0.Y + tension * (p1.Y - pm1.Y) / 3f); - var c2 = new PointF(p1.X - tension * (pp2.X - p0.X) / 3f, - p1.Y - tension * (pp2.Y - p0.Y) / 3f); - - _points.Add(c1); _types.Add((byte)PathPointType.Bezier); - _points.Add(c2); _types.Add((byte)PathPointType.Bezier); - byte endType = (byte)PathPointType.Bezier; - if (i == n - 1) endType |= (byte)PathPointType.CloseSubpath; - _points.Add(p1); _types.Add(endType); - } - _newFigure = true; - } - - // ----------------------------------------------------------------------- - // Sub-path composition - // ----------------------------------------------------------------------- - - /// - /// Adds the specified path to this path. - /// - /// The path to add. - /// Whether to connect the added path to the current path. - public void AddPath(GraphicsPath addingPath, bool connect) - { - if (addingPath == null) throw new ArgumentNullException(nameof(addingPath)); - if (addingPath._points.Count == 0) return; - - int insertAt = _points.Count; - _points.AddRange(addingPath._points); - _types.AddRange(addingPath._types); - - // If connecting and there is an open figure, change the added path's first - // Start point into a Line so it continues the current subpath. - if (connect && !_newFigure && insertAt > 0) - _types[insertAt] = (byte)((_types[insertAt] & ~0x07) | (byte)PathPointType.Line); - - _newFigure = _types.Count > 0 - && (_types[_types.Count - 1] & (byte)PathPointType.CloseSubpath) != 0; - } - - // ----------------------------------------------------------------------- - // AddString — text layout engine (Batch 12) - // ----------------------------------------------------------------------- - - /// - /// Adds a text string to this path. - /// - /// The string to add. - /// The font family. - /// The font style. - /// The em size of the font. - /// The origin point. - /// The string format. - public void AddString(string s, FontFamily family, int style, float emSize, - PointF origin, StringFormat? format) - => AddString(s, family, style, emSize, - new RectangleF(origin.X, origin.Y, 1e7f, 1e7f), - format ?? new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Adds a text string to this path. - /// - /// The string to add. - /// The font family. - /// The font style. - /// The em size of the font. - /// The layout rectangle. - /// The string format. - public void AddString(string s, FontFamily family, int style, float emSize, - RectangleF layoutRect, StringFormat? format) - { - if (string.IsNullOrEmpty(s)) return; - if (family == null) throw new ArgumentNullException(nameof(family)); - - var drawingStyle = (Enums.FontStyle)style; - using var font = new Text.Font(family, emSize, drawingStyle, GraphicsUnit.Point); - - // Standard screen DPI for point-sized fonts. - const float dpi = 96f; - var lines = TextLayoutEngine.Layout(s, font, layoutRect, format, dpi, dpi); - - IFont? fontFace = family.GetFontFace(drawingStyle); - if (fontFace == null) return; // No real font — cannot produce glyph outlines. - - var metrics = family.GetMetricsData(drawingStyle); - float emPixels = emSize * dpi / 72f; // Points → pixels at 96 DPI - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) - : 1f; - - var renderer = new GlyphOutlineRenderer(fontFace); - var rasterizer = new GlyphRasterizer(); - - float firstTabOffset; - float[] tabStops = (format ?? StringFormat.GenericDefault).GetTabStops(out firstTabOffset); - - foreach (var line in lines) - { - foreach (var run in line.Runs) - { - float curX = run.X; - foreach (char c in run.Text) - { - float adv = TextLayoutEngine.GetCharAdvance( - c, curX - run.X, - fontFace, emScale, - emPixels * TextLayoutEngine.DefaultCharWidthFactor, - firstTabOffset, tabStops, emPixels); - - if (c != '\t') - { - var gid = fontFace.Encoding.DecodeToGid(c); - if (gid != null) - { - using var glyphPath = rasterizer.RenderGlyph( - renderer, gid, emScale, curX, run.Baseline); - if (glyphPath.PointCount > 0) - AddPath(glyphPath, false); - } - } - - curX += adv; - } - } - } - } - - // ----------------------------------------------------------------------- - // AddRichText — rich text (mixed fonts/styles/sizes/brushes) - // ----------------------------------------------------------------------- - - /// - /// Adds rich text to this path, allowing mixed fonts, styles, sizes, and brushes. - /// - public void AddRichText(string s, FontFamily family, int style, float emSize, - RichTextOptions? options, PointF origin, StringFormat? format) - => AddRichText(s, family, style, emSize, options, - new RectangleF(origin.X, origin.Y, 1e7f, 1e7f), - format ?? new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Adds rich text to this path within the specified layout rectangle. - /// - public void AddRichText(string s, FontFamily family, int style, float emSize, - RichTextOptions? options, RectangleF layoutRect, - StringFormat? format) - { - if (string.IsNullOrEmpty(s)) return; - if (family == null) throw new ArgumentNullException(nameof(family)); - - var drawingStyle = (Enums.FontStyle)style; - var sf = format ?? StringFormat.GenericDefault; - const float dpi = 96f; - - using var defaultFont = new Text.Font(family, emSize, drawingStyle, GraphicsUnit.Point); - var chain = options?.Fallback; - var runs = RunSegmenter.Segment(s, defaultFont, options, sf, chain); - var lines = TextLayoutEngine.Layout(runs, layoutRect, sf, dpi, dpi); - if (lines.Count == 0) return; - - float firstTabOffset; - float[] tabStops = sf.GetTabStops(out firstTabOffset); - - var rendererCache = new Dictionary(); - var rasterizer = new GlyphRasterizer(); - - foreach (var line in lines) - { - foreach (var run in line.Runs) - { - var fontFace = run.Font.FontFamily.GetFontFace(run.Font.Style); - if (fontFace == null) continue; - - if (!rendererCache.TryGetValue(fontFace, out var renderer)) - { - renderer = new GlyphOutlineRenderer(fontFace); - rendererCache[fontFace] = renderer; - } - - var metrics = run.Font.FontFamily.GetMetricsData(run.Font.Style); - float emPixels = TextLayoutEngine.FontSizeToPixels( - run.Font.Size, run.Font.Unit, dpi); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) : 1f; - float fallbackW = emPixels * TextLayoutEngine.DefaultCharWidthFactor; - - float curX = run.X; - foreach (char c in run.Text) - { - if (c == '\t' || c == '\r' || c == '\n') continue; - - char renderChar = c; - char mirrored = c; - if (run.IsRTL && BidiMirroring.TryGetMirror(c, out mirrored)) - renderChar = mirrored; - - var gid = fontFace.Encoding.DecodeToGid(renderChar); - if (gid != null) - { - using var glyphPath = rasterizer.RenderGlyph( - renderer, gid, emScale, curX, run.Baseline); - if (glyphPath.PointCount > 0) - AddPath(glyphPath, false); - } - - curX += TextLayoutEngine.GetCharAdvance(c, curX - run.X, - fontFace, emScale, fallbackW, - firstTabOffset, tabStops, emPixels); - } - } - } - } - - // ----------------------------------------------------------------------- - // AddStringOnPath — text-on-path (Batch 21) - // ----------------------------------------------------------------------- - - /// - /// Adds a text string laid out along the specified baseline path. - /// Each glyph is positioned on the path and rotated to follow the - /// path tangent. - /// - /// The string to add. - /// The font family. - /// The font style. - /// The em size of the font in points. - /// The baseline path along which to lay out the text, in pixel coordinates. - public void AddStringOnPath(string s, FontFamily family, int style, float emSize, - GraphicsPath baselinePath) - => AddStringOnPath(s, family, style, emSize, baselinePath, null, null); - - /// - /// Adds a text string laid out along the specified baseline path. - /// - /// The string to add. - /// The font family. - /// The font style. - /// The em size of the font in points. - /// The baseline path along which to lay out the text, in pixel coordinates. - /// The string format (only is used), or null for default. - public void AddStringOnPath(string s, FontFamily family, int style, float emSize, - GraphicsPath baselinePath, StringFormat? format) - => AddStringOnPath(s, family, style, emSize, baselinePath, format, null); - - /// - /// Adds a text string laid out along the specified baseline path. - /// - /// The string to add. - /// The font family. - /// The font style. - /// The em size of the font in points. - /// The baseline path along which to lay out the text, in pixel coordinates. - /// The string format (only is used), or null for default. - /// Placement options (start offset, perpendicular offset, overflow), or null for defaults. - public void AddStringOnPath(string s, FontFamily family, int style, float emSize, - GraphicsPath baselinePath, - StringFormat? format, TextOnPathOptions? options) - { - if (family == null) throw new ArgumentNullException(nameof(family)); - if (baselinePath == null) throw new ArgumentNullException(nameof(baselinePath)); - if (string.IsNullOrEmpty(s)) return; - - var drawingStyle = (Enums.FontStyle)style; - using var font = new Text.Font(family, emSize, drawingStyle, GraphicsUnit.Point); - - // AddString convention: 96 DPI for point-sized fonts. - const float dpi = 96f; - GraphicsPath result = TextOnPathLayout.BuildPath( - s, font, baselinePath, format, options, dpi, dpi); - - if (result.PointCount > 0) - AddPath(result, false); - } - - // ----------------------------------------------------------------------- - // Transform - // ----------------------------------------------------------------------- - - /// - /// Applies a transformation matrix to this path. - /// - /// The transformation matrix. - public void Transform(Matrix matrix) - { - if (matrix == null) throw new ArgumentNullException(nameof(matrix)); - if (_points.Count == 0) return; - var pts = _points.ToArray(); - matrix.TransformPoints(pts); - _points.Clear(); - _points.AddRange(pts); - } - - // ----------------------------------------------------------------------- - // Flatten (de Casteljau subdivision until chord error < flatness) - // ----------------------------------------------------------------------- - - /// - /// Flattens this path using the default flatness. - /// - public void Flatten() => Flatten(null, DefaultFlatness); - - /// - /// Flattens this path using the specified transformation matrix and default flatness. - /// - /// The transformation matrix to apply before flattening. - public void Flatten(Matrix? matrix) => Flatten(matrix, DefaultFlatness); - - /// - /// Flattens this path using the specified transformation matrix and flatness. - /// - /// The transformation matrix to apply before flattening. - /// The maximum allowable error between the curve and the flattened line. - public void Flatten(Matrix? matrix, float flatness) - { - if (matrix != null) Transform(matrix); - - var newPts = new List(_points.Count); - var newTypes = new List(_points.Count); - int i = 0; - - while (i < _points.Count) - { - byte rawType = (byte)(_types[i] & (byte)PathPointType.PathTypeMask); - - if (rawType == (byte)PathPointType.Bezier - && newPts.Count > 0 && i + 2 < _points.Count) - { - PointF p0 = newPts[newPts.Count - 1]; - PointF c1 = _points[i]; - PointF c2 = _points[i + 1]; - PointF p1 = _points[i + 2]; - bool closeIt = (_types[i + 2] & (byte)PathPointType.CloseSubpath) != 0; - - FlattenBezier(p0, c1, c2, p1, newPts, newTypes, flatness, closeIt); - i += 3; - } - else - { - // Preserve point as-is; Bezier that isn't in a valid triplet → Line - byte flat = rawType == (byte)PathPointType.Bezier - ? (byte)PathPointType.Line - : rawType; - if ((_types[i] & (byte)PathPointType.CloseSubpath) != 0) - flat |= (byte)PathPointType.CloseSubpath; - newPts.Add(_points[i]); - newTypes.Add(flat); - i++; - } - } - - _points.Clear(); _points.AddRange(newPts); - _types.Clear(); _types.AddRange(newTypes); - } - - private static void FlattenBezier(PointF p0, PointF c1, PointF c2, PointF p1, - List pts, List types, - float flatness, bool close) - { - float dx = p1.X - p0.X, dy = p1.Y - p0.Y; - float lenSq = dx * dx + dy * dy; - float ftolSq = flatness * flatness * lenSq; - - // Perpendicular cross-product distances (squared) - float d1sq = CrossSq(c1.X - p0.X, c1.Y - p0.Y, dx, dy); - float d2sq = CrossSq(c2.X - p0.X, c2.Y - p0.Y, dx, dy); - - if (d1sq <= ftolSq && d2sq <= ftolSq) - { - byte t = (byte)PathPointType.Line; - if (close) t |= (byte)PathPointType.CloseSubpath; - pts.Add(p1); - types.Add(t); - } - else - { - PointF m01 = Mid(p0, c1); - PointF m12 = Mid(c1, c2); - PointF m23 = Mid(c2, p1); - PointF m012 = Mid(m01, m12); - PointF m123 = Mid(m12, m23); - PointF m0123 = Mid(m012, m123); - - FlattenBezier(p0, m01, m012, m0123, pts, types, flatness, false); - FlattenBezier(m0123, m123, m23, p1, pts, types, flatness, close); - } - } - - private static float CrossSq(float ax, float ay, float bx, float by) - { float c = ax * by - ay * bx; return c * c; } - - private static PointF Mid(PointF a, PointF b) - => new PointF((a.X + b.X) * 0.5f, (a.Y + b.Y) * 0.5f); - - // ----------------------------------------------------------------------- - // GetBounds - // ----------------------------------------------------------------------- - - /// - /// Gets the bounding rectangle of this path. - /// - /// The bounding rectangle. - public RectangleF GetBounds() => GetBounds(null, null); - - /// - /// Gets the bounding rectangle of this path after applying the specified transformation. - /// - /// The transformation matrix. - /// The bounding rectangle. - public RectangleF GetBounds(Matrix? matrix) => GetBounds(matrix, null); - - /// - /// Gets the bounding rectangle of this path after applying the specified transformation and pen width. - /// - /// The transformation matrix. - /// The pen used to determine the width of the bounding rectangle. - /// The bounding rectangle. - public RectangleF GetBounds(Matrix? matrix, Pens.Pen? pen) - { - if (_points.Count == 0) return RectangleF.Empty; - - var pts = _points.ToArray(); - if (matrix != null) matrix.TransformPoints(pts); - - float minX = pts[0].X, minY = pts[0].Y; - float maxX = pts[0].X, maxY = pts[0].Y; - for (int i = 1; i < pts.Length; i++) - { - if (pts[i].X < minX) minX = pts[i].X; - if (pts[i].Y < minY) minY = pts[i].Y; - if (pts[i].X > maxX) maxX = pts[i].X; - if (pts[i].Y > maxY) maxY = pts[i].Y; - } - - float pw = pen != null ? pen.Width * 0.5f : 0f; - return new RectangleF(minX - pw, minY - pw, - maxX - minX + pw * 2f, maxY - minY + pw * 2f); - } - - // ----------------------------------------------------------------------- - // IsVisible / IsOutlineVisible - // ----------------------------------------------------------------------- - - /// - /// Determines whether the specified point is contained within this path. - /// - /// The x-coordinate of the point. - /// The y-coordinate of the point. - /// true if the point is contained within the path; otherwise, false. - public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y)); - - /// - /// Determines whether the specified point is contained within this path. - /// - /// The point to test. - /// true if the point is contained within the path; otherwise, false. - public bool IsVisible(PointF pt) - { - if (_points.Count == 0) return false; - var flat = Clone(); - flat.Flatten(); - return IsVisibleFlattened(flat, pt.X, pt.Y); - } - - /// - /// Determines whether the specified point is contained within the outline of this path. - /// - /// The point to test. - /// The pen used to determine the width of the outline. - /// true if the point is contained within the outline; otherwise, false. - public bool IsOutlineVisible(PointF pt, Pens.Pen pen) - { - if (pen == null || _points.Count == 0) return false; - float halfW = pen.Width * 0.5f; - var flat = Clone(); - flat.Flatten(); - var pts = flat._points; - var types = flat._types; - int subStart = -1; - - for (int i = 0; i < pts.Count; i++) - { - byte t = (byte)(types[i] & (byte)PathPointType.PathTypeMask); - if (t == (byte)PathPointType.Start) - { - subStart = i; - } - else if (i > 0 && SegDist(pt, pts[i - 1], pts[i]) <= halfW) - return true; - - if ((types[i] & (byte)PathPointType.CloseSubpath) != 0 - && subStart >= 0 && subStart != i - && SegDist(pt, pts[i], pts[subStart]) <= halfW) - return true; - } - return false; - } - - // ----------------------------------------------------------------------- - // Widen (stub — StrokeExpander in Batch 8) - // ----------------------------------------------------------------------- - - /// - /// Widens this path using the specified pen. - /// - /// The pen used to widen the path. - public void Widen(Pen pen) => Widen(pen, null, DefaultFlatness); - - /// - /// Widens this path using the specified pen and transformation matrix. - /// - /// The pen used to widen the path. - /// The transformation matrix. - public void Widen(Pen pen, Matrix? m) => Widen(pen, m, DefaultFlatness); - - /// - /// Widens this path using the specified pen, transformation matrix, and flatness. - /// - /// The pen used to widen the path. - /// The transformation matrix. - /// The flatness of the widened path. - public void Widen(Pen pen, Matrix? m, float flatness) - { - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - var widened = Rendering.StrokeExpander.Expand(this, pen, m, flatness); - _points.Clear(); - _types.Clear(); - _points.AddRange(widened.PathPoints); - _types.AddRange(widened.PathTypes); - _newFigure = _types.Count == 0 - || (_types[_types.Count - 1] & (byte)PathPointType.CloseSubpath) != 0; - } - - // ----------------------------------------------------------------------- - // Modify - // ----------------------------------------------------------------------- - - /// - /// Clears all points and types from this path. - /// - public void Reset() - { - _points.Clear(); - _types.Clear(); - _newFigure = true; - } - - /// - /// Reverses the order of points in this path. - /// - public void Reverse() - { - if (_points.Count == 0) return; - - var outPts = new List(_points.Count); - var outTypes = new List(_types.Count); - - // Collect subpath ranges - var starts = new List(); - var ends = new List(); - int s = -1; - - for (int i = 0; i < _types.Count; i++) - { - if ((_types[i] & 0x07) == (byte)PathPointType.Start) - { - if (s >= 0) { starts.Add(s); ends.Add(i - 1); } - s = i; - } - } - if (s >= 0) { starts.Add(s); ends.Add(_types.Count - 1); } - - foreach (var (from, to) in Zip(starts, ends)) - { - bool closed = (_types[to] & (byte)PathPointType.CloseSubpath) != 0; - for (int i = to; i >= from; i--) - { - outPts.Add(_points[i]); - byte t = i == to ? (byte)PathPointType.Start - : i == from && closed ? (byte)((byte)PathPointType.Line | (byte)PathPointType.CloseSubpath) - : (byte)PathPointType.Line; - outTypes.Add(t); - } - } - - _points.Clear(); _points.AddRange(outPts); - _types.Clear(); _types.AddRange(outTypes); - } - - // ----------------------------------------------------------------------- - // Clone / Dispose - // ----------------------------------------------------------------------- - - /// - /// Creates an exact copy of this . - /// - /// A new that is a copy of this instance. - public GraphicsPath Clone() - { - var c = new GraphicsPath(_fillMode) { _newFigure = _newFigure }; - c._points.AddRange(_points); - c._types.AddRange(_types); - return c; - } - - /// - /// Releases all resources used by this . - /// - public void Dispose() { /* no unmanaged resources */ } - - // ----------------------------------------------------------------------- - // Private helpers - // ----------------------------------------------------------------------- - - private static bool IsVisibleFlattened(GraphicsPath path, float px, float py) - { - var pts = path._points; - var types = path._types; - if (pts.Count < 2) return false; - - int crossings = 0, winding = 0; - bool alternate = path._fillMode == FillMode.Alternate; - int subStart = -1; - - for (int i = 0; i < pts.Count; i++) - { - byte t = (byte)(types[i] & (byte)PathPointType.PathTypeMask); - if (t == (byte)PathPointType.Start) - { - subStart = i; - } - else - { - float ax = pts[i - 1].X, ay = pts[i - 1].Y; - float bx = pts[i].X, by = pts[i].Y; - if (alternate) crossings += RayCross(px, py, ax, ay, bx, by); - else winding += WindingAdd(px, py, ax, ay, bx, by); - } - - if ((types[i] & (byte)PathPointType.CloseSubpath) != 0 - && subStart >= 0 && subStart != i) - { - float ax = pts[i].X, ay = pts[i].Y; - float bx = pts[subStart].X, by = pts[subStart].Y; - if (alternate) crossings += RayCross(px, py, ax, ay, bx, by); - else winding += WindingAdd(px, py, ax, ay, bx, by); - } - } - - return alternate ? (crossings & 1) != 0 : winding != 0; - } - - private static int RayCross(float px, float py, - float ax, float ay, float bx, float by) - { - if ((ay <= py && by > py) || (by <= py && ay > py)) - if (px < ax + (py - ay) / (by - ay) * (bx - ax)) - return 1; - return 0; - } - - private static int WindingAdd(float px, float py, - float ax, float ay, float bx, float by) - { - if (ay <= py) - { - if (by > py && ax * by - ay * bx - px * (by - ay) + py * (bx - ax) > 0) - return 1; - } - else if (by <= py && ax * by - ay * bx - px * (by - ay) + py * (bx - ax) < 0) - return -1; - return 0; - } - - private static float SegDist(PointF p, PointF a, PointF b) - { - float dx = b.X - a.X, dy = b.Y - a.Y; - float lenSq = dx * dx + dy * dy; - if (lenSq == 0f) return PtDist(p, a); - float t = Math.Max(0f, Math.Min(1f, - ((p.X - a.X) * dx + (p.Y - a.Y) * dy) / lenSq)); - return PtDist(p, new PointF(a.X + t * dx, a.Y + t * dy)); - } - - private static float PtDist(PointF a, PointF b) - { - float dx = a.X - b.X, dy = a.Y - b.Y; - return (float)Math.Sqrt(dx * dx + dy * dy); - } - - private static IEnumerable<(int, int)> Zip(List a, List b) - { - for (int i = 0; i < a.Count; i++) yield return (a[i], b[i]); - } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/HatchBrush.cs b/src/MiniPdf/Drawing/Drawing2D/HatchBrush.cs deleted file mode 100644 index fd753604..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/HatchBrush.cs +++ /dev/null @@ -1,59 +0,0 @@ -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Defines a rectangular, horizontal, vertical, or crosshatch brush. - /// - /// - /// A fills shapes with a hatching pattern defined by - /// , using a foreground and background color. - /// - public sealed class HatchBrush : Brush - { - /// - /// Initializes a new with the specified hatch style and foreground color. - /// The background color defaults to black. - /// - /// The hatch style enumeration specifying the pattern. - /// The foreground color. - public HatchBrush(HatchStyle hatchStyle, Color foreColor) - : this(hatchStyle, foreColor, Color.Black) { } - - /// - /// Initializes a new with the specified hatch style, foreground color, and background color. - /// - /// The hatch style enumeration specifying the pattern. - /// The foreground color. - /// The background color. - public HatchBrush(HatchStyle hatchStyle, Color foreColor, Color backColor) - { - HatchStyle = hatchStyle; - ForegroundColor = foreColor; - BackgroundColor = backColor; - } - - /// - /// Gets the hatch style of this brush. - /// - public HatchStyle HatchStyle { get; } - - /// - /// Gets the foreground color of this brush. - /// - public Color ForegroundColor { get; } - - /// - /// Gets the background color of this brush. - /// - public Color BackgroundColor { get; } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public override Brush Clone() - => new HatchBrush(HatchStyle, ForegroundColor, BackgroundColor); - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/HatchStyle.cs b/src/MiniPdf/Drawing/Drawing2D/HatchStyle.cs deleted file mode 100644 index bace7cab..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/HatchStyle.cs +++ /dev/null @@ -1,288 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the hatch style for fill patterns. - /// - public enum HatchStyle - { - /// - /// Horizontal hatch pattern. - /// - Horizontal = 0, - - /// - /// Vertical hatch pattern. - /// - Vertical = 1, - - /// - /// Forward diagonal hatch pattern (top-left to bottom-right). - /// - ForwardDiagonal = 2, - - /// - /// Backward diagonal hatch pattern (top-right to bottom-left). - /// - BackwardDiagonal = 3, - - /// - /// Cross hatch pattern. - /// - Cross = 4, - - /// - /// Large grid hatch pattern (alias for Cross). - /// - LargeGrid = 4, // alias - - /// - /// Diagonal cross hatch pattern. - /// - DiagonalCross = 5, - - /// - /// 5% hatch pattern. - /// - Percent05 = 6, - - /// - /// 10% hatch pattern. - /// - Percent10 = 7, - - /// - /// 20% hatch pattern. - /// - Percent20 = 8, - - /// - /// 25% hatch pattern. - /// - Percent25 = 9, - - /// - /// 30% hatch pattern. - /// - Percent30 = 10, - - /// - /// 40% hatch pattern. - /// - Percent40 = 11, - - /// - /// 50% hatch pattern. - /// - Percent50 = 12, - - /// - /// 60% hatch pattern. - /// - Percent60 = 13, - - /// - /// 70% hatch pattern. - /// - Percent70 = 14, - - /// - /// 75% hatch pattern. - /// - Percent75 = 15, - - /// - /// 80% hatch pattern. - /// - Percent80 = 16, - - /// - /// 90% hatch pattern. - /// - Percent90 = 17, - - /// - /// Light downward diagonal hatch pattern. - /// - LightDownwardDiagonal = 18, - - /// - /// Light upward diagonal hatch pattern. - /// - LightUpwardDiagonal = 19, - - /// - /// Dark downward diagonal hatch pattern. - /// - DarkDownwardDiagonal = 20, - - /// - /// Dark upward diagonal hatch pattern. - /// - DarkUpwardDiagonal = 21, - - /// - /// Wide downward diagonal hatch pattern. - /// - WideDownwardDiagonal = 22, - - /// - /// Wide upward diagonal hatch pattern. - /// - WideUpwardDiagonal = 23, - - /// - /// Light vertical hatch pattern. - /// - LightVertical = 24, - - /// - /// Light horizontal hatch pattern. - /// - LightHorizontal = 25, - - /// - /// Narrow vertical hatch pattern. - /// - NarrowVertical = 26, - - /// - /// Narrow horizontal hatch pattern. - /// - NarrowHorizontal = 27, - - /// - /// Dark vertical hatch pattern. - /// - DarkVertical = 28, - - /// - /// Dark horizontal hatch pattern. - /// - DarkHorizontal = 29, - - /// - /// Dashed downward diagonal hatch pattern. - /// - DashedDownwardDiagonal = 30, - - /// - /// Dashed upward diagonal hatch pattern. - /// - DashedUpwardDiagonal = 31, - - /// - /// Dashed horizontal hatch pattern. - /// - DashedHorizontal = 32, - - /// - /// Dashed vertical hatch pattern. - /// - DashedVertical = 33, - - /// - /// Small confetti hatch pattern. - /// - SmallConfetti = 34, - - /// - /// Large confetti hatch pattern. - /// - LargeConfetti = 35, - - /// - /// Zigzag hatch pattern. - /// - ZigZag = 36, - - /// - /// Wave hatch pattern. - /// - Wave = 37, - - /// - /// Diagonal brick hatch pattern. - /// - DiagonalBrick = 38, - - /// - /// Horizontal brick hatch pattern. - /// - HorizontalBrick = 39, - - /// - /// Weave hatch pattern. - /// - Weave = 40, - - /// - /// Plaid hatch pattern. - /// - Plaid = 41, - - /// - /// Divot hatch pattern. - /// - Divot = 42, - - /// - /// Dotted grid hatch pattern. - /// - DottedGrid = 43, - - /// - /// Dotted diamond hatch pattern. - /// - DottedDiamond = 44, - - /// - /// Shingle hatch pattern. - /// - Shingle = 45, - - /// - /// Trellis hatch pattern. - /// - Trellis = 46, - - /// - /// Sphere hatch pattern. - /// - Sphere = 47, - - /// - /// Small grid hatch pattern. - /// - SmallGrid = 48, - - /// - /// Small checkerboard hatch pattern. - /// - SmallCheckerBoard = 49, - - /// - /// Large checkerboard hatch pattern. - /// - LargeCheckerBoard = 50, - - /// - /// Outlined diamond hatch pattern. - /// - OutlinedDiamond = 51, - - /// - /// Solid diamond hatch pattern. - /// - SolidDiamond = 52, - - /// - /// Minimum hatch style value. - /// - Min = Horizontal, - - /// - /// Maximum hatch style value. - /// - Max = SolidDiamond, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/ImageAttributes.cs b/src/MiniPdf/Drawing/Drawing2D/ImageAttributes.cs deleted file mode 100644 index 6a0225c5..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/ImageAttributes.cs +++ /dev/null @@ -1,276 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies colour-adjustment information applied to pixels during image rendering. - /// Supports colour matrices, gamma correction, colour-key transparency and colour remapping. - /// - public sealed class ImageAttributes : IDisposable - { - // Per-type slots: Bitmap (type=1) takes priority over Default (type=0) - private ColorMatrix? _bitmapColorMatrix; - private ColorMatrix? _defaultColorMatrix; - private float _bitmapGamma = 1f; - private float _defaultGamma = 1f; - private bool _hasColorKey; - private Color _colorKeyLow; - private Color _colorKeyHigh; - private ColorMap[]? _remapTable; - private bool _noOp; - - // ── Color matrix ───────────────────────────────────────────────────── - - /// - /// Sets the colour matrix for the default colour adjustment category. - /// - /// The colour matrix to apply. - public void SetColorMatrix(ColorMatrix colorMatrix) - => SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); - - /// - /// Sets the colour matrix for the specified colour adjustment category. - /// - /// The colour matrix to apply. - /// The colour matrix flags that specify how the colour matrix is applied. - public void SetColorMatrix(ColorMatrix colorMatrix, ColorMatrixFlag flags) - => SetColorMatrix(colorMatrix, flags, ColorAdjustType.Default); - - /// - /// Sets the colour matrix for the specified colour adjustment category. - /// - /// The colour matrix to apply. - /// The colour matrix flags that specify how the colour matrix is applied. - /// The colour adjustment type that specifies the adjustment category. - public void SetColorMatrix(ColorMatrix colorMatrix, ColorMatrixFlag flags, ColorAdjustType type) - { - if (type == ColorAdjustType.Bitmap) - _bitmapColorMatrix = colorMatrix; - else - _defaultColorMatrix = colorMatrix; - } - - /// - /// Clears the colour matrix for the default colour adjustment category. - /// - public void ClearColorMatrix() - => ClearColorMatrix(ColorAdjustType.Default); - - /// - /// Clears the colour matrix for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void ClearColorMatrix(ColorAdjustType type) - { - if (type == ColorAdjustType.Bitmap) - _bitmapColorMatrix = null; - else - _defaultColorMatrix = null; - } - - // ── Gamma correction ────────────────────────────────────────────────── - - /// - /// Sets the gamma value for the default colour adjustment category. - /// - /// The gamma value. - public void SetGamma(float gamma) - => SetGamma(gamma, ColorAdjustType.Default); - - /// - /// Sets the gamma value for the specified colour adjustment category. - /// - /// The gamma value. - /// The colour adjustment type that specifies the adjustment category. - public void SetGamma(float gamma, ColorAdjustType type) - { - if (type == ColorAdjustType.Bitmap) - _bitmapGamma = gamma; - else - _defaultGamma = gamma; - } - - /// - /// Clears the gamma value for the default colour adjustment category. - /// - public void ClearGamma() - => ClearGamma(ColorAdjustType.Default); - - /// - /// Clears the gamma value for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void ClearGamma(ColorAdjustType type) - { - if (type == ColorAdjustType.Bitmap) _bitmapGamma = 1f; - else _defaultGamma = 1f; - } - - // ── Color key (transparency range) ──────────────────────────────────── - - /// - /// Sets the colour key for the default colour adjustment category. - /// - /// The low colour key value. - /// The high colour key value. - public void SetColorKey(Color colorLow, Color colorHigh) - => SetColorKey(colorLow, colorHigh, ColorAdjustType.Default); - - /// - /// Sets the colour key for the specified colour adjustment category. - /// - /// The low colour key value. - /// The high colour key value. - /// The colour adjustment type that specifies the adjustment category. - public void SetColorKey(Color colorLow, Color colorHigh, ColorAdjustType type) - { - _hasColorKey = true; - _colorKeyLow = colorLow; - _colorKeyHigh = colorHigh; - } - - /// - /// Clears the colour key for the default colour adjustment category. - /// - public void ClearColorKey() - => ClearColorKey(ColorAdjustType.Default); - - /// - /// Clears the colour key for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void ClearColorKey(ColorAdjustType type) - => _hasColorKey = false; - - // ── Remap table ─────────────────────────────────────────────────────── - - /// - /// Sets the colour remap table for the default colour adjustment category. - /// - /// The array of colour map entries that define the remap table. - public void SetRemapTable(ColorMap[] map) - => SetRemapTable(map, ColorAdjustType.Default); - - /// - /// Sets the colour remap table for the specified colour adjustment category. - /// - /// The array of colour map entries that define the remap table. - /// The colour adjustment type that specifies the adjustment category. - public void SetRemapTable(ColorMap[] map, ColorAdjustType type) - => _remapTable = map == null ? null : (ColorMap[])map.Clone(); - - /// - /// Clears the colour remap table for the default colour adjustment category. - /// - public void ClearRemapTable() - => ClearRemapTable(ColorAdjustType.Default); - - /// - /// Clears the colour remap table for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void ClearRemapTable(ColorAdjustType type) - => _remapTable = null; - - // ── No-op ───────────────────────────────────────────────────────────── - - /// - /// Sets the no-op flag for the default colour adjustment category. - /// - public void SetNoOp() => _noOp = true; - - /// - /// Sets the no-op flag for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void SetNoOp(ColorAdjustType type) => _noOp = true; - - /// - /// Clears the no-op flag for the specified colour adjustment category. - /// - /// The colour adjustment type that specifies the adjustment category. - public void ClearNoOp(ColorAdjustType type) => _noOp = false; - - // ── Clone / Dispose ─────────────────────────────────────────────────── - - /// - /// Creates an exact copy of this object. - /// - /// A new object that is a copy of this instance. - public ImageAttributes Clone() => new ImageAttributes - { - _bitmapColorMatrix = _bitmapColorMatrix, - _defaultColorMatrix = _defaultColorMatrix, - _bitmapGamma = _bitmapGamma, - _defaultGamma = _defaultGamma, - _hasColorKey = _hasColorKey, - _colorKeyLow = _colorKeyLow, - _colorKeyHigh = _colorKeyHigh, - _remapTable = _remapTable == null ? null : (ColorMap[])_remapTable.Clone(), - _noOp = _noOp, - }; - - /// - /// Releases all resources used by this . - /// - public void Dispose() { } - - // ── Internal per-pixel colour adjustment ────────────────────────────── - - internal Color ApplyToColor(Color c) - { - if (_noOp) return c; - - // 1. Remap table - if (_remapTable != null) - { - int argb = c.ToArgb(); - foreach (var entry in _remapTable) - if (entry.OldColor.ToArgb() == argb) { c = entry.NewColor; break; } - } - - // 2. Color key → fully transparent - if (_hasColorKey && - c.R >= _colorKeyLow.R && c.R <= _colorKeyHigh.R && - c.G >= _colorKeyLow.G && c.G <= _colorKeyHigh.G && - c.B >= _colorKeyLow.B && c.B <= _colorKeyHigh.B) - return Color.FromArgb(0, c.R, c.G, c.B); - - // 3. Color matrix (bitmap-specific slot wins over default) - ColorMatrix? matrix = _bitmapColorMatrix ?? _defaultColorMatrix; - if (matrix != null) - { - float r = c.R / 255f, g = c.G / 255f, b = c.B / 255f, a = c.A / 255f; - float nr = r * matrix[0, 0] + g * matrix[1, 0] + b * matrix[2, 0] + a * matrix[3, 0] + matrix[4, 0]; - float ng = r * matrix[0, 1] + g * matrix[1, 1] + b * matrix[2, 1] + a * matrix[3, 1] + matrix[4, 1]; - float nb = r * matrix[0, 2] + g * matrix[1, 2] + b * matrix[2, 2] + a * matrix[3, 2] + matrix[4, 2]; - float na = r * matrix[0, 3] + g * matrix[1, 3] + b * matrix[2, 3] + a * matrix[3, 3] + matrix[4, 3]; - c = Color.FromArgb(ClampByte(na * 255f), ClampByte(nr * 255f), ClampByte(ng * 255f), ClampByte(nb * 255f)); - } - - // 4. Gamma correction (apply inverse-gamma power) - float gamma = (_bitmapGamma != 1f) ? _bitmapGamma : _defaultGamma; - if (gamma != 1f && gamma > 0f) - { - float inv = 1f / gamma; - c = Color.FromArgb( - c.A, - (byte)(255f * (float)Math.Pow(c.R / 255.0, inv)), - (byte)(255f * (float)Math.Pow(c.G / 255.0, inv)), - (byte)(255f * (float)Math.Pow(c.B / 255.0, inv))); - } - - return c; - } - - private static byte ClampByte(float v) - { - if (v <= 0f) return 0; - if (v >= 255f) return 255; - return (byte)v; - } - } -} - diff --git a/src/MiniPdf/Drawing/Drawing2D/InterpolationMode.cs b/src/MiniPdf/Drawing/Drawing2D/InterpolationMode.cs deleted file mode 100644 index a5d41768..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/InterpolationMode.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the interpolation mode for scaling and rotating images. - /// - public enum InterpolationMode - { - /// - /// Invalid interpolation mode. - /// - Invalid = -1, - - /// - /// Default interpolation mode. - /// - Default = 0, - - /// - /// Low quality interpolation. - /// - Low = 1, - - /// - /// High quality interpolation. - /// - High = 2, - - /// - /// Bilinear interpolation. - /// - Bilinear = 3, - - /// - /// Bicubic interpolation. - /// - Bicubic = 4, - - /// - /// Nearest neighbor interpolation. - /// - NearestNeighbor = 5, - - /// - /// High quality bilinear interpolation. - /// - HighQualityBilinear = 6, - - /// - /// High quality bicubic interpolation. - /// - HighQualityBicubic = 7, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/LineCap.cs b/src/MiniPdf/Drawing/Drawing2D/LineCap.cs deleted file mode 100644 index bb54912b..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/LineCap.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the cap style for the start and end of lines drawn with a . - /// - public enum LineCap - { - /// - /// Flat line cap. - /// - Flat = 0, - - /// - /// Square line cap. - /// - Square = 1, - - /// - /// Round line cap. - /// - Round = 2, - - /// - /// Triangular line cap. - /// - Triangle = 3, - - /// - /// No anchor. - /// - NoAnchor = 16, - - /// - /// Square anchor. - /// - SquareAnchor = 17, - - /// - /// Round anchor. - /// - RoundAnchor = 18, - - /// - /// Diamond anchor. - /// - DiamondAnchor = 19, - - /// - /// Arrow anchor. - /// - ArrowAnchor = 20, - - /// - /// Anchor mask. - /// - AnchorMask = 240, - - /// - /// Custom line cap. - /// - Custom = 255, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/LineJoin.cs b/src/MiniPdf/Drawing/Drawing2D/LineJoin.cs deleted file mode 100644 index 200454cc..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/LineJoin.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the join style for the connection of line segments drawn with a . - /// - public enum LineJoin - { - /// - /// Miter join. - /// - Miter = 0, - - /// - /// Bevel join. - /// - Bevel = 1, - - /// - /// Round join. - /// - Round = 2, - - /// - /// Miter clipped join. - /// - MiterClipped = 3, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/LinearGradientBrush.cs b/src/MiniPdf/Drawing/Drawing2D/LinearGradientBrush.cs deleted file mode 100644 index 485b79a3..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/LinearGradientBrush.cs +++ /dev/null @@ -1,387 +0,0 @@ -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Geometry; -using System; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Defines a brush that blends two colors along a linear gradient. - /// - /// - /// A fills shapes with a gradient that transitions - /// linearly from a start point to an end point. The gradient can be customized with - /// and for non-linear interpolation. - /// - public sealed class LinearGradientBrush : Brush - { - private Color[] _colors; // always length 2 - private PointF _pt1; - private PointF _pt2; - private RectangleF _rectangle; - private WrapMode _wrapMode; - private bool _gammaCorrection; - private Blend? _blend; - private ColorBlend? _interpolationColors; - private Matrix _transform; - - // ----------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------- - - /// - /// Initializes a new with the specified start and end points and colors. - /// - /// The starting point of the gradient. - /// The ending point of the gradient. - /// The starting color. - /// The ending color. - public LinearGradientBrush(PointF pt1, PointF pt2, Color color1, Color color2) - { - _pt1 = pt1; - _pt2 = pt2; - _colors = new[] { color1, color2 }; - _rectangle = new RectangleF( - Math.Min(pt1.X, pt2.X), Math.Min(pt1.Y, pt2.Y), - Math.Abs(pt2.X - pt1.X), Math.Abs(pt2.Y - pt1.Y)); - _wrapMode = WrapMode.Tile; - _transform = new Matrix(); - } - - /// - /// Initializes a new with the specified start and end points and colors. - /// - /// The starting point of the gradient. - /// The ending point of the gradient. - /// The starting color. - /// The ending color. - public LinearGradientBrush(Point pt1, Point pt2, Color color1, Color color2) - : this(new PointF(pt1.X, pt1.Y), new PointF(pt2.X, pt2.Y), color1, color2) { } - - /// - /// Initializes a new with the specified rectangle and colors, using a gradient mode. - /// - /// The rectangle that defines the start and end points of the gradient. - /// The starting color. - /// The ending color. - /// The linear gradient mode specifying the direction. - public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode mode) - { - _colors = new[] { color1, color2 }; - _rectangle = rect; - _wrapMode = WrapMode.Tile; - _transform = new Matrix(); - ComputePointsFromMode(rect, mode); - } - - /// - /// Initializes a new with the specified rectangle and colors, using a gradient mode. - /// - /// The rectangle that defines the start and end points of the gradient. - /// The starting color. - /// The ending color. - /// The linear gradient mode specifying the direction. - public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode mode) - : this(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), color1, color2, mode) { } - - /// - /// Initializes a new with the specified rectangle, colors, and angle. - /// - /// The rectangle that defines the center of the gradient. - /// The starting color. - /// The ending color. - /// The angle of the gradient in degrees. - public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle) - : this(rect, color1, color2, angle, false) { } - - /// - /// Initializes a new with the specified rectangle, colors, angle, and scaleability. - /// - /// The rectangle that defines the center of the gradient. - /// The starting color. - /// The ending color. - /// The angle of the gradient in degrees. - /// If true, the angle scales with the shape. - public LinearGradientBrush(RectangleF rect, Color color1, Color color2, float angle, bool isAngleScaleable) - { - _colors = new[] { color1, color2 }; - _rectangle = rect; - _wrapMode = WrapMode.Tile; - _transform = new Matrix(); - ComputePointsFromAngle(rect, angle, isAngleScaleable); - } - - /// - /// Initializes a new with the specified rectangle, colors, angle, and scaleability. - /// - /// The rectangle that defines the center of the gradient. - /// The starting color. - /// The ending color. - /// The angle of the gradient in degrees. - /// If true, the angle scales with the shape. - public LinearGradientBrush(Rectangle rect, Color color1, Color color2, float angle, bool isAngleScaleable) - : this(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), color1, color2, angle, isAngleScaleable) { } - - // ----------------------------------------------------------------------- - // Properties - // ----------------------------------------------------------------------- - - /// - /// Gets or sets the starting and ending colors of the gradient. - /// - public Color[] LinearColors - { - get => new[] { _colors[0], _colors[1] }; - set - { - if (value == null || value.Length < 2) - throw new ArgumentException("LinearColors requires at least 2 colours.", nameof(value)); - _colors[0] = value[0]; - _colors[1] = value[1]; - } - } - - /// - /// Gets the rectangle that defines the bounds of this gradient brush. - /// - public RectangleF Rectangle => _rectangle; - - /// - /// Gets or sets the transformation matrix for this brush. - /// - public Matrix Transform - { - get => _transform; - set => _transform = value ?? new Matrix(); - } - - /// - /// Gets or sets the wrap mode for filling areas outside the gradient. - /// - public WrapMode WrapMode - { - get => _wrapMode; - set => _wrapMode = value; - } - - /// - /// Gets or sets whether gamma correction is enabled for the gradient. - /// - public bool GammaCorrection - { - get => _gammaCorrection; - set => _gammaCorrection = value; - } - - /// - /// Gets or sets the blend factors for custom gradient blending. - /// - public Blend? Blend - { - get => _blend; - set { _blend = value; if (value != null) _interpolationColors = null; } - } - - /// - /// Gets or sets the color blend for custom gradient interpolation. - /// - public ColorBlend InterpolationColors - { - get => _interpolationColors ?? DefaultColorBlend(); - set { _interpolationColors = value; _blend = null; } - } - - /// - /// Gets the starting point of the gradient. - /// - public PointF Point1 => _pt1; - - /// - /// Gets the ending point of the gradient. - /// - public PointF Point2 => _pt2; - - // ----------------------------------------------------------------------- - // Transform helpers - // ----------------------------------------------------------------------- - - /// - /// Resets the transformation matrix to the identity matrix. - /// - public void ResetTransform() => _transform.Reset(); - - /// - /// Multiplies the transformation matrix by the specified matrix. - /// - /// The matrix to multiply. - /// The order of multiplication (prepend or append). - public void MultiplyTransform(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) => _transform.Multiply(matrix, order); - - /// - /// Rotates the transformation matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) => _transform.Rotate(angle, order); - - /// - /// Scales the transformation matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) => _transform.Scale(sx, sy, order); - - /// - /// Translates the transformation matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) => _transform.Translate(dx, dy, order); - - // ----------------------------------------------------------------------- - // Blend shape helpers - // ----------------------------------------------------------------------- - - /// - /// Creates a triangular blend that emphasizes colors at the specified focus. - /// - /// The focus position (0.0 to 1.0). - /// The scale factor for the blend. - public void SetBlendTriangularShape(float focus, float scale = 1f) - { - // Creates a triangular blend: 0 → scale at focus → 0 - float mid = Math.Max(0f, Math.Min(1f, focus)); - _blend = new Blend(3) - { - Positions = new[] { 0f, mid, 1f }, - Factors = new[] { 0f, scale, 0f }, - }; - _interpolationColors = null; - } - - /// - /// Creates a bell-shaped blend that emphasizes colors at the specified focus. - /// - /// The focus position (0.0 to 1.0). - /// The scale factor for the blend. - public void SetSigmaBellShape(float focus, float scale = 1f) - { - // Creates a bell-curve blend approximated with 7 sample points - const int pts = 7; - float mid = Math.Max(0f, Math.Min(1f, focus)); - var positions = new float[pts]; - var factors = new float[pts]; - - for (int i = 0; i < pts; i++) - { - float t = i / (float)(pts - 1); - positions[i] = t; - // Gaussian-like curve centred at mid - float dist = (t - mid) * 4f; // scale so bell fits [0,1] - factors[i] = scale * (float)Math.Exp(-dist * dist); - } - _blend = new Blend(pts) { Positions = positions, Factors = factors }; - _interpolationColors = null; - } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public override Brush Clone() - { - var clone = new LinearGradientBrush(_pt1, _pt2, _colors[0], _colors[1]) - { - _rectangle = _rectangle, - _wrapMode = _wrapMode, - _gammaCorrection = _gammaCorrection, - }; - clone._transform = _transform.Clone(); - if (_blend != null) - { - clone._blend = new Blend(_blend.Positions.Length) - { - Positions = (float[])_blend.Positions.Clone(), - Factors = (float[])_blend.Factors.Clone(), - }; - } - if (_interpolationColors != null) - { - clone._interpolationColors = new ColorBlend(_interpolationColors.Positions.Length) - { - Positions = (float[])_interpolationColors.Positions.Clone(), - Colors = (Color[])_interpolationColors.Colors.Clone(), - }; - } - return clone; - } - - /// - /// Releases the unmanaged and optionally the managed resources used by this . - /// - /// If true, releases both managed and unmanaged resources; if false, releases only unmanaged resources. - protected override void Dispose(bool disposing) - { - if (disposing) - _transform.Dispose(); - base.Dispose(disposing); - } - - // ----------------------------------------------------------------------- - // Private helpers - // ----------------------------------------------------------------------- - - private void ComputePointsFromMode(RectangleF rect, LinearGradientMode mode) - { - switch (mode) - { - case LinearGradientMode.Horizontal: - _pt1 = new PointF(rect.Left, rect.Top); - _pt2 = new PointF(rect.Right, rect.Top); - break; - case LinearGradientMode.Vertical: - _pt1 = new PointF(rect.Left, rect.Top); - _pt2 = new PointF(rect.Left, rect.Bottom); - break; - case LinearGradientMode.ForwardDiagonal: - _pt1 = new PointF(rect.Left, rect.Top); - _pt2 = new PointF(rect.Right, rect.Bottom); - break; - default: // BackwardDiagonal - _pt1 = new PointF(rect.Right, rect.Top); - _pt2 = new PointF(rect.Left, rect.Bottom); - break; - } - } - - private void ComputePointsFromAngle(RectangleF rect, float angle, bool scaleAngle) - { - float effectiveAngle = angle; - if (scaleAngle && rect.Width != 0f && rect.Height != 0f) - { - double radians = angle * (Math.PI / 180.0); - effectiveAngle = (float)(Math.Atan2( - Math.Tan(radians) * rect.Height, - rect.Width) * (180.0 / Math.PI)); - } - - float cx = rect.X + rect.Width * 0.5f; - float cy = rect.Y + rect.Height * 0.5f; - double rad = effectiveAngle * (Math.PI / 180.0); - float cos = (float)Math.Cos(rad); - float sin = (float)Math.Sin(rad); - float halfLen = (Math.Abs(rect.Width * cos) + Math.Abs(rect.Height * sin)) * 0.5f; - - _pt1 = new PointF(cx - cos * halfLen, cy - sin * halfLen); - _pt2 = new PointF(cx + cos * halfLen, cy + sin * halfLen); - } - - private ColorBlend DefaultColorBlend() => new ColorBlend(2) - { - Colors = new[] { _colors[0], _colors[1] }, - Positions = new[] { 0f, 1f }, - }; - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/LinearGradientMode.cs b/src/MiniPdf/Drawing/Drawing2D/LinearGradientMode.cs deleted file mode 100644 index a6822b1a..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/LinearGradientMode.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the direction of a linear gradient. - /// - public enum LinearGradientMode - { - /// - /// Horizontal gradient. - /// - Horizontal = 0, - - /// - /// Vertical gradient. - /// - Vertical = 1, - - /// - /// Forward diagonal gradient (top-left to bottom-right). - /// - ForwardDiagonal = 2, - - /// - /// Backward diagonal gradient (top-right to bottom-left). - /// - BackwardDiagonal = 3, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/Matrix.cs b/src/MiniPdf/Drawing/Drawing2D/Matrix.cs deleted file mode 100644 index 951c8029..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/Matrix.cs +++ /dev/null @@ -1,312 +0,0 @@ -using MiniSoftware.Drawing.Geometry; -using System; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Represents a 2D affine transformation matrix. - /// Internal storage: [M11, M12, M21, M22, DX, DY] (GDI+ element order). - /// Row-vector transform: x' = x*M11 + y*M21 + DX, y' = x*M12 + y*M22 + DY. - /// - /// - /// A can be used to transform coordinates when drawing with . - /// It supports translation, scaling, rotation, and shearing operations. - /// - public sealed class Matrix : IDisposable - { - // Index: 0=M11, 1=M12, 2=M21, 3=M22, 4=DX, 5=DY - private float[] _elements; - - /// - /// Initializes a new as the identity matrix. - /// - public Matrix() - { - _elements = new float[] { 1f, 0f, 0f, 1f, 0f, 0f }; - } - - /// - /// Initializes a new with the specified elements. - /// - /// The element at row 1, column 1. - /// The element at row 1, column 2. - /// The element at row 2, column 1. - /// The element at row 2, column 2. - /// The horizontal translation component. - /// The vertical translation component. - public Matrix(float m11, float m12, float m21, float m22, float dx, float dy) - { - _elements = new float[] { m11, m12, m21, m22, dx, dy }; - } - - /// - /// Creates a matrix that maps to the parallelogram - /// defined by three destination points (top-left, top-right, bottom-left). - /// - public Matrix(RectangleF rect, PointF[] plgpts) - { - if (plgpts == null) throw new ArgumentNullException(nameof(plgpts)); - if (plgpts.Length != 3) throw new ArgumentException("plgpts must have exactly 3 points.", nameof(plgpts)); - - // Map rect corners (top-left→plgpts[0], top-right→plgpts[1], bottom-left→plgpts[2]) - float m11 = (plgpts[1].X - plgpts[0].X) / rect.Width; - float m12 = (plgpts[1].Y - plgpts[0].Y) / rect.Width; - float m21 = (plgpts[2].X - plgpts[0].X) / rect.Height; - float m22 = (plgpts[2].Y - plgpts[0].Y) / rect.Height; - float dx = plgpts[0].X - rect.X * m11 - rect.Y * m21; - float dy = plgpts[0].Y - rect.X * m12 - rect.Y * m22; - _elements = new float[] { m11, m12, m21, m22, dx, dy }; - } - - /// Returns a copy of the six elements [M11, M12, M21, M22, DX, DY]. - public float[] Elements => (float[])_elements.Clone(); - - /// - /// Gets the horizontal translation component of this matrix. - /// - public float OffsetX => _elements[4]; - - /// - /// Gets the vertical translation component of this matrix. - /// - public float OffsetY => _elements[5]; - - /// - /// Gets a value indicating whether this matrix is the identity matrix. - /// - public bool IsIdentity - => _elements[0] == 1f && _elements[1] == 0f - && _elements[2] == 0f && _elements[3] == 1f - && _elements[4] == 0f && _elements[5] == 0f; - - /// - /// Gets a value indicating whether this matrix is invertible. - /// - public bool IsInvertible - { - get - { - float det = _elements[0] * _elements[3] - _elements[1] * _elements[2]; - return det != 0f; - } - } - - /// - /// Resets this matrix to the identity matrix. - /// - public void Reset() - { - _elements[0] = 1f; _elements[1] = 0f; - _elements[2] = 0f; _elements[3] = 1f; - _elements[4] = 0f; _elements[5] = 0f; - } - - /// - /// Multiplies this matrix by in the specified order. - /// Prepend: result = matrix * this (matrix applied first to points). - /// Append: result = this * matrix (matrix applied after this to points). - /// - public void Multiply(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) - { - if (matrix == null) throw new ArgumentNullException(nameof(matrix)); - MultiplyDirect( - matrix._elements[0], matrix._elements[1], - matrix._elements[2], matrix._elements[3], - matrix._elements[4], matrix._elements[5], - order); - } - - /// - /// Rotates this matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void Rotate(float angle, MatrixOrder order = MatrixOrder.Prepend) - { - double rad = angle * (Math.PI / 180.0); - float cos = (float)Math.Cos(rad); - float sin = (float)Math.Sin(rad); - // Rotation matrix in GDI+ row-vector order: [cos, sin, -sin, cos, 0, 0] - MultiplyDirect(cos, sin, -sin, cos, 0f, 0f, order); - } - - /// - /// Rotates this matrix by the specified angle around the specified point. - /// - /// The angle of rotation in degrees. - /// The center point of rotation. - /// The order of multiplication (prepend or append). - public void RotateAt(float angle, PointF center, MatrixOrder order = MatrixOrder.Prepend) - { - if (order == MatrixOrder.Prepend) - { - Translate(center.X, center.Y, MatrixOrder.Prepend); - Rotate(angle, MatrixOrder.Prepend); - Translate(-center.X, -center.Y, MatrixOrder.Prepend); - } - else - { - Translate(-center.X, -center.Y, MatrixOrder.Append); - Rotate(angle, MatrixOrder.Append); - Translate(center.X, center.Y, MatrixOrder.Append); - } - } - - /// - /// Translates this matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void Translate(float offsetX, float offsetY, MatrixOrder order = MatrixOrder.Prepend) - { - MultiplyDirect(1f, 0f, 0f, 1f, offsetX, offsetY, order); - } - - /// - /// Scales this matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void Scale(float scaleX, float scaleY, MatrixOrder order = MatrixOrder.Prepend) - { - MultiplyDirect(scaleX, 0f, 0f, scaleY, 0f, 0f, order); - } - - /// - /// Shears this matrix by the specified factors. - /// - /// The horizontal shear factor. - /// The vertical shear factor. - /// The order of multiplication (prepend or append). - public void Shear(float shearX, float shearY, MatrixOrder order = MatrixOrder.Prepend) - { - MultiplyDirect(1f, shearY, shearX, 1f, 0f, 0f, order); - } - - /// - /// Inverts this matrix. - /// - /// Thrown when the matrix is not invertible. - public void Invert() - { - float det = _elements[0] * _elements[3] - _elements[1] * _elements[2]; - if (det == 0f) - throw new InvalidOperationException("Matrix is not invertible."); - float invDet = 1f / det; - float m11 = _elements[3] * invDet; - float m12 = -_elements[1] * invDet; - float m21 = -_elements[2] * invDet; - float m22 = _elements[0] * invDet; - float dx = (_elements[2] * _elements[5] - _elements[3] * _elements[4]) * invDet; - float dy = (_elements[1] * _elements[4] - _elements[0] * _elements[5]) * invDet; - _elements = new float[] { m11, m12, m21, m22, dx, dy }; - } - - /// - /// Transforms an array of points by this matrix. - /// - /// The array of points to transform. - public void TransformPoints(PointF[] pts) - { - if (pts == null) throw new ArgumentNullException(nameof(pts)); - float m11 = _elements[0], m12 = _elements[1]; - float m21 = _elements[2], m22 = _elements[3]; - float dx = _elements[4], dy = _elements[5]; - for (int i = 0; i < pts.Length; i++) - { - float x = pts[i].X, y = pts[i].Y; - pts[i] = new PointF(x * m11 + y * m21 + dx, x * m12 + y * m22 + dy); - } - } - - /// - /// Transforms an array of points by this matrix. - /// - /// The array of points to transform. - public void TransformPoints(Point[] pts) - { - if (pts == null) throw new ArgumentNullException(nameof(pts)); - float m11 = _elements[0], m12 = _elements[1]; - float m21 = _elements[2], m22 = _elements[3]; - float dx = _elements[4], dy = _elements[5]; - for (int i = 0; i < pts.Length; i++) - { - float x = pts[i].X, y = pts[i].Y; - pts[i] = new Point( - (int)Math.Round(x * m11 + y * m21 + dx), - (int)Math.Round(x * m12 + y * m22 + dy)); - } - } - - /// - /// Transforms an array of vectors by this matrix, ignoring the translation components. - /// - /// The array of vectors to transform. - public void TransformVectors(PointF[] pts) - { - if (pts == null) throw new ArgumentNullException(nameof(pts)); - float m11 = _elements[0], m12 = _elements[1]; - float m21 = _elements[2], m22 = _elements[3]; - for (int i = 0; i < pts.Length; i++) - { - float x = pts[i].X, y = pts[i].Y; - pts[i] = new PointF(x * m11 + y * m21, x * m12 + y * m22); - } - } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same elements. - public Matrix Clone() - => new Matrix(_elements[0], _elements[1], _elements[2], _elements[3], _elements[4], _elements[5]); - - /// - /// Releases all resources used by this . - /// - public void Dispose() { /* all managed */ } - - // ----------------------------------------------------------------------- - // Private helpers - // ----------------------------------------------------------------------- - - /// - /// Core multiply without allocating a temporary Matrix object. - /// b = the incoming operation matrix; a = this (current matrix). - /// Prepend: result = b * a (b applied first to points) - /// Append: result = a * b (b applied after a to points) - /// - private void MultiplyDirect( - float bm11, float bm12, float bm21, float bm22, float bdx, float bdy, - MatrixOrder order) - { - float[] a = _elements; - float r0, r1, r2, r3, r4, r5; - - if (order == MatrixOrder.Prepend) - { - // result = b * a - r0 = bm11 * a[0] + bm12 * a[2]; - r1 = bm11 * a[1] + bm12 * a[3]; - r2 = bm21 * a[0] + bm22 * a[2]; - r3 = bm21 * a[1] + bm22 * a[3]; - r4 = bdx * a[0] + bdy * a[2] + a[4]; - r5 = bdx * a[1] + bdy * a[3] + a[5]; - } - else - { - // result = a * b - r0 = a[0] * bm11 + a[1] * bm21; - r1 = a[0] * bm12 + a[1] * bm22; - r2 = a[2] * bm11 + a[3] * bm21; - r3 = a[2] * bm12 + a[3] * bm22; - r4 = a[4] * bm11 + a[5] * bm21 + bdx; - r5 = a[4] * bm12 + a[5] * bm22 + bdy; - } - - _elements = new float[] { r0, r1, r2, r3, r4, r5 }; - } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/MatrixOrder.cs b/src/MiniPdf/Drawing/Drawing2D/MatrixOrder.cs deleted file mode 100644 index 41464bc8..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/MatrixOrder.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the order for matrix operations. - /// - public enum MatrixOrder - { - /// - /// The new operation is applied before the existing transformation. - /// - Prepend = 0, - - /// - /// The new operation is applied after the existing transformation. - /// - Append = 1, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PathData.cs b/src/MiniPdf/Drawing/Drawing2D/PathData.cs deleted file mode 100644 index 6f63f763..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PathData.cs +++ /dev/null @@ -1,20 +0,0 @@ -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Contains the data needed to create or modify a . - /// - public sealed class PathData - { - /// - /// Gets or sets the array of points that define the path. - /// - public PointF[] Points { get; set; } = System.Array.Empty(); - - /// - /// Gets or sets the array of point types (PathPointType values) for the path. - /// - public byte[] Types { get; set; } = System.Array.Empty(); - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PathGradientBrush.cs b/src/MiniPdf/Drawing/Drawing2D/PathGradientBrush.cs deleted file mode 100644 index 03137847..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PathGradientBrush.cs +++ /dev/null @@ -1,293 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Encapsulates a Brush object that creates a gradient using the center point and - /// the vertices of the path defining the gradient shape. - /// - public sealed class PathGradientBrush : Brush - { - private PointF[] _pathPoints; - private PointF _centerPoint; - private Color _centerColor; - private Color[] _surroundColors; - private PointF _focusScales; - private Blend? _blend; - private ColorBlend? _interpolationColors; - private Matrix _transform; - private WrapMode _wrapMode; - - // ----------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------- - - /// - /// Initializes a new with the specified points. - /// - /// The array of points that define the gradient path. - public PathGradientBrush(PointF[] points) - : this(points, WrapMode.Clamp) { } - - /// - /// Initializes a new with the specified points and wrap mode. - /// - /// The array of points that define the gradient path. - /// The wrap mode that determines how the gradient is tiled. - public PathGradientBrush(PointF[] points, WrapMode wrapMode) - { - if (points == null) throw new ArgumentNullException(nameof(points)); - if (points.Length < 2) throw new ArgumentException("At least 2 points required.", nameof(points)); - - _pathPoints = (PointF[])points.Clone(); - _wrapMode = wrapMode; - _centerColor = Color.White; - _surroundColors = new[] { Color.Black }; - _focusScales = new PointF(0f, 0f); - _transform = new Matrix(); - _centerPoint = ComputeCentroid(points); - } - - /// - /// Initializes a new from the specified path. - /// - /// The path that defines the gradient shape. - public PathGradientBrush(GraphicsPath path) - : this(path?.PathPoints ?? throw new ArgumentNullException(nameof(path))) { } - - /// - /// Initializes a new from the specified path and wrap mode. - /// - /// The path that defines the gradient shape. - /// The wrap mode that determines how the gradient is tiled. - public PathGradientBrush(GraphicsPath path, WrapMode wrapMode) - : this(path?.PathPoints ?? throw new ArgumentNullException(nameof(path)), wrapMode) { } - - // ----------------------------------------------------------------------- - // Properties - // ----------------------------------------------------------------------- - - /// - /// Gets or sets the center color of the gradient. - /// - public Color CenterColor - { - get => _centerColor; - set => _centerColor = value; - } - - /// - /// Gets or sets the array of surround colors. - /// - public Color[] SurroundColors - { - get => (Color[])_surroundColors.Clone(); - set - { - if (value == null) throw new ArgumentNullException(nameof(value)); - _surroundColors = (Color[])value.Clone(); - } - } - - /// - /// Gets or sets the center point of the gradient. - /// - public PointF CenterPoint - { - get => _centerPoint; - set => _centerPoint = value; - } - - /// - /// Gets or sets the focus scales for the gradient. - /// - public PointF FocusScales - { - get => _focusScales; - set => _focusScales = value; - } - - /// - /// Gets the bounding rectangle of the gradient path. - /// - public RectangleF Rectangle - { - get - { - float minX = _pathPoints[0].X, maxX = _pathPoints[0].X; - float minY = _pathPoints[0].Y, maxY = _pathPoints[0].Y; - for (int i = 1; i < _pathPoints.Length; i++) - { - if (_pathPoints[i].X < minX) minX = _pathPoints[i].X; - if (_pathPoints[i].X > maxX) maxX = _pathPoints[i].X; - if (_pathPoints[i].Y < minY) minY = _pathPoints[i].Y; - if (_pathPoints[i].Y > maxY) maxY = _pathPoints[i].Y; - } - return new RectangleF(minX, minY, maxX - minX, maxY - minY); - } - } - - /// - /// Gets or sets the wrap mode for filling areas outside the gradient. - /// - public WrapMode WrapMode - { - get => _wrapMode; - set => _wrapMode = value; - } - - /// - /// Gets or sets the transformation matrix for the brush. - /// - public Matrix Transform - { - get => _transform; - set => _transform = value ?? throw new ArgumentNullException(nameof(value)); - } - - /// - /// Gets or sets the blend factors for custom gradient blending. - /// - public Blend? Blend - { - get => _blend; - set => _blend = value; - } - - /// - /// Gets or sets the color blend for custom gradient interpolation. - /// - public ColorBlend? InterpolationColors - { - get => _interpolationColors; - set => _interpolationColors = value; - } - - // ----------------------------------------------------------------------- - // Transform helpers - // ----------------------------------------------------------------------- - - /// - /// Resets the transformation matrix to the identity matrix. - /// - public void ResetTransform() => _transform.Reset(); - - /// - /// Multiplies the transformation matrix by the specified matrix. - /// - /// The matrix to multiply. - /// The order of multiplication (prepend or append). - public void MultiplyTransform(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Multiply(matrix, order); - - /// - /// Rotates the transformation matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Rotate(angle, order); - - /// - /// Scales the transformation matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Scale(sx, sy, order); - - /// - /// Translates the transformation matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Translate(dx, dy, order); - - // ----------------------------------------------------------------------- - // Blend shape helpers - // ----------------------------------------------------------------------- - - /// - /// Creates a triangular blend that emphasizes colors at the specified focus. - /// - /// The focus position (0.0 to 1.0). - /// The scale factor for the blend. - public void SetBlendTriangularShape(float focus, float scale = 1.0f) - { - if (focus < 0f || focus > 1f) throw new ArgumentOutOfRangeException(nameof(focus)); - if (scale < 0f || scale > 1f) throw new ArgumentOutOfRangeException(nameof(scale)); - var b = new Blend(); - b.Positions = new[] { 0f, focus, 1f }; - b.Factors = new[] { 0f, scale, 0f }; - _blend = b; - } - - /// - /// Creates a bell-shaped blend centered at the specified focus. - /// - /// The focus position (0.0 to 1.0). - /// The scale factor for the blend. - public void SetSigmaBellShape(float focus, float scale = 1.0f) - { - if (focus < 0f || focus > 1f) throw new ArgumentOutOfRangeException(nameof(focus)); - if (scale < 0f || scale > 1f) throw new ArgumentOutOfRangeException(nameof(scale)); - const int steps = 64; - var pos = new float[steps + 1]; - var factors = new float[steps + 1]; - for (int i = 0; i <= steps; i++) - { - float t = (float)i / steps; - pos[i] = t; - double u = (t - focus) * 6.0; - factors[i] = (float)(scale * (1.0 / (1.0 + Math.Exp(-u)))); - } - _blend = new Blend { Positions = pos, Factors = factors }; - } - - // ----------------------------------------------------------------------- - // Clone / Dispose - // ----------------------------------------------------------------------- - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public override Brush Clone() - { - var c = new PathGradientBrush((PointF[])_pathPoints.Clone(), _wrapMode) - { - CenterColor = _centerColor, - CenterPoint = _centerPoint, - FocusScales = _focusScales, - _transform = (Matrix)_transform.Clone(), - }; - c._surroundColors = (Color[])_surroundColors.Clone(); - c._blend = _blend; - c._interpolationColors = _interpolationColors; - return c; - } - - /// - /// Releases the unmanaged resources used by the . - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected override void Dispose(bool disposing) { } - - // ----------------------------------------------------------------------- - // Helpers - // ----------------------------------------------------------------------- - - private static PointF ComputeCentroid(PointF[] pts) - { - float cx = 0f, cy = 0f; - foreach (var p in pts) { cx += p.X; cy += p.Y; } - return new PointF(cx / pts.Length, cy / pts.Length); - } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PathPointType.cs b/src/MiniPdf/Drawing/Drawing2D/PathPointType.cs deleted file mode 100644 index 4de40f6f..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PathPointType.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the type of a path point. Upper bits carry flags; lower 3 bits are the point type. - /// - [Flags] - public enum PathPointType : byte - { - /// - /// Indicates the start of a new figure. - /// - Start = 0, - - /// - /// Indicates a line segment. - /// - Line = 1, - - /// - /// Indicates a Bézier curve segment with one control point. - /// - Bezier = 3, - - /// - /// Indicates a Bézier curve segment with two control points. - /// - Bezier3 = 3, - - /// - /// A mask that isolates the point type from the flags. - /// - PathTypeMask = 0x07, - - /// - /// Indicates that the point is a dash mode marker. - /// - DashMode = 0x10, - - /// - /// Indicates that the point is a path marker. - /// - PathMarker = 0x20, - - /// - /// Indicates that the figure should be closed. - /// - CloseSubpath = 0x80, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PenAlignment.cs b/src/MiniPdf/Drawing/Drawing2D/PenAlignment.cs deleted file mode 100644 index 2c6d49ab..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PenAlignment.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the alignment of a relative to the stroke outline. - /// - public enum PenAlignment - { - /// - /// The pen stroke is centered on the outline. - /// - Center = 0, - - /// - /// The pen stroke is inset from the outline. - /// - Inset = 1, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PenType.cs b/src/MiniPdf/Drawing/Drawing2D/PenType.cs deleted file mode 100644 index dffb0720..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PenType.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the type of a fill. - /// - public enum PenType - { - /// - /// Solid color pen. - /// - SolidColor = 0, - - /// - /// Hatch fill pen. - /// - HatchFill = 1, - - /// - /// Texture fill pen. - /// - TextureFill = 2, - - /// - /// Path gradient pen. - /// - PathGradient = 3, - - /// - /// Linear gradient pen. - /// - LinearGradient = 4, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/PixelOffsetMode.cs b/src/MiniPdf/Drawing/Drawing2D/PixelOffsetMode.cs deleted file mode 100644 index 5abb8383..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/PixelOffsetMode.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the pixel offset mode for rendering. - /// - public enum PixelOffsetMode - { - /// - /// Invalid pixel offset mode. - /// - Invalid = -1, - - /// - /// Default pixel offset mode. - /// - Default = 0, - - /// - /// High speed pixel offset mode. - /// - HighSpeed = 1, - - /// - /// High quality pixel offset mode. - /// - HighQuality = 2, - - /// - /// No pixel offset. - /// - None = 3, - - /// - /// Half-pixel offset for improved quality. - /// - Half = 4, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/Region.cs b/src/MiniPdf/Drawing/Drawing2D/Region.cs deleted file mode 100644 index cbc627fc..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/Region.cs +++ /dev/null @@ -1,561 +0,0 @@ -using MiniSoftware.Drawing.Geometry; -using System; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Describes the interior of a graphics shape composed of rectangles, paths, - /// and set operations (union, intersection, exclusion, complement, xor). - /// - /// - /// A can be used to clip drawing operations to a specific area. - /// Regions support boolean operations like Union, Intersect, Exclude, Complement, and Xor. - /// - public sealed class Region : IDisposable - { - // The root node of the CSG tree. - private RegionNode _root; - - // ----------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------- - - /// Creates an infinite region. - public Region() { _root = InfiniteRegionNode.Instance; } - - /// Creates a region from a rectangle. - public Region(RectangleF rect) { _root = new LeafRectNode(rect); } - - /// Creates a region from a rectangle. - public Region(Rectangle rect) - : this(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)) { } - - /// Creates a region that has the same interior as a path. - public Region(GraphicsPath path) - { - if (path == null) throw new ArgumentNullException(nameof(path)); - _root = new LeafPathNode(path.Clone()); - } - - /// Initialises a Region from serialized data. - public Region(RegionData rgnData) - { - if (rgnData == null) throw new ArgumentNullException(nameof(rgnData)); - using (var ms = new MemoryStream(rgnData.Data)) - using (var br = new BinaryReader(ms)) - _root = RegionNodeSerializer.Read(br); - } - - // ----------------------------------------------------------------------- - // Set operations - // ----------------------------------------------------------------------- - - /// - /// Updates this region to the union of itself and the specified region. - /// - /// The region to union with. - public void Union(Region region) - { - if (region == null) throw new ArgumentNullException(nameof(region)); - _root = new OpRegionNode(_root, region._root.DeepClone(), SetOp.Union); - } - - /// - /// Updates this region to the union of itself and the specified rectangle. - /// - /// The rectangle to union with. - public void Union(RectangleF rect) => Union(new Region(rect)); - - /// - /// Updates this region to the union of itself and the specified rectangle. - /// - /// The rectangle to union with. - public void Union(Rectangle rect) => Union(new Region(rect)); - - /// - /// Updates this region to the union of itself and the specified path. - /// - /// The path to union with. - public void Union(GraphicsPath path) => Union(new Region(path)); - - /// - /// Updates this region to the intersection of itself and the specified region. - /// - /// The region to intersect with. - public void Intersect(Region region) - { - if (region == null) throw new ArgumentNullException(nameof(region)); - _root = new OpRegionNode(_root, region._root.DeepClone(), SetOp.Intersect); - } - - /// - /// Updates this region to the intersection of itself and the specified rectangle. - /// - /// The rectangle to intersect with. - public void Intersect(RectangleF rect) => Intersect(new Region(rect)); - - /// - /// Updates this region to the intersection of itself and the specified rectangle. - /// - /// The rectangle to intersect with. - public void Intersect(Rectangle rect) => Intersect(new Region(rect)); - - /// - /// Updates this region to the intersection of itself and the specified path. - /// - /// The path to intersect with. - public void Intersect(GraphicsPath path) => Intersect(new Region(path)); - - /// - /// Updates this region to the exclusion of the specified region. - /// - /// The region to exclude. - public void Exclude(Region region) - { - if (region == null) throw new ArgumentNullException(nameof(region)); - _root = new OpRegionNode(_root, region._root.DeepClone(), SetOp.Exclude); - } - - /// - /// Updates this region to the exclusion of the specified rectangle. - /// - /// The rectangle to exclude. - public void Exclude(RectangleF rect) => Exclude(new Region(rect)); - - /// - /// Updates this region to the exclusion of the specified rectangle. - /// - /// The rectangle to exclude. - public void Exclude(Rectangle rect) => Exclude(new Region(rect)); - - /// - /// Updates this region to the exclusion of the specified path. - /// - /// The path to exclude. - public void Exclude(GraphicsPath path) => Exclude(new Region(path)); - - /// - /// Updates this region to the complement of itself relative to the specified region. - /// - /// The region to use for the complement operation. - public void Complement(Region region) - { - if (region == null) throw new ArgumentNullException(nameof(region)); - _root = new OpRegionNode(_root, region._root.DeepClone(), SetOp.Complement); - } - - /// - /// Updates this region to the complement of itself relative to the specified rectangle. - /// - /// The rectangle to use for the complement operation. - public void Complement(RectangleF rect) => Complement(new Region(rect)); - - /// - /// Updates this region to the complement of itself relative to the specified rectangle. - /// - /// The rectangle to use for the complement operation. - public void Complement(Rectangle rect) => Complement(new Region(rect)); - - /// - /// Updates this region to the complement of itself relative to the specified path. - /// - /// The path to use for the complement operation. - public void Complement(GraphicsPath path) => Complement(new Region(path)); - - /// - /// Updates this region to the exclusive OR of itself and the specified region. - /// - /// The region to XOR with. - public void Xor(Region region) - { - if (region == null) throw new ArgumentNullException(nameof(region)); - _root = new OpRegionNode(_root, region._root.DeepClone(), SetOp.Xor); - } - - /// - /// Updates this region to the exclusive OR of itself and the specified rectangle. - /// - /// The rectangle to XOR with. - public void Xor(RectangleF rect) => Xor(new Region(rect)); - - /// - /// Updates this region to the exclusive OR of itself and the specified rectangle. - /// - /// The rectangle to XOR with. - public void Xor(Rectangle rect) => Xor(new Region(rect)); - - /// - /// Updates this region to the exclusive OR of itself and the specified path. - /// - /// The path to XOR with. - public void Xor(GraphicsPath path) => Xor(new Region(path)); - - // ----------------------------------------------------------------------- - // State mutators - // ----------------------------------------------------------------------- - - /// Makes this region empty (contains no points). - public void MakeEmpty() => _root = EmptyRegionNode.Instance; - - /// Makes this region infinite (contains all points). - public void MakeInfinite() => _root = InfiniteRegionNode.Instance; - - // ----------------------------------------------------------------------- - // Transformation - // ----------------------------------------------------------------------- - - /// - /// Translates this region by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - public void Translate(float dx, float dy) => _root.Translate(dx, dy); - - /// - /// Translates this region by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - public void Translate(int dx, int dy) => Translate((float)dx, (float)dy); - - /// - /// Transforms this region by the specified matrix. - /// - /// The transformation matrix. - public void Transform(Matrix matrix) - { - if (matrix == null) throw new ArgumentNullException(nameof(matrix)); - _root.ApplyTransform(matrix); - } - - // ----------------------------------------------------------------------- - // Visibility tests - // ----------------------------------------------------------------------- - - /// - /// Gets a value indicating whether this region is empty. - /// - /// The graphics context (optional). - /// true if the region is empty; otherwise, false. - public bool IsEmpty(Graphics? g = null) => IsEmptyInternal(); - - /// - /// Gets a value indicating whether this region is infinite. - /// - /// The graphics context (optional). - /// true if the region is infinite; otherwise, false. - public bool IsInfinite(Graphics? g = null) => _root is InfiniteRegionNode; - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The X coordinate of the point. - /// The Y coordinate of the point. - /// true if the point is visible; otherwise, false. - public bool IsVisible(float x, float y) => _root.IsPointInside(x, y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The X coordinate of the point. - /// The Y coordinate of the point. - /// The graphics context (optional). - /// true if the point is visible; otherwise, false. - public bool IsVisible(float x, float y, Graphics? g) => _root.IsPointInside(x, y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The point to test. - /// true if the point is visible; otherwise, false. - public bool IsVisible(PointF pt) => _root.IsPointInside(pt.X, pt.Y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The point to test. - /// The graphics context (optional). - /// true if the point is visible; otherwise, false. - public bool IsVisible(PointF pt, Graphics? g) => _root.IsPointInside(pt.X, pt.Y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The point to test. - /// true if the point is visible; otherwise, false. - public bool IsVisible(Point pt) => _root.IsPointInside(pt.X, pt.Y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The point to test. - /// The graphics context (optional). - /// true if the point is visible; otherwise, false. - public bool IsVisible(Point pt, Graphics? g) => _root.IsPointInside(pt.X, pt.Y); - - /// - /// Determines whether the specified point is visible within this region. - /// - /// The X coordinate of the point. - /// The Y coordinate of the point. - /// The graphics context (optional). - /// true if the point is visible; otherwise, false. - public bool IsVisible(int x, int y, Graphics? g) => _root.IsPointInside(x, y); - - /// - /// Returns true if any part of lies within this region. - /// - public bool IsVisible(RectangleF rect, Graphics? g = null) - { - if (rect.IsEmpty) return false; - // Check 9 sample points: 4 corners, 4 edge midpoints, centre - float mx = rect.X + rect.Width * 0.5f; - float my = rect.Y + rect.Height * 0.5f; - return IsVisible(rect.X, rect.Y) || IsVisible(rect.Right, rect.Y) - || IsVisible(rect.Right, rect.Bottom) || IsVisible(rect.X, rect.Bottom) - || IsVisible(mx, rect.Y) || IsVisible(rect.Right, my) - || IsVisible(mx, rect.Bottom) || IsVisible(rect.X, my) - || IsVisible(mx, my); - } - - /// - /// Returns true if any part of lies within this region. - /// - /// The rectangle to test. - /// The graphics context (optional). - /// true if any part of the rectangle is visible; otherwise, false. - public bool IsVisible(Rectangle rect, Graphics? g = null) - => IsVisible(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), g); - - // ----------------------------------------------------------------------- - // Geometry - // ----------------------------------------------------------------------- - - /// Gets the bounding rectangle of this region. - public RectangleF GetBounds(Graphics? g = null) => _root.GetBounds(); - - // ----------------------------------------------------------------------- - // Serialization - // ----------------------------------------------------------------------- - - /// - /// Returns a object that represents the information - /// stored in this . - /// - public RegionData GetRegionData() - { - using (var ms = new MemoryStream()) - using (var bw = new BinaryWriter(ms)) - { - _root.WriteTo(bw); - bw.Flush(); - return new RegionData(ms.ToArray()); - } - } - - // ----------------------------------------------------------------------- - // GetRegionScans - // ----------------------------------------------------------------------- - - /// - /// Returns an array of RectangleF that approximate the region as a set of - /// horizontal scan bands. The returned rectangles are transformed by - /// (pass new Matrix() for identity). - /// - public RectangleF[] GetRegionScans(Matrix matrix) - { - if (matrix == null) throw new ArgumentNullException(nameof(matrix)); - - // Fast path: single rect leaf - if (_root is LeafRectNode rectLeaf) - { - var r = rectLeaf.Rect; - if (r.IsEmpty) return Array.Empty(); - return new[] { ApplyMatrix(matrix, r) }; - } - - if (_root is EmptyRegionNode) - return Array.Empty(); - - if (_root is InfiniteRegionNode) - { - // Return a large bounding rect (max 1e6 × 1e6) - var big = new RectangleF(-1e6f, -1e6f, 2e6f, 2e6f); - return new[] { ApplyMatrix(matrix, big) }; - } - - // General case: scanline sampling - var bounds = _root.GetBounds(); - if (bounds.IsEmpty) return Array.Empty(); - - // Clamp infinite/huge bounds - const float maxCoord = 1e6f; - float x0 = Math.Max(bounds.X, -maxCoord); - float y0 = Math.Max(bounds.Y, -maxCoord); - float x1 = Math.Min(bounds.Right, maxCoord); - float y1 = Math.Min(bounds.Bottom, maxCoord); - - float scanH = 1.0f; // 1 unit scanline height - int xSamples = 512; - float xStep = (x1 - x0) / xSamples; - if (xStep <= 0f) return Array.Empty(); - - var scans = new List(); - float yEnd = (float)Math.Ceiling((y1 - y0) / scanH) * scanH + y0; - - for (float y = y0; y < yEnd; y += scanH) - { - float yMid = y + scanH * 0.5f; - bool inSpan = false; - float spanStartX = 0f; - - for (int i = 0; i <= xSamples; i++) - { - float x = x0 + i * xStep; - bool vis = _root.IsPointInside(x, yMid); - - if (!inSpan && vis) - { - inSpan = true; - spanStartX = x; - } - else if (inSpan && !vis) - { - scans.Add(new RectangleF(spanStartX, y, x - spanStartX, scanH)); - inSpan = false; - } - } - if (inSpan) - scans.Add(new RectangleF(spanStartX, y, x1 - spanStartX, scanH)); - } - - // Apply matrix - if (!matrix.IsIdentity) - { - for (int i = 0; i < scans.Count; i++) - scans[i] = ApplyMatrix(matrix, scans[i]); - } - - return scans.ToArray(); - } - - // ----------------------------------------------------------------------- - // Clone / Equals - // ----------------------------------------------------------------------- - - /// - /// Creates an exact copy of this . - /// - /// A new that is a copy of this instance. - public Region Clone() - { - var c = new Region(); - c._root = _root.DeepClone(); - return c; - } - - /// - /// Tests whether this region has the same interior as . - /// Uses point-sampling since full rasterization requires Graphics (Batch 7). - /// - public bool Equals(Region region, Graphics? g = null) - { - if (region == null) return false; - if (ReferenceEquals(this, region)) return true; - - // Fast structural shortcut for trivial nodes - if (_root is EmptyRegionNode && region._root is EmptyRegionNode) return true; - if (_root is InfiniteRegionNode && region._root is InfiniteRegionNode) return true; - - // Sample a grid of points within the union of both bounds - var b1 = GetBounds(); - var b2 = region.GetBounds(); - var combined = RectangleF.Union(b1, b2); - if (combined.IsEmpty) return true; - - const int steps = 20; - float wStep = combined.Width / steps; - float hStep = combined.Height / steps; - if (wStep <= 0f) wStep = 1f; - if (hStep <= 0f) hStep = 1f; - - for (int iy = 0; iy <= steps; iy++) - for (int ix = 0; ix <= steps; ix++) - { - float x = combined.X + ix * wStep; - float y = combined.Y + iy * hStep; - if (_root.IsPointInside(x, y) != region._root.IsPointInside(x, y)) - return false; - } - return true; - } - - // ----------------------------------------------------------------------- - // IDisposable - // ----------------------------------------------------------------------- - - private bool _disposed; - - /// - /// Releases all resources used by this . - /// - public void Dispose() - { - if (_disposed) return; - _disposed = true; - // Walk the tree and dispose any path leaves - DisposeNode(_root); - } - - // ----------------------------------------------------------------------- - // Private helpers - // ----------------------------------------------------------------------- - - private bool IsEmptyInternal() - { - if (_root is EmptyRegionNode) return true; - if (_root is InfiniteRegionNode) return false; - var b = _root.GetBounds(); - if (b.IsEmpty) return true; - // Quick centre sample - float cx = b.X + b.Width * 0.5f; - float cy = b.Y + b.Height * 0.5f; - return !_root.IsPointInside(cx, cy); - } - - private static RectangleF ApplyMatrix(Matrix matrix, RectangleF r) - { - if (matrix.IsIdentity) return r; - var pts = new PointF[] - { - new PointF(r.X, r.Y), - new PointF(r.Right, r.Y), - new PointF(r.Right, r.Bottom), - new PointF(r.X, r.Bottom), - }; - matrix.TransformPoints(pts); - float minX = pts[0].X, maxX = pts[0].X; - float minY = pts[0].Y, maxY = pts[0].Y; - for (int i = 1; i < pts.Length; i++) - { - if (pts[i].X < minX) minX = pts[i].X; - if (pts[i].X > maxX) maxX = pts[i].X; - if (pts[i].Y < minY) minY = pts[i].Y; - if (pts[i].Y > maxY) maxY = pts[i].Y; - } - return new RectangleF(minX, minY, maxX - minX, maxY - minY); - } - - private static void DisposeNode(RegionNode node) - { - if (node is LeafPathNode p) { p.Path.Dispose(); return; } - if (node is OpRegionNode op) - { - DisposeNode(op.Left); - DisposeNode(op.Right); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/RegionData.cs b/src/MiniPdf/Drawing/Drawing2D/RegionData.cs deleted file mode 100644 index 1bf658ee..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/RegionData.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Encapsulates the data that describes a Region. - /// - public sealed class RegionData - { - /// The raw binary data for this region. - public byte[] Data { get; set; } - - internal RegionData(byte[] data) { Data = data; } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/RegionNode.cs b/src/MiniPdf/Drawing/Drawing2D/RegionNode.cs deleted file mode 100644 index 08bd2cba..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/RegionNode.cs +++ /dev/null @@ -1,292 +0,0 @@ -using MiniSoftware.Drawing.Geometry; -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Drawing2D -{ - // ------------------------------------------------------------------------- - // Set operation codes (mirrors CombineMode for internal use) - // ------------------------------------------------------------------------- - internal enum SetOp : byte - { - Union = 0, - Intersect = 1, - Exclude = 2, - Complement = 3, - Xor = 4, - } - - // ------------------------------------------------------------------------- - // Node type tags used in binary serialization - // ------------------------------------------------------------------------- - internal enum NodeTag : byte - { - Empty = 0, - Infinite = 1, - Rect = 2, - Path = 3, - Op = 4, - } - - // ------------------------------------------------------------------------- - // Abstract base - // ------------------------------------------------------------------------- - internal abstract class RegionNode - { - internal abstract bool IsPointInside(float x, float y); - internal abstract RectangleF GetBounds(); - internal abstract RegionNode DeepClone(); - internal abstract void Translate(float dx, float dy); - internal abstract void ApplyTransform(Matrix matrix); - internal abstract void WriteTo(BinaryWriter w); - } - - // ------------------------------------------------------------------------- - // Empty node – no pixels - // ------------------------------------------------------------------------- - internal sealed class EmptyRegionNode : RegionNode - { - internal static readonly EmptyRegionNode Instance = new EmptyRegionNode(); - - internal override bool IsPointInside(float x, float y) => false; - internal override RectangleF GetBounds() => RectangleF.Empty; - internal override RegionNode DeepClone() => Instance; - internal override void Translate(float dx, float dy) { } - internal override void ApplyTransform(Matrix matrix) { } - internal override void WriteTo(BinaryWriter w) => w.Write((byte)NodeTag.Empty); - } - - // ------------------------------------------------------------------------- - // Infinite node – all pixels - // ------------------------------------------------------------------------- - internal sealed class InfiniteRegionNode : RegionNode - { - internal static readonly InfiniteRegionNode Instance = new InfiniteRegionNode(); - - // Represent infinity as a very large rectangle for bounds purposes - private static readonly RectangleF InfiniteBounds = - new RectangleF(-1e9f, -1e9f, 2e9f, 2e9f); - - internal override bool IsPointInside(float x, float y) => true; - internal override RectangleF GetBounds() => InfiniteBounds; - internal override RegionNode DeepClone() => Instance; - internal override void Translate(float dx, float dy) { } - internal override void ApplyTransform(Matrix matrix) { } - internal override void WriteTo(BinaryWriter w) => w.Write((byte)NodeTag.Infinite); - } - - // ------------------------------------------------------------------------- - // Rectangle leaf - // ------------------------------------------------------------------------- - internal sealed class LeafRectNode : RegionNode - { - internal RectangleF Rect; - - internal LeafRectNode(RectangleF rect) { Rect = rect; } - - internal override bool IsPointInside(float x, float y) - => Rect.Contains(x, y); - - internal override RectangleF GetBounds() - => Rect; - - internal override RegionNode DeepClone() - => new LeafRectNode(Rect); - - internal override void Translate(float dx, float dy) - => Rect = new RectangleF(Rect.X + dx, Rect.Y + dy, Rect.Width, Rect.Height); - - internal override void ApplyTransform(Matrix matrix) - { - // Transform the four corners, then compute the axis-aligned bounding box. - var pts = new PointF[] - { - new PointF(Rect.X, Rect.Y), - new PointF(Rect.Right, Rect.Y), - new PointF(Rect.Right, Rect.Bottom), - new PointF(Rect.X, Rect.Bottom), - }; - matrix.TransformPoints(pts); - float minX = pts[0].X, maxX = pts[0].X; - float minY = pts[0].Y, maxY = pts[0].Y; - for (int i = 1; i < pts.Length; i++) - { - if (pts[i].X < minX) minX = pts[i].X; - if (pts[i].X > maxX) maxX = pts[i].X; - if (pts[i].Y < minY) minY = pts[i].Y; - if (pts[i].Y > maxY) maxY = pts[i].Y; - } - Rect = new RectangleF(minX, minY, maxX - minX, maxY - minY); - } - - internal override void WriteTo(BinaryWriter w) - { - w.Write((byte)NodeTag.Rect); - w.Write(Rect.X); - w.Write(Rect.Y); - w.Write(Rect.Width); - w.Write(Rect.Height); - } - } - - // ------------------------------------------------------------------------- - // Path leaf - // ------------------------------------------------------------------------- - internal sealed class LeafPathNode : RegionNode - { - internal GraphicsPath Path; - - internal LeafPathNode(GraphicsPath path) { Path = path; } - - internal override bool IsPointInside(float x, float y) - => Path.IsVisible(x, y); - - internal override RectangleF GetBounds() - => Path.GetBounds(); - - internal override RegionNode DeepClone() - => new LeafPathNode(Path.Clone()); - - internal override void Translate(float dx, float dy) - { - using (var m = new Matrix(1, 0, 0, 1, dx, dy)) - Path.Transform(m); - } - - internal override void ApplyTransform(Matrix matrix) - => Path.Transform(matrix); - - internal override void WriteTo(BinaryWriter w) - { - w.Write((byte)NodeTag.Path); - var pts = Path.PathPoints; - var types = Path.PathTypes; - int n = pts.Length; - w.Write(n); - for (int i = 0; i < n; i++) { w.Write(pts[i].X); w.Write(pts[i].Y); } - for (int i = 0; i < n; i++) w.Write(types[i]); - } - } - - // ------------------------------------------------------------------------- - // CSG operation node - // ------------------------------------------------------------------------- - internal sealed class OpRegionNode : RegionNode - { - internal RegionNode Left, Right; - internal SetOp Op; - - internal OpRegionNode(RegionNode left, RegionNode right, SetOp op) - { - Left = left; - Right = right; - Op = op; - } - - internal override bool IsPointInside(float x, float y) - { - bool l = Left.IsPointInside(x, y); - bool r = Right.IsPointInside(x, y); - switch (Op) - { - case SetOp.Union: return l | r; - case SetOp.Intersect: return l & r; - case SetOp.Exclude: return l & !r; - case SetOp.Complement: return !l & r; - case SetOp.Xor: return l ^ r; - default: return false; - } - } - - internal override RectangleF GetBounds() - { - var lb = Left.GetBounds(); - var rb = Right.GetBounds(); - switch (Op) - { - case SetOp.Intersect: - // Conservative: use intersection of bounds. - return RectangleF.Intersect(lb, rb); - case SetOp.Exclude: - return lb; - case SetOp.Complement: - return rb; - default: // Union, Xor - return RectangleF.Union(lb, rb); - } - } - - internal override RegionNode DeepClone() - => new OpRegionNode(Left.DeepClone(), Right.DeepClone(), Op); - - internal override void Translate(float dx, float dy) - { - Left.Translate(dx, dy); - Right.Translate(dx, dy); - } - - internal override void ApplyTransform(Matrix matrix) - { - Left.ApplyTransform(matrix); - Right.ApplyTransform(matrix); - } - - internal override void WriteTo(BinaryWriter w) - { - w.Write((byte)NodeTag.Op); - w.Write((byte)Op); - Left.WriteTo(w); - Right.WriteTo(w); - } - } - - // ------------------------------------------------------------------------- - // Factory / deserializer - // ------------------------------------------------------------------------- - internal static class RegionNodeSerializer - { - internal static RegionNode Read(BinaryReader r) - { - var tag = (NodeTag)r.ReadByte(); - switch (tag) - { - case NodeTag.Empty: - return EmptyRegionNode.Instance; - - case NodeTag.Infinite: - return InfiniteRegionNode.Instance; - - case NodeTag.Rect: - { - float x = r.ReadSingle(), y = r.ReadSingle(), - w = r.ReadSingle(), h = r.ReadSingle(); - return new LeafRectNode(new RectangleF(x, y, w, h)); - } - - case NodeTag.Path: - { - int n = r.ReadInt32(); - var pts = new PointF[n]; - var types = new byte[n]; - for (int i = 0; i < n; i++) - { - pts[i] = new PointF(r.ReadSingle(), r.ReadSingle()); - } - for (int i = 0; i < n; i++) types[i] = r.ReadByte(); - return new LeafPathNode(new GraphicsPath(pts, types)); - } - - case NodeTag.Op: - { - var op = (SetOp)r.ReadByte(); - var left = Read(r); - var right = Read(r); - return new OpRegionNode(left, right, op); - } - - default: - throw new InvalidOperationException($"Unknown region node tag {tag}."); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/SmoothingMode.cs b/src/MiniPdf/Drawing/Drawing2D/SmoothingMode.cs deleted file mode 100644 index 77b9915d..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/SmoothingMode.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies the smoothing mode for rendering lines and curves. - /// - public enum SmoothingMode - { - /// - /// Invalid smoothing mode. - /// - Invalid = -1, - - /// - /// Default smoothing mode (no anti-aliasing). - /// - Default = 0, - - /// - /// High speed, no smoothing. - /// - HighSpeed = 1, - - /// - /// High quality smoothing. - /// - HighQuality = 2, - - /// - /// No smoothing. - /// - None = 3, - - /// - /// Anti-aliased smoothing. - /// - AntiAlias = 4, - } -} diff --git a/src/MiniPdf/Drawing/Drawing2D/WrapMode.cs b/src/MiniPdf/Drawing/Drawing2D/WrapMode.cs deleted file mode 100644 index 3540be6b..00000000 --- a/src/MiniPdf/Drawing/Drawing2D/WrapMode.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Drawing2D -{ - /// - /// Specifies how texture and gradient brushes are tiled when they extend beyond the shape. - /// - public enum WrapMode - { - /// - /// Tiles the brush horizontally and vertically. - /// - Tile = 0, - - /// - /// Tiles the brush horizontally and flips it vertically. - /// - TileFlipX = 1, - - /// - /// Tiles the brush vertically and flips it horizontally. - /// - TileFlipY = 2, - - /// - /// Tiles the brush horizontally and vertically and flips both. - /// - TileFlipXY = 3, - - /// - /// Clamps the brush to the edges. - /// - Clamp = 4, - } -} diff --git a/src/MiniPdf/Drawing/Enums/FontStyle.cs b/src/MiniPdf/Drawing/Enums/FontStyle.cs deleted file mode 100644 index 5a21a676..00000000 --- a/src/MiniPdf/Drawing/Enums/FontStyle.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Enums -{ - /// - /// Specifies style information applied to text. - /// - [Flags] - public enum FontStyle - { - /// - /// Normal text. - /// - Regular = 0, - - /// - /// Bold text. - /// - Bold = 1, - - /// - /// Italic text. - /// - Italic = 2, - - /// - /// Underlined text. - /// - Underline = 4, - - /// - /// Strikethrough text. - /// - Strikeout = 8, - } -} diff --git a/src/MiniPdf/Drawing/Enums/GraphicsUnit.cs b/src/MiniPdf/Drawing/Enums/GraphicsUnit.cs deleted file mode 100644 index d4d10b75..00000000 --- a/src/MiniPdf/Drawing/Enums/GraphicsUnit.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace MiniSoftware.Drawing.Enums -{ - /// - /// Specifies the unit of measure for graphics operations. - /// - public enum GraphicsUnit - { - /// - /// World coordinate (multiple document units per inch). - /// - World = 0, - - /// - /// Display device units (multiple pixels per inch). - /// - Display = 1, - - /// - /// Measurement in pixels. - /// - Pixel = 2, - - /// - /// Measurement in points (1/72 inch). - /// - Point = 3, - - /// - /// Measurement in inches. - /// - Inch = 4, - - /// - /// Measurement in document units (1/300 inch). - /// - Document = 5, - - /// - /// Measurement in millimeters. - /// - Millimeter = 6, - } -} diff --git a/src/MiniPdf/Drawing/Enums/ImageLockMode.cs b/src/MiniPdf/Drawing/Enums/ImageLockMode.cs deleted file mode 100644 index fdda0f86..00000000 --- a/src/MiniPdf/Drawing/Enums/ImageLockMode.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Enums -{ - /// - /// Specifies the mode for locking image bits. - /// - public enum ImageLockMode - { - /// - /// Read-only access to image bits. - /// - ReadOnly = 1, - - /// - /// Write-only access to image bits. - /// - WriteOnly = 2, - - /// - /// Read-write access to image bits. - /// - ReadWrite = 3, - - /// - /// User input buffer mode. - /// - UserInputBuffer = 4, - } -} diff --git a/src/MiniPdf/Drawing/Enums/PixelFormat.cs b/src/MiniPdf/Drawing/Enums/PixelFormat.cs deleted file mode 100644 index ca650899..00000000 --- a/src/MiniPdf/Drawing/Enums/PixelFormat.cs +++ /dev/null @@ -1,123 +0,0 @@ -namespace MiniSoftware.Drawing.Enums -{ - /// - /// Specifies the format of the color data for each pixel in an image. - /// - public enum PixelFormat - { - /// - /// Undefined pixel format. - /// - Undefined = 0, - - /// - /// Pixel format is not important. - /// - DontCare = 0, - - /// - /// Maximum value for pixel format enumeration. - /// - Max = 15, - - /// - /// Indexed color format. - /// - Indexed = 0x00010000, - - /// - /// GDI-supported pixel format. - /// - Gdi = 0x00020000, - - /// - /// 16 bits per pixel; 5 bits each for red, green, and blue; 5 bits for alpha. - /// - Format16bppRgb555 = 0x00021005, - - /// - /// 16 bits per pixel; 5 bits for red, 6 bits for green, 5 bits for blue. - /// - Format16bppRgb565 = 0x00021006, - - /// - /// 24 bits per pixel; 8 bits each for red, green, and blue. - /// - Format24bppRgb = 0x00021808, - - /// - /// 32 bits per pixel; 8 bits each for red, green, and blue. - /// - Format32bppRgb = 0x00022009, - - /// - /// 1 bit per pixel indexed color. - /// - Format1bppIndexed = 0x00030101, - - /// - /// 4 bits per pixel indexed color. - /// - Format4bppIndexed = 0x00030402, - - /// - /// 8 bits per pixel indexed color. - /// - Format8bppIndexed = 0x00030803, - - /// - /// Alpha channel present. - /// - Alpha = 0x00040000, - - /// - /// 16 bits per pixel; 1 bit for alpha, 5 bits each for red, green, and blue. - /// - Format16bppArgb1555 = 0x00061007, - - /// - /// Premultiplied alpha format. - /// - PAlpha = 0x00080000, - - /// - /// 32 bits per pixel; 8 bits each for red, green, blue, and alpha; premultiplied. - /// - Format32bppPArgb = 0x000E200B, - - /// - /// Extended pixel format. - /// - Extended = 0x00100000, - - /// - /// 16 bits per pixel grayscale. - /// - Format16bppGrayScale= 0x00101004, - - /// - /// 48 bits per pixel; 16 bits each for red, green, and blue. - /// - Format48bppRgb = 0x0010300C, - - /// - /// 64 bits per pixel; 16 bits each for red, green, blue, and alpha; premultiplied. - /// - Format64bppPArgb = 0x001C400E, - - /// - /// Canonical pixel format. - /// - Canonical = 0x00200000, - - /// - /// 32 bits per pixel; 8 bits each for alpha, red, green, and blue. - /// - Format32bppArgb = 0x0026200A, - - /// - /// 64 bits per pixel; 16 bits each for alpha, red, green, and blue. - /// - Format64bppArgb = 0x0034400D, - } -} diff --git a/src/MiniPdf/Drawing/Enums/RotateFlipType.cs b/src/MiniPdf/Drawing/Enums/RotateFlipType.cs deleted file mode 100644 index 28e23439..00000000 --- a/src/MiniPdf/Drawing/Enums/RotateFlipType.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace MiniSoftware.Drawing.Enums -{ - /// - /// Specifies the type of rotation and/or flipping to apply to an image. - /// - public enum RotateFlipType - { - /// - /// No rotation and no flipping. - /// - RotateNoneFlipNone = 0, - - /// - /// 90-degree rotation with no flipping. - /// - Rotate90FlipNone = 1, - - /// - /// 180-degree rotation with no flipping. - /// - Rotate180FlipNone = 2, - - /// - /// 270-degree rotation with no flipping. - /// - Rotate270FlipNone = 3, - - /// - /// No rotation with horizontal flipping. - /// - RotateNoneFlipX = 4, - - /// - /// 90-degree rotation with horizontal flipping. - /// - Rotate90FlipX = 5, - - /// - /// 180-degree rotation with horizontal flipping. - /// - Rotate180FlipX = 6, - - /// - /// 270-degree rotation with horizontal flipping. - /// - Rotate270FlipX = 7, - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffData.cs b/src/MiniPdf/Drawing/Font/Cff/CffData.cs deleted file mode 100644 index d6d95f89..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffData.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Internal data holder produced by . - /// Stores the parsed CFF table in a font-type-agnostic form. - /// - internal sealed class CffData - { - /// PostScript name (first Name INDEX entry). - public string FontName = string.Empty; - - /// Full name resolved from Top DICT FullName SID. - public string? FullName; - - /// Family name resolved from Top DICT FamilyName SID. - public string? FamilyName; - - /// FontBBox array [xMin, yMin, xMax, yMax] in font units. - public double[] FontBBox = new double[4]; - - /// Raw charstring bytes, one entry per glyph (indexed by GID). - public byte[][] CharStrings = Array.Empty(); - - /// - /// Glyph names resolved from the charset table, indexed by GID. - /// Entry 0 is always ".notdef". Empty when no charset is present. - /// - public string[] GlyphNames = Array.Empty(); - - /// Private DICT for simple (non-CID) fonts. - public CffPrivateDict PrivateDict = new CffPrivateDict(); - - /// Global subroutines shared across all glyphs. - public byte[][]? GlobalSubrs; - - // ── CID font support ────────────────────────────────────────────────── - - /// when ROS / FDArray / FDSelect are present. - public bool IsCIDFont; - - /// Per-FD Private DICTs for CID fonts; null for simple fonts. - public CffCIDFontDict[]? CIDFontDicts; - - /// Maps each GID to an FD index into . - public int[]? GlyphFDIndex; - } - - /// - /// Per-Font-Dict data within a CID-keyed CFF font. - /// Each FD has its own Private DICT (and thus its own default/nominal widths and local subrs). - /// - internal sealed class CffCIDFontDict - { - public CffPrivateDict PrivateDict = new CffPrivateDict(); - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffFont.cs b/src/MiniPdf/Drawing/Font/Cff/CffFont.cs deleted file mode 100644 index 037db7e2..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffFont.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Encoding; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Rendering; -using MiniSoftware.Drawing.Font.Ttf; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Represents a loaded CFF (Compact Font Format) or OTF/CFF font face. - /// Charstrings are decoded via . - /// - public sealed class CffFont : IFont - { - // ── Private state ───────────────────────────────────────────────────── - - private readonly FontMetrics _metrics; - private readonly IFontEncoding _encoding; - private readonly CffGlyphAccessor _glyphAccessor; - - // ── Internal access for rendering / serialisation ───────────────────── - - internal CffData CffData { get; } - - /// - /// The sfnt table set when this font was loaded from an OTF container; - /// for standalone raw CFF files. - /// - internal TtfTables? SfntTables { get; } - - /// - /// Raw bytes of the "CFF " table when loaded from an OTF container; - /// for standalone raw CFF files. - /// - internal byte[]? RawCffBytes { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - /// Parsed CFF binary data. - /// - /// OpenType sfnt table set (for OTF/CFF), or for - /// standalone CFF files. - /// - /// - /// Raw bytes of the "CFF " table for round-trip serialisation, - /// or for standalone CFF files. - /// - internal CffFont(CffData cffData, TtfTables? sfntTables, byte[]? rawCffBytes = null) - { - CffData = cffData ?? throw new ArgumentNullException(nameof(cffData)); - SfntTables = sfntTables; - RawCffBytes = rawCffBytes; - - _metrics = BuildMetrics(cffData, sfntTables); - _encoding = BuildEncoding(sfntTables); - _glyphAccessor = new CffGlyphAccessor(cffData); - - if (sfntTables != null) - NumGlyphs = sfntTables.Maxp.NumGlyphs; - else - NumGlyphs = cffData.CharStrings.Length; - - Style = sfntTables != null - ? ResolveStyle(sfntTables.Head.MacStyle) - : FontFaceStyle.Regular; - } - - // ── IFont ───────────────────────────────────────────────────────────── - - /// - public string FontName => - CffData.FullName ?? CffData.FontName; - - /// - public string FontFamily => - CffData.FamilyName ?? CffData.FontName; - - /// - public int NumGlyphs { get; } - - /// - public FontFaceStyle Style { get; } - - /// - public IFontMetrics Metrics => _metrics; - - /// - public IFontEncoding Encoding => _encoding; - - /// - public IGlyphAccessor GlyphAccessor => _glyphAccessor; - - /// - public void Save(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - CffFontWriter.Write(this, stream); - } - - /// - public void Save(string filePath) - { - if (filePath is null) throw new ArgumentNullException(nameof(filePath)); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, - FileShare.None, bufferSize: 4096); - Save(fs); - } - - /// - /// Returns a string representation of this CFF font, including its name and glyph count. - /// - public override string ToString() => - $"CffFont(\"{FontName}\", {NumGlyphs} glyphs)"; - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static FontMetrics BuildMetrics(CffData cff, TtfTables? sfnt) - { - var m = new FontMetrics(gid => - { - if (!(gid is GlyphUInt32Id uid)) return 0.0; - int idx = (int)uid.Value; - if (idx < 0 || idx >= cff.CharStrings.Length) return 0.0; - - var priv = GetPrivateDictStatic(cff, idx); - var interp = new Type2Interpreter(); - // Use a no-op painter to extract width only - return interp.Interpret(cff.CharStrings[idx], NopPainter.Instance, priv, cff.GlobalSubrs); - }); - - if (sfnt != null) - { - m.Ascender = sfnt.Hhea.Ascender; - m.Descender = sfnt.Hhea.Descender; - m.LineGap = sfnt.Hhea.LineGap; - m.UnitsPerEM = sfnt.Head.UnitsPerEm; - - if (sfnt.Os2Table != null) - { - m.TypoAscender = sfnt.Os2Table.TypoAscender; - m.TypoDescender = sfnt.Os2Table.TypoDescender; - } - else - { - m.TypoAscender = sfnt.Hhea.Ascender; - m.TypoDescender = sfnt.Hhea.Descender; - } - } - else - { - // Standalone CFF: derive metrics from FontBBox - // FontBBox = [xMin, yMin, xMax, yMax] - m.Ascender = cff.FontBBox[3]; - m.Descender = cff.FontBBox[1]; - m.UnitsPerEM = cff.FontBBox[3] - cff.FontBBox[1]; - if (m.UnitsPerEM <= 0) m.UnitsPerEM = 1000; // typical CFF default - m.TypoAscender = m.Ascender; - m.TypoDescender = m.Descender; - } - - return m; - } - - private static IFontEncoding BuildEncoding(TtfTables? sfnt) - { - if (sfnt?.CMapTable != null) - { - var best = sfnt.CMapTable.FindUnicodeTable(); - if (best != null) return new TtfUnicodeEncoding(best); - } - return NullEncoding.Instance; - } - - private static FontFaceStyle ResolveStyle(ushort macStyle) - { - bool bold = (macStyle & 0x01) != 0; - bool italic = (macStyle & 0x02) != 0; - if (bold && italic) return FontFaceStyle.BoldItalic; - if (bold) return FontFaceStyle.Bold; - if (italic) return FontFaceStyle.Italic; - return FontFaceStyle.Regular; - } - - private static CffPrivateDict GetPrivateDictStatic(CffData cff, int gid) - { - if (cff.IsCIDFont && cff.GlyphFDIndex != null && cff.CIDFontDicts != null) - { - int fdIdx = gid < cff.GlyphFDIndex.Length ? cff.GlyphFDIndex[gid] : 0; - if (fdIdx >= 0 && fdIdx < cff.CIDFontDicts.Length) - return cff.CIDFontDicts[fdIdx].PrivateDict; - } - return cff.PrivateDict; - } - - // ── No-op painter for width-only measurement ────────────────────────── - - private sealed class NopPainter : IGlyphOutlinePainter - { - public static readonly NopPainter Instance = new NopPainter(); - public void MoveTo(MoveTo cmd) { } - public void LineTo(LineTo cmd) { } - public void CurveTo(CurveTo cmd) { } - public void ClosePath() { } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffFontReader.cs b/src/MiniPdf/Drawing/Font/Cff/CffFontReader.cs deleted file mode 100644 index b9047612..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffFontReader.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.IO; -using MiniSoftware.Drawing.Font.Ttf; -using MiniSoftware.Drawing.Font.Ttf.Tables; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Reads a CFF font from a stream and returns a . - /// Auto-detects OTF/CFF sfnt containers (magic OTTO) from standalone - /// raw CFF files. - /// - public static class CffFontReader - { - private const uint OttoMagic = 0x4F54544F; // "OTTO" - - /// - /// Parses the CFF font data from and returns a - /// . - /// - /// - /// The stream must be readable and seekable. It is not disposed by this reader. - /// - /// is null. - /// - /// The data cannot be parsed as a valid CFF or OTF/CFF font. - /// - public static CffFont Read(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - - // Peek at the first four bytes to distinguish OTF sfnt from raw CFF. - using var reader = new FontBinaryReader(stream, leaveOpen: true); - uint magic = reader.ReadUInt32(); - reader.Seek(0); - - return magic == OttoMagic - ? ReadFromSfnt(reader) - : ReadStandaloneCff(stream); - } - - // ── OTF/CFF sfnt container ──────────────────────────────────────────── - - private static CffFont ReadFromSfnt(FontBinaryReader reader) - { - reader.Seek(0); - - var (_, records) = OpenTypeTableDirectory.Parse(reader); - var rawTables = OpenTypeTableDirectory.ReadAllTableBytes(reader, records); - - // Parse optional sfnt metadata tables (same pattern as TtfFontReader). - TtfHeadTable? head = TryParse(rawTables, "head", b => TtfHeadTable.Parse(b)); - TtfHheaTable? hhea = TryParse(rawTables, "hhea", b => TtfHheaTable.Parse(b)); - TtfMaxpTable? maxp = TryParse(rawTables, "maxp", b => TtfMaxpTable.Parse(b)); - TtfNameTable? name = TryParse(rawTables, "name", b => TtfNameTable.Parse(b)); - - TtfHmtxTable? hmtx = null; - if (hhea != null && maxp != null && rawTables.ContainsKey("hmtx")) - hmtx = TryParse(rawTables, "hmtx", - b => TtfHmtxTable.Parse(b, hhea.NumberOfHMetrics, maxp.NumGlyphs)); - - TtfOs2Table? os2 = TryParse(rawTables, "OS/2", b => TtfOs2Table.Parse(b)); - TtfPostTable? post = TryParse(rawTables, "post", b => TtfPostTable.Parse(b)); - TtfCMapTable? cmap = TryParse(rawTables, "cmap", b => TtfCMapTable.Parse(b)); - - // Assemble sfnt tables (loca/glyf absent in CFF-flavoured OTF) - TtfTables? sfnt = null; - if (head != null && hhea != null && maxp != null && name != null && hmtx != null) - sfnt = new TtfTables(head, hhea, maxp, name, hmtx, - os2, post, loca: null, glyfTable: null, cmapTable: cmap); - - // Extract and parse the "CFF " table - if (!rawTables.TryGetValue("CFF ", out byte[]? cffBytes)) - throw new InvalidOperationException( - "OTF font has an 'OTTO' magic but no 'CFF ' table."); - - var cffData = CffParser.Parse(cffBytes); - - // Patch font name from sfnt name table when available - if (sfnt != null) - { - if (cffData.FullName is null) cffData.FullName = sfnt.Name.FullName; - if (cffData.FamilyName is null) cffData.FamilyName = sfnt.Name.FamilyName; - if (string.IsNullOrEmpty(cffData.FontName)) - cffData.FontName = sfnt.Name.PostScriptName ?? sfnt.Name.FullName ?? string.Empty; - } - - return new CffFont(cffData, sfnt, cffBytes); - } - - // ── Standalone CFF ──────────────────────────────────────────────────── - - private static CffFont ReadStandaloneCff(Stream stream) - { - byte[] cffBytes = ReadAllBytes(stream); - var cffData = CffParser.Parse(cffBytes); - return new CffFont(cffData, sfntTables: null); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static byte[] ReadAllBytes(Stream stream) - { - if (stream.CanSeek) - { - long rem = stream.Length - stream.Position; - if (rem < 0) rem = 0; - byte[] buf = new byte[rem]; - int read = 0; - while (read < buf.Length) - { - int n = stream.Read(buf, read, buf.Length - read); - if (n == 0) break; - read += n; - } - return buf; - } - // Non-seekable fall-through - using var ms = new MemoryStream(); - stream.CopyTo(ms); - return ms.ToArray(); - } - - private static T? TryParse( - System.Collections.Generic.IReadOnlyDictionary rawTables, - string tag, - Func parser) - where T : class - { - if (!rawTables.TryGetValue(tag, out byte[]? raw)) return null; - try { return parser(raw); } - catch { return null; } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffFontWriter.cs b/src/MiniPdf/Drawing/Font/Cff/CffFontWriter.cs deleted file mode 100644 index 5157a32e..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffFontWriter.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.IO; -using MiniSoftware.Drawing.Font.Ttf; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Serialises a back to a binary sfnt/CFF stream. - /// - /// For OTF/CFF fonts (loaded from an sfnt container with the "CFF " table) - /// the sfnt frame is rebuilt from the raw table bytes stored at load time, - /// with the original "CFF " bytes re-inserted. - /// - /// - /// Standalone raw CFF files are written back as-is without an sfnt wrapper. - /// - /// - public static class CffFontWriter - { - // ───────────────────────────────────────────────────────────────────── - // Public entry point - // ───────────────────────────────────────────────────────────────────── - - /// - /// Serialises and writes the result to - /// . - /// - /// Either argument is null. - /// - /// Thrown for standalone (non-sfnt) CFF files where round-trip serialisation - /// is not yet supported. - /// - public static void Write(CffFont font, Stream stream) - { - if (font == null) throw new ArgumentNullException(nameof(font)); - if (stream == null) throw new ArgumentNullException(nameof(stream)); - - byte[] data = WriteToBytes(font); - stream.Write(data, 0, data.Length); - } - - /// - /// Serialises and returns the resulting bytes. - /// - public static byte[] WriteToBytes(CffFont font) - { - if (font == null) throw new ArgumentNullException(nameof(font)); - - if (font.SfntTables == null || font.RawCffBytes == null) - throw new NotSupportedException( - "Serialisation of standalone (non-sfnt) CFF files is not supported."); - - // Collect the sfnt tables (head, hhea, maxp, etc.) and add the CFF table. - var tables = TtfFontWriter.CollectTables(font.SfntTables); - tables.Add(("CFF ", font.RawCffBytes)); - - // Re-sort (CFF must fit into the canonical tag order). - tables.Sort((a, b) => string.Compare(a.Tag, b.Tag, StringComparison.Ordinal)); - - return TtfFontWriter.BuildSfnt(OpenTypeOffsetTable.SfVersionCff, tables); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffGlyphAccessor.cs b/src/MiniPdf/Drawing/Font/Cff/CffGlyphAccessor.cs deleted file mode 100644 index 55ec17aa..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffGlyphAccessor.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Rendering; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Provides glyph metrics and names for a CFF font by executing - /// Type 2 charstrings via . - /// - public sealed class CffGlyphAccessor : IGlyphAccessor - { - private readonly CffData _data; - - internal CffGlyphAccessor(CffData data) - { - _data = data ?? throw new ArgumentNullException(nameof(data)); - } - - /// - public Glyph? GetGlyphById(GlyphId gid) - { - if (!(gid is GlyphUInt32Id uid)) return null; - - int idx = (int)uid.Value; - if (idx < 0 || idx >= _data.CharStrings.Length) return null; - - var priv = GetPrivateDict(idx); - var recording = new BBoxRecordingPainter(); - var interp = new Type2Interpreter(); - double width = interp.Interpret(_data.CharStrings[idx], recording, priv, _data.GlobalSubrs); - - return new Glyph(gid, recording.GetBBox(), width); - } - - /// - public Glyph? GetGlyphByIndex(uint index) - => GetGlyphById(new GlyphUInt32Id(index)); - - // ── Helpers ─────────────────────────────────────────────────────────── - - private CffPrivateDict GetPrivateDict(int gid) - { - if (_data.IsCIDFont && _data.GlyphFDIndex != null && _data.CIDFontDicts != null) - { - int fdIdx = gid < _data.GlyphFDIndex.Length ? _data.GlyphFDIndex[gid] : 0; - if (fdIdx >= 0 && fdIdx < _data.CIDFontDicts.Length) - return _data.CIDFontDicts[fdIdx].PrivateDict; - } - return _data.PrivateDict; - } - - // ── BBox recording painter ──────────────────────────────────────────── - - private sealed class BBoxRecordingPainter : IGlyphOutlinePainter - { - private double _minX = double.MaxValue, _minY = double.MaxValue; - private double _maxX = double.MinValue, _maxY = double.MinValue; - private bool _hasPoints; - - private void Track(double x, double y) - { - if (x < _minX) _minX = x; - if (x > _maxX) _maxX = x; - if (y < _minY) _minY = y; - if (y > _maxY) _maxY = y; - _hasPoints = true; - } - - public void MoveTo(MoveTo cmd) => Track(cmd.X, cmd.Y); - public void LineTo(LineTo cmd) => Track(cmd.X, cmd.Y); - public void CurveTo(CurveTo cmd) - { - Track(cmd.X1, cmd.Y1); - Track(cmd.X2, cmd.Y2); - Track(cmd.X3, cmd.Y3); - } - public void ClosePath() { } - - public GlyphBoundingBox GetBBox() - => _hasPoints - ? new GlyphBoundingBox(_minX, _minY, _maxX, _maxY) - : new GlyphBoundingBox(0, 0, 0, 0); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffParser.cs b/src/MiniPdf/Drawing/Font/Cff/CffParser.cs deleted file mode 100644 index 72cec3c0..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffParser.cs +++ /dev/null @@ -1,553 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Parses the binary CFF (Compact Font Format) table and produces a - /// instance. Supports CFF version 1 (including CID-keyed fonts). - /// - internal static class CffParser - { - // ── CFF Standard Strings (Appendix A, 390 entries) ─────────────────── - - private static readonly string[] s_stdStrings = - { - ".notdef","space","exclam","quotedbl","numbersign","dollar","percent", - "ampersand","quoteright","parenleft","parenright","asterisk","plus","comma", - "hyphen","period","slash","zero","one","two","three","four","five","six", - "seven","eight","nine","colon","semicolon","less","equal","greater","question", - "at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R", - "S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright", - "asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i", - "j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", - "braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling", - "fraction","yen","florin","section","currency","quotesingle","quotedblleft", - "guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger", - "daggerdbl","periodcentered","paragraph","bullet","quotesinglbase", - "quotedblbase","quotedblright","guillemotright","ellipsis","perthousand", - "questiondown","grave","acute","circumflex","tilde","macron","breve", - "dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron", - "emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae", - "dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot", - "mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide", - "brokenbar","degree","thorn","threequarters","twosuperior","registered", - "minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex", - "Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex", - "Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde", - "Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute", - "Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute", - "acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute", - "ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis", - "igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde", - "scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis", - "zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior", - "ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior", - "twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle", - "threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle", - "eightoldstyle","nineoldstyle","commasuperior","threequartersemdash", - "periodsuperior","questionsmall","asuperior","bsuperior","centsuperior", - "dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior", - "osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl", - "parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior", - "Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall", - "Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall", - "Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall", - "Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall", - "exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall", - "Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall", - "figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall", - "questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths", - "onethird","twothirds","zerosuperior","foursuperior","fivesuperior", - "sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior", - "oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior", - "sixinferior","seveninferior","eightinferior","nineinferior","centinferior", - "dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall", - "Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall", - "Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall", - "Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall", - "Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall", - "Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall", - "Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall", - "Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold", - "Book","Light","Medium","Regular","Roman","Semibold" - }; // 390 entries - - // ── Top DICT operator codes ─────────────────────────────────────────── - private const int Op_version = 0; - private const int Op_Notice = 1; - private const int Op_FullName = 2; - private const int Op_FamilyName = 3; - private const int Op_Weight = 4; - private const int Op_FontBBox = 5; - private const int Op_CharStrings = 17; - private const int Op_Private = 18; // two operands: size, offset - private const int Op_Charset = 15; - private const int Op_Encoding = 16; - private const int Op_ROS = 0x0C1E; // 12 30 — CID ROS - private const int Op_FDArray = 0x0C24; // 12 36 - private const int Op_FDSelect = 0x0C25; // 12 37 - private const int Op_CIDFontName = 0x0C26; // 12 38 - - // ── Private DICT operator codes ─────────────────────────────────────── - private const int PDOp_Subrs = 19; - private const int PDOp_defaultWidthX = 20; - private const int PDOp_nominalWidthX = 21; - - // ── Public entry point ──────────────────────────────────────────────── - - /// - /// Parses a complete CFF binary blob and returns a instance. - /// - public static CffData Parse(byte[] data) - { - if (data is null || data.Length < 4) - throw new ArgumentException("CFF data is too short.", nameof(data)); - - byte major = data[0]; - byte minor = data[1]; - byte hdrSize = data[2]; - // offSize (data[3]) is the default for INDEX offset sizes; not used directly here. - - if (major != 1) - throw new NotSupportedException( - $"CFF major version {major} is not supported (only version 1)."); - - int pos = hdrSize; // Name INDEX starts right after the header. - - // 1. Name INDEX → font name(s) - byte[][] nameIndex = ReadIndex(data, ref pos); - string fontName = (nameIndex.Length > 0) - ? SysEncoding.ASCII.GetString(nameIndex[0]).TrimEnd('\0') - : string.Empty; - - // 2. Top DICT INDEX - byte[][] topDictIndex = ReadIndex(data, ref pos); - if (topDictIndex.Length == 0) - throw new InvalidOperationException("CFF Top DICT INDEX is empty."); - var topDictEntries = ParseDict(topDictIndex[0], 0, topDictIndex[0].Length); - - // 3. String INDEX - byte[][] stringIndex = ReadIndex(data, ref pos); - string[] customStrings = new string[stringIndex.Length]; - for (int i = 0; i < stringIndex.Length; i++) - customStrings[i] = SysEncoding.ASCII.GetString(stringIndex[i]).TrimEnd('\0'); - - // 4. Global Subr INDEX - byte[][] globalSubrs = ReadIndex(data, ref pos); - - // ── Resolve Top DICT entries ────────────────────────────────────── - var result = new CffData { FontName = fontName }; - result.GlobalSubrs = globalSubrs.Length > 0 ? globalSubrs : null; - - int charStringsOffset = 0; - int charsetOffset = 0; // 0 = ISOAdobe predefined - int privateSize = 0; - int privateOffset = 0; - bool isCID = false; - int fdArrayOffset = 0; - int fdSelectOffset = 0; - - foreach (var (op, operands) in topDictEntries) - { - switch (op) - { - case Op_FullName: - if (operands.Length > 0) - result.FullName = GetString((int)operands[0], customStrings); - break; - case Op_FamilyName: - if (operands.Length > 0) - result.FamilyName = GetString((int)operands[0], customStrings); - break; - case Op_FontBBox: - for (int i = 0; i < 4 && i < operands.Length; i++) - result.FontBBox[i] = operands[i]; - break; - case Op_CharStrings: - if (operands.Length > 0) charStringsOffset = (int)operands[0]; - break; - case Op_Charset: - if (operands.Length > 0) charsetOffset = (int)operands[0]; - break; - case Op_Private: - if (operands.Length >= 2) - { - privateSize = (int)operands[0]; - privateOffset = (int)operands[1]; - } - break; - case Op_ROS: - isCID = true; - break; - case Op_FDArray: - if (operands.Length > 0) fdArrayOffset = (int)operands[0]; - break; - case Op_FDSelect: - if (operands.Length > 0) fdSelectOffset = (int)operands[0]; - break; - } - } - - // 5. Parse CharStrings INDEX - if (charStringsOffset > 0) - { - int csp = charStringsOffset; - byte[][] charStrings = ReadIndex(data, ref csp); - result.CharStrings = charStrings; - } - - int numGlyphs = result.CharStrings.Length; - - // 6. Parse charset → glyph names - result.GlyphNames = ReadCharset(data, charsetOffset, numGlyphs, customStrings); - - // 7. Parse Private DICT (and local subrs) for simple fonts - if (privateOffset > 0 && privateSize > 0 && !isCID) - { - result.PrivateDict = ParsePrivateDict(data, privateOffset, privateSize); - } - - // 8. CID font support - if (isCID && fdArrayOffset > 0) - { - result.IsCIDFont = true; - result.CIDFontDicts = ParseFDArray(data, fdArrayOffset); - - if (fdSelectOffset > 0 && numGlyphs > 0) - result.GlyphFDIndex = ParseFDSelect(data, fdSelectOffset, numGlyphs); - } - - return result; - } - - // ── INDEX reader ────────────────────────────────────────────────────── - - private static byte[][] ReadIndex(byte[] data, ref int pos) - { - if (pos + 2 > data.Length) return Array.Empty(); - - int count = (data[pos] << 8) | data[pos + 1]; - pos += 2; - - if (count == 0) return Array.Empty(); - - int offSize = data[pos++]; - if (offSize < 1 || offSize > 4) - throw new InvalidOperationException($"CFF INDEX offSize {offSize} is out of range."); - - int[] offsets = new int[count + 1]; - for (int i = 0; i <= count; i++) - { - int v = 0; - for (int b = 0; b < offSize; b++) - v = (v << 8) | data[pos++]; - offsets[i] = v; - } - - int dataStart = pos; // offsets are 1-based from here - byte[][] result = new byte[count][]; - for (int i = 0; i < count; i++) - { - int start = dataStart + offsets[i] - 1; - int len = offsets[i + 1] - offsets[i]; - if (len < 0) len = 0; - byte[] item = new byte[len]; - if (len > 0) Buffer.BlockCopy(data, start, item, 0, len); - result[i] = item; - } - - pos = dataStart + offsets[count] - 1; - return result; - } - - // ── DICT parser ─────────────────────────────────────────────────────── - - private static List<(int op, double[] operands)> ParseDict(byte[] data, int start, int length) - { - var result = new List<(int, double[])>(); - var operands = new List(); - int pos = start; - int end = start + length; - - while (pos < end) - { - byte b0 = data[pos]; - - if (b0 == 12) - { - // Two-byte operator - pos++; - if (pos >= end) break; - byte b1 = data[pos++]; - result.Add((0x0C00 | b1, operands.ToArray())); - operands.Clear(); - } - else if (b0 <= 21) - { - // Single-byte operator - result.Add((b0, operands.ToArray())); - operands.Clear(); - pos++; - } - else if (b0 == 28) - { - // ShortInt: 3 bytes - pos++; - if (pos + 1 >= end) break; - int v = (sbyte)data[pos] << 8 | data[pos + 1]; - pos += 2; - operands.Add(v); - } - else if (b0 == 29) - { - // LongInt: 5 bytes - pos++; - if (pos + 3 >= end) break; - int v = (int)((uint)(data[pos] << 24) | (uint)(data[pos + 1] << 16) | - (uint)(data[pos + 2] << 8) | data[pos + 3]); - pos += 4; - operands.Add(v); - } - else if (b0 == 30) - { - // Real number (nibble-encoded) - pos++; - operands.Add(ReadRealNumber(data, ref pos, end)); - } - else if (b0 >= 32 && b0 <= 246) - { - operands.Add(b0 - 139); - pos++; - } - else if (b0 >= 247 && b0 <= 250) - { - pos++; - if (pos >= end) break; - byte b1 = data[pos++]; - operands.Add((b0 - 247) * 256.0 + b1 + 108); - } - else if (b0 >= 251 && b0 <= 254) - { - pos++; - if (pos >= end) break; - byte b1 = data[pos++]; - operands.Add(-((b0 - 251) * 256.0 + b1 + 108)); - } - else - { - pos++; // skip reserved bytes - } - } - - return result; - } - - private static double ReadRealNumber(byte[] data, ref int pos, int end) - { - var sb = new System.Text.StringBuilder(); - while (pos < end) - { - byte b = data[pos++]; - int hi = (b >> 4) & 0x0F; - int lo = b & 0x0F; - if (!AppendNibble(sb, hi)) break; - if (!AppendNibble(sb, lo)) break; - } - return double.TryParse(sb.ToString(), - System.Globalization.NumberStyles.Float, - System.Globalization.CultureInfo.InvariantCulture, - out double v) ? v : 0.0; - } - - private static bool AppendNibble(System.Text.StringBuilder sb, int nibble) - { - switch (nibble) - { - case 0x0: case 0x1: case 0x2: case 0x3: case 0x4: - case 0x5: case 0x6: case 0x7: case 0x8: case 0x9: - sb.Append((char)('0' + nibble)); return true; - case 0xA: sb.Append('.'); return true; - case 0xB: sb.Append('E'); return true; - case 0xC: sb.Append("E-"); return true; - case 0xD: return true; // reserved — skip - case 0xE: sb.Append('-'); return true; - case 0xF: return false; // end of number - default: return false; - } - } - - // ── Private DICT ────────────────────────────────────────────────────── - - private static CffPrivateDict ParsePrivateDict(byte[] data, int offset, int size) - { - var pd = new CffPrivateDict(); - var entries = ParseDict(data, offset, size); - int subrsRelOffset = 0; - foreach (var (op, operands) in entries) - { - switch (op) - { - case PDOp_defaultWidthX: - if (operands.Length > 0) pd.DefaultWidthX = operands[0]; - break; - case PDOp_nominalWidthX: - if (operands.Length > 0) pd.NominalWidthX = operands[0]; - break; - case PDOp_Subrs: - if (operands.Length > 0) subrsRelOffset = (int)operands[0]; - break; - } - } - if (subrsRelOffset != 0) - { - int subrsAbs = offset + subrsRelOffset; - if (subrsAbs < data.Length) - { - int p = subrsAbs; - byte[][] localSubrs = ReadIndex(data, ref p); - if (localSubrs.Length > 0) - pd.LocalSubrs = localSubrs; - } - } - return pd; - } - - // ── Charset ─────────────────────────────────────────────────────────── - - private static string[] ReadCharset(byte[] data, int offset, int numGlyphs, string[] customStrings) - { - if (numGlyphs == 0) return Array.Empty(); - - var names = new string[numGlyphs]; - names[0] = ".notdef"; - - if (offset <= 2) - { - // Predefined charsets 0/1/2 — glyph names not critical for rendering - for (int i = 1; i < numGlyphs; i++) - names[i] = string.Empty; - return names; - } - - if (offset >= data.Length) return names; - - int format = data[offset]; - int pos = offset + 1; - - switch (format) - { - case 0: // SID per glyph - for (int gid = 1; gid < numGlyphs && pos + 1 < data.Length; gid++) - { - int sid = (data[pos] << 8) | data[pos + 1]; - pos += 2; - names[gid] = GetString(sid, customStrings); - } - break; - - case 1: // Range1: {SID(2), nLeft(1)}+ - { - int gid = 1; - while (gid < numGlyphs && pos + 2 < data.Length) - { - int sid = (data[pos] << 8) | data[pos + 1]; - int nLeft = data[pos + 2]; - pos += 3; - for (int k = 0; k <= nLeft && gid < numGlyphs; k++, gid++) - names[gid] = GetString(sid + k, customStrings); - } - break; - } - - case 2: // Range2: {SID(2), nLeft(2)}+ - { - int gid = 1; - while (gid < numGlyphs && pos + 3 < data.Length) - { - int sid = (data[pos] << 8) | data[pos + 1]; - int nLeft = (data[pos + 2] << 8) | data[pos + 3]; - pos += 4; - for (int k = 0; k <= nLeft && gid < numGlyphs; k++, gid++) - names[gid] = GetString(sid + k, customStrings); - } - break; - } - } - - return names; - } - - // ── CID FDArray / FDSelect ──────────────────────────────────────────── - - private static CffCIDFontDict[] ParseFDArray(byte[] data, int offset) - { - int p = offset; - byte[][] fdBytes = ReadIndex(data, ref p); - var result = new CffCIDFontDict[fdBytes.Length]; - for (int i = 0; i < fdBytes.Length; i++) - { - var fd = new CffCIDFontDict(); - var fdEntries = ParseDict(fdBytes[i], 0, fdBytes[i].Length); - int privSize = 0, privOffset = 0; - foreach (var (op, operands) in fdEntries) - { - if (op == Op_Private && operands.Length >= 2) - { - privSize = (int)operands[0]; - privOffset = (int)operands[1]; - } - } - if (privOffset > 0 && privSize > 0) - fd.PrivateDict = ParsePrivateDict(data, privOffset, privSize); - result[i] = fd; - } - return result; - } - - private static int[] ParseFDSelect(byte[] data, int offset, int numGlyphs) - { - var result = new int[numGlyphs]; - if (offset >= data.Length) return result; - - int format = data[offset]; - int pos = offset + 1; - - if (format == 0) - { - for (int i = 0; i < numGlyphs && pos < data.Length; i++) - result[i] = data[pos++]; - } - else if (format == 3) - { - int nRanges = (data[pos] << 8) | data[pos + 1]; - pos += 2; - for (int r = 0; r < nRanges && pos + 2 < data.Length; r++) - { - int first = (data[pos] << 8) | data[pos + 1]; - int fdIdx = data[pos + 2]; - pos += 3; - int end = (r + 1 < nRanges && pos + 1 < data.Length) - ? (data[pos] << 8) | data[pos + 1] - : numGlyphs; - for (int g = first; g < end && g < numGlyphs; g++) - result[g] = fdIdx; - } - } - - return result; - } - - // ── String lookup ───────────────────────────────────────────────────── - - private static string GetString(int sid, string[] customStrings) - { - if (sid < 0) return string.Empty; - if (sid < s_stdStrings.Length) return s_stdStrings[sid]; - int ci = sid - s_stdStrings.Length; - return ci < customStrings.Length ? customStrings[ci] : string.Empty; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/CffPrivateDict.cs b/src/MiniPdf/Drawing/Font/Cff/CffPrivateDict.cs deleted file mode 100644 index 95845347..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/CffPrivateDict.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Parsed contents of a CFF Private DICT. - /// Holds the default/nominal advance-width values and optional local subroutines. - /// - public sealed class CffPrivateDict - { - /// - /// Width used when no explicit width is encoded in the charstring. - /// Corresponds to the CFF defaultWidthX entry (key 20). - /// - public double DefaultWidthX { get; internal set; } = 0.0; - - /// - /// Nominal width added to the delta stored in the charstring. - /// Corresponds to the CFF nominalWidthX entry (key 21). - /// - public double NominalWidthX { get; internal set; } = 0.0; - - /// - /// Local subroutines for this Private DICT, or - /// when the Subrs entry (key 19) is absent. - /// - public byte[][]? LocalSubrs { get; internal set; } - } -} diff --git a/src/MiniPdf/Drawing/Font/Cff/Type2Interpreter.cs b/src/MiniPdf/Drawing/Font/Cff/Type2Interpreter.cs deleted file mode 100644 index 4ca71d01..00000000 --- a/src/MiniPdf/Drawing/Font/Cff/Type2Interpreter.cs +++ /dev/null @@ -1,893 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Rendering; - -namespace MiniSoftware.Drawing.Font.Cff -{ - /// - /// Directly executes a Type 2 charstring, emitting drawing commands to an - /// . The interpreter is reentrant: recursive - /// calls for callsubr / callgsubr share the same - /// instance. - /// - internal sealed class Type2Interpreter - { - // ── Subroutine bias ─────────────────────────────────────────────────── - - internal static int CalcBias(int nSubrs) - { - if (nSubrs < 1240) return 107; - if (nSubrs < 33900) return 1131; - return 32768; - } - - // ── Public entry point ──────────────────────────────────────────────── - - /// - /// Executes and delivers outline commands - /// to . - /// - /// The advance width of the glyph in font units. - public double Interpret( - byte[] charstring, - IGlyphOutlinePainter painter, - CffPrivateDict priv, - byte[][]? globalSubrs) - { - if (charstring is null || charstring.Length == 0) - return priv.DefaultWidthX; - - var state = new InterpState(painter, priv, globalSubrs); - Execute(charstring, state); - if (state.InPath) { painter.ClosePath(); state.InPath = false; } - return state.Width; - } - - // ── Core execution ──────────────────────────────────────────────────── - - private static void Execute(byte[] data, InterpState s) - { - int pos = 0; - int len = data.Length; - - while (pos < len) - { - byte b0 = data[pos++]; - - // ── Number operands ─────────────────────────────────────────── - if (b0 >= 32 && b0 <= 246) - { - s.Push(b0 - 139); - continue; - } - if (b0 >= 247 && b0 <= 250) - { - if (pos >= len) return; - s.Push((b0 - 247) * 256.0 + data[pos++] + 108); - continue; - } - if (b0 >= 251 && b0 <= 254) - { - if (pos >= len) return; - s.Push(-((b0 - 251) * 256.0 + data[pos++] + 108)); - continue; - } - if (b0 == 28) // shortint - { - if (pos + 1 >= len) return; - int v = (sbyte)data[pos] << 8 | data[pos + 1]; - pos += 2; - s.Push(v); - continue; - } - if (b0 == 255) // fixed 16.16 - { - if (pos + 3 >= len) return; - int fixed1616 = (int)((uint)(data[pos] << 24) | (uint)(data[pos + 1] << 16) | - (uint)(data[pos + 2] << 8) | data[pos + 3]); - pos += 4; - s.Push(fixed1616 / 65536.0); - continue; - } - - // ── Two-byte operators (escape 12) ──────────────────────────── - if (b0 == 12) - { - if (pos >= len) return; - byte b1 = data[pos++]; - switch (b1) - { - case 3: // and - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push((v1 != 0 && v2 != 0) ? 1.0 : 0.0); - break; - } - case 4: // or - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push((v1 != 0 || v2 != 0) ? 1.0 : 0.0); - break; - } - case 5: // not - s.Push(s.Pop() == 0 ? 1.0 : 0.0); - break; - case 9: // abs - s.Push(Math.Abs(s.Pop())); - break; - case 10: // add - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v1 + v2); - break; - } - case 11: // sub - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v1 - v2); - break; - } - case 12: // div - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v2 == 0 ? 0 : v1 / v2); - break; - } - case 14: // neg - s.Push(-s.Pop()); - break; - case 15: // eq - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v1 == v2 ? 1.0 : 0.0); - break; - } - case 18: // drop - if (s.Top > 0) s.Pop(); - break; - case 20: // put - { - int idx = (int)s.Pop(); - double val = s.Pop(); - if (idx >= 0 && idx < s.Storage.Length) s.Storage[idx] = val; - break; - } - case 21: // get - { - int idx = (int)s.Pop(); - s.Push(idx >= 0 && idx < s.Storage.Length ? s.Storage[idx] : 0); - break; - } - case 22: // ifelse - { - double s2 = s.Pop(), s1 = s.Pop(); - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(s1 <= s2 ? v1 : v2); - break; - } - case 23: // random — push deterministic 0.5 - s.Push(0.5); - break; - case 24: // mul - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v1 * v2); - break; - } - case 26: // sqrt - s.Push(Math.Sqrt(Math.Abs(s.Pop()))); - break; - case 27: // dup - { - double v = s.Peek(); - s.Push(v); - break; - } - case 28: // exch - { - double v2 = s.Pop(), v1 = s.Pop(); - s.Push(v2); s.Push(v1); - break; - } - case 29: // index - { - int idx = (int)s.Pop(); - s.Push(idx < 0 ? s.Peek() : s.PeekAt(idx)); - break; - } - case 30: // roll - { - int j = (int)s.Pop(); - int n = (int)s.Pop(); - s.Roll(n, j); - break; - } - case 34: // hflex - ExecHFlex(s); - break; - case 35: // flex - ExecFlex(s); - break; - case 36: // hflex1 - ExecHFlex1(s); - break; - case 37: // flex1 - ExecFlex1(s); - break; - default: - s.ClearStack(); - break; - } - continue; - } - - // ── Single-byte operators ───────────────────────────────────── - switch (b0) - { - case 1: // hstem - case 3: // vstem - case 18: // hstemhm - case 23: // vstemhm - DoStem(s); - break; - - case 4: // vmoveto - { - ExtractWidthIfFirst(s, 2); - double dy = s.Pop(); - s.ClearStack(); - DoMoveTo(s, 0, dy); - break; - } - - case 5: // rlineto - { - int i = 0; - while (i + 1 < s.Top) - { - s.CX += s.Stack[i]; s.CY += s.Stack[i + 1]; i += 2; - s.Painter.LineTo(new LineTo(s.CX, s.CY)); - } - s.ClearStack(); - break; - } - - case 6: // hlineto - DoHLineTo(s); - break; - - case 7: // vlineto - DoVLineTo(s); - break; - - case 8: // rrcurveto - DoRRCurveTo(s); - break; - - case 10: // callsubr - { - int idx = (int)s.Pop() + s.LocalBias; - if (s.LocalSubrs != null && idx >= 0 && idx < s.LocalSubrs.Length) - Execute(s.LocalSubrs[idx], s); - break; - } - - case 11: // return - return; // return from current Execute() call - - case 14: // endchar - ExtractWidthIfFirst(s, 1); - if (s.InPath) { s.Painter.ClosePath(); s.InPath = false; } - return; - - case 15: // (unused in Type2) — ignore - case 16: // blend — variable fonts; ignore for now - s.ClearStack(); - break; - - case 19: // hintmask - case 20: // cntrmask - DoStem(s); // implicit stems from remaining stack - // Skip hint mask bytes - int maskBytes = (s.StemCount + 7) / 8; - pos += maskBytes; - if (pos > len) pos = len; - break; - - case 21: // rmoveto - { - ExtractWidthIfFirst(s, 3); - double dy = s.Pop(), dx = s.Pop(); - s.ClearStack(); - DoMoveTo(s, dx, dy); - break; - } - - case 22: // hmoveto - { - ExtractWidthIfFirst(s, 2); - double dx = s.Pop(); - s.ClearStack(); - DoMoveTo(s, dx, 0); - break; - } - - case 24: // rcurveline - DoRCurveLine(s); - break; - - case 25: // rlinecurve - DoRLineCurve(s); - break; - - case 26: // vvcurveto - DoVVCurveTo(s); - break; - - case 27: // hhcurveto - DoHHCurveTo(s); - break; - - case 29: // callgsubr - { - int idx = (int)s.Pop() + s.GlobalBias; - if (s.GlobalSubrs != null && idx >= 0 && idx < s.GlobalSubrs.Length) - Execute(s.GlobalSubrs[idx], s); - break; - } - - case 30: // vhcurveto - DoVHCurveTo(s); - break; - - case 31: // hvcurveto - DoHVCurveTo(s); - break; - - default: - // Unknown operator — clear stack and continue - s.ClearStack(); - break; - } - } - } - - // ── Stem helpers ────────────────────────────────────────────────────── - - private static void DoStem(InterpState s) - { - if (!s.FirstOpSeen && s.Top % 2 != 0) - { - // Odd stack count → first value is the width delta - s.Width = s.NominalWidth + s.Stack[0]; - // Shift stack left by 1 - for (int i = 0; i + 1 < s.Top; i++) s.Stack[i] = s.Stack[i + 1]; - s.Top--; - s.HasWidth = true; - } - s.StemCount += s.Top / 2; - s.FirstOpSeen = true; - s.ClearStack(); - } - - // ── MoveTo helpers ──────────────────────────────────────────────────── - - private static void ExtractWidthIfFirst(InterpState s, int expectedArgs) - { - if (!s.FirstOpSeen && s.Top == expectedArgs) - { - s.Width = s.NominalWidth + s.Stack[0]; - for (int i = 0; i + 1 < s.Top; i++) s.Stack[i] = s.Stack[i + 1]; - s.Top--; - s.HasWidth = true; - } - s.FirstOpSeen = true; - } - - private static void DoMoveTo(InterpState s, double dx, double dy) - { - if (s.InPath) { s.Painter.ClosePath(); s.InPath = false; } - s.CX += dx; - s.CY += dy; - s.SX = s.CX; - s.SY = s.CY; - s.Painter.MoveTo(new MoveTo(s.CX, s.CY)); - s.InPath = true; - } - - // ── Line operators ──────────────────────────────────────────────────── - - private static void DoHLineTo(InterpState s) - { - // hlineto: dx {dy dx}* OR {dx dy}+ - // Alternating: first segment horizontal (dx), then vertical (dy), ... - // If odd count: first is horizontal; if even: first pair h/v - int i = 0, count = s.Top; - bool isH = true; - while (i < count) - { - if (isH) s.CX += s.Stack[i]; - else s.CY += s.Stack[i]; - s.Painter.LineTo(new LineTo(s.CX, s.CY)); - i++; - isH = !isH; - } - s.ClearStack(); - } - - private static void DoVLineTo(InterpState s) - { - // vlineto: dy {dx dy}* — first segment vertical - int i = 0, count = s.Top; - bool isV = true; - while (i < count) - { - if (isV) s.CY += s.Stack[i]; - else s.CX += s.Stack[i]; - s.Painter.LineTo(new LineTo(s.CX, s.CY)); - i++; - isV = !isV; - } - s.ClearStack(); - } - - // ── Curve operators ─────────────────────────────────────────────────── - - private static void DoRRCurveTo(InterpState s) - { - int i = 0; - while (i + 5 < s.Top) - { - double x1 = s.CX + s.Stack[i]; double y1 = s.CY + s.Stack[i + 1]; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2 + s.Stack[i + 4]; double y3 = y2 + s.Stack[i + 5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - s.CX = x3; s.CY = y3; - i += 6; - } - s.ClearStack(); - } - - private static void DoHHCurveTo(InterpState s) - { - // |- dy1? {dxa dxb dyb dxc}+ hhcurveto |- - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - - if (count % 2 != 0) - { - // Odd: first arg is dy1 - double dy1 = s.Stack[i]; - double x1 = curX + s.Stack[i + 1]; double y1 = curY + dy1; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2 + s.Stack[i + 4]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - i += 5; count -= 5; - } - - while (count >= 4) - { - double x1 = curX + s.Stack[i]; double y1 = curY; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2 + s.Stack[i + 3]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - i += 4; count -= 4; - } - - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - private static void DoVVCurveTo(InterpState s) - { - // |- dx1? {dya dxb dyb dyc}+ vvcurveto |- - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - - if (count % 2 != 0) - { - // Odd: first arg is dx1 - double dx1 = s.Stack[i]; - double x1 = curX + dx1; double y1 = curY + s.Stack[i + 1]; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2; double y3 = y2 + s.Stack[i + 4]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - i += 5; count -= 5; - } - - while (count >= 4) - { - double x1 = curX; double y1 = curY + s.Stack[i]; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2; double y3 = y2 + s.Stack[i + 3]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - i += 4; count -= 4; - } - - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - private static void DoHVCurveTo(InterpState s) - { - // |- {dxa dxb dyb dyc dyd dxe dye dxf}+ dyf? (rem 0/1) - // |- dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf? (rem 4/5) - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - int rem = count % 8; - - if (rem == 4 || rem == 5) - { - // First curve: h → v (dx1 dx2 dy2 dy3) - if (count == 5) - { - double x1 = curX + s.Stack[0]; double y1 = curY; - double x2 = x1 + s.Stack[1]; double y2 = y1 + s.Stack[2]; - double x3 = x2 + s.Stack[4]; double y3 = y2 + s.Stack[3]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 5; count -= 5; - } - else - { - double x1 = curX + s.Stack[0]; double y1 = curY; - double x2 = x1 + s.Stack[1]; double y2 = y1 + s.Stack[2]; - double x3 = x2; double y3 = y2 + s.Stack[3]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 4; count -= 4; - } - // Remaining curves alternate v→h then h→v - while (count >= 8) - { - // v → h - double x1 = curX; double y1 = curY + s.Stack[i]; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2 + s.Stack[i + 3]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - // h → v - if (count == 9) - { - x1 = curX + s.Stack[i + 4]; y1 = curY; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 8]; y3 = y2 + s.Stack[i + 7]; - } - else - { - x1 = curX + s.Stack[i + 4]; y1 = curY; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2; y3 = y2 + s.Stack[i + 7]; - } - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 8; count -= 8; - } - } - else // rem == 0 or 1 - { - while (count >= 8) - { - // h → v - double x1 = curX + s.Stack[i]; double y1 = curY; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2; double y3 = y2 + s.Stack[i + 3]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - // v → h - if (count == 9) - { - x1 = curX; y1 = curY + s.Stack[i + 4]; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 7]; y3 = y2 + s.Stack[i + 8]; - } - else - { - x1 = curX; y1 = curY + s.Stack[i + 4]; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 7]; y3 = y2; - } - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 8; count -= 8; - } - } - - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - private static void DoVHCurveTo(InterpState s) - { - // |- {dya dxb dyb dxc dxd dxe dye dyf}+ dxf? (rem 0/1) - // |- dy1 dx2 dy2 dx3 {dxa dxb dyb dyc dyd dxe dye dxf}* dyf? (rem 4/5) - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - int rem = count % 8; - - if (rem == 4 || rem == 5) - { - // First curve: v → h (dy1 dx2 dy2 dx3) - if (count == 5) - { - double x1 = curX; double y1 = curY + s.Stack[0]; - double x2 = x1 + s.Stack[1]; double y2 = y1 + s.Stack[2]; - double x3 = x2 + s.Stack[3]; double y3 = y2 + s.Stack[4]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 5; count -= 5; - } - else - { - double x1 = curX; double y1 = curY + s.Stack[0]; - double x2 = x1 + s.Stack[1]; double y2 = y1 + s.Stack[2]; - double x3 = x2 + s.Stack[3]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 4; count -= 4; - } - // Remaining alternate h→v then v→h - while (count >= 8) - { - // h → v - double x1 = curX + s.Stack[i]; double y1 = curY; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2; double y3 = y2 + s.Stack[i + 3]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - // v → h - if (count == 9) - { - x1 = curX; y1 = curY + s.Stack[i + 4]; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 7]; y3 = y2 + s.Stack[i + 8]; - } - else - { - x1 = curX; y1 = curY + s.Stack[i + 4]; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 7]; y3 = y2; - } - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 8; count -= 8; - } - } - else // rem == 0 or 1 - { - while (count >= 8) - { - // v → h - double x1 = curX; double y1 = curY + s.Stack[i]; - double x2 = x1 + s.Stack[i + 1]; double y2 = y1 + s.Stack[i + 2]; - double x3 = x2 + s.Stack[i + 3]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - // h → v - if (count == 9) - { - x1 = curX + s.Stack[i + 4]; y1 = curY; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2 + s.Stack[i + 8]; y3 = y2 + s.Stack[i + 7]; - } - else - { - x1 = curX + s.Stack[i + 4]; y1 = curY; - x2 = x1 + s.Stack[i + 5]; y2 = y1 + s.Stack[i + 6]; - x3 = x2; y3 = y2 + s.Stack[i + 7]; - } - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 8; count -= 8; - } - } - - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - private static void DoRCurveLine(InterpState s) - { - // |- {dxa dya dxb dyb dxc dyc}+ dxd dyd rcurveline |- - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - while (count > 2) - { - if (count == 8) // last group is the lineto - { - double x1 = curX + s.Stack[i]; double y1 = curY + s.Stack[i + 1]; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2 + s.Stack[i + 4]; double y3 = y2 + s.Stack[i + 5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 6; count -= 6; - break; - } - if (count < 8) - { - // Remaining 6 are the last curve + the final 2 are the line - double x1 = curX + s.Stack[i]; double y1 = curY + s.Stack[i + 1]; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2 + s.Stack[i + 4]; double y3 = y2 + s.Stack[i + 5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; i += 6; count -= 6; - break; - } - double ax1 = curX + s.Stack[i]; double ay1 = curY + s.Stack[i + 1]; - double ax2 = ax1 + s.Stack[i + 2]; double ay2 = ay1 + s.Stack[i + 3]; - double ax3 = ax2 + s.Stack[i + 4]; double ay3 = ay2 + s.Stack[i + 5]; - s.Painter.CurveTo(new CurveTo(ax1, ay1, ax2, ay2, ax3, ay3)); - curX = ax3; curY = ay3; i += 6; count -= 6; - } - // final lineto - if (i + 1 < s.Top) - { - curX += s.Stack[i]; curY += s.Stack[i + 1]; - s.Painter.LineTo(new LineTo(curX, curY)); - } - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - private static void DoRLineCurve(InterpState s) - { - // |- {dxa dya}+ dxb dyb dxc dyc dxd dyd rlinecurve |- - int i = 0, count = s.Top; - double curX = s.CX, curY = s.CY; - while (count > 6) - { - curX += s.Stack[i]; curY += s.Stack[i + 1]; - s.Painter.LineTo(new LineTo(curX, curY)); - i += 2; count -= 2; - } - // Final rrcurveto - if (i + 5 < s.Top) - { - double x1 = curX + s.Stack[i]; double y1 = curY + s.Stack[i + 1]; - double x2 = x1 + s.Stack[i + 2]; double y2 = y1 + s.Stack[i + 3]; - double x3 = x2 + s.Stack[i + 4]; double y3 = y2 + s.Stack[i + 5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - curX = x3; curY = y3; - } - s.CX = curX; s.CY = curY; - s.ClearStack(); - } - - // ── Flex operators ──────────────────────────────────────────────────── - - private static void ExecFlex(InterpState s) - { - // dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd - // Two rrcurveto segments; fd (flex depth) ignored. - if (s.Top < 13) { s.ClearStack(); return; } - double curX = s.CX, curY = s.CY; - double x1 = curX + s.Stack[0]; double y1 = curY + s.Stack[1]; - double x2 = x1 + s.Stack[2]; double y2 = y1 + s.Stack[3]; - double x3 = x2 + s.Stack[4]; double y3 = y2 + s.Stack[5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - double x4 = x3 + s.Stack[6]; double y4 = y3 + s.Stack[7]; - double x5 = x4 + s.Stack[8]; double y5 = y4 + s.Stack[9]; - double x6 = x5 + s.Stack[10]; double y6 = y5 + s.Stack[11]; - s.Painter.CurveTo(new CurveTo(x4, y4, x5, y5, x6, y6)); - s.CX = x6; s.CY = y6; - s.ClearStack(); - } - - private static void ExecHFlex(InterpState s) - { - // dx1 dx2 dy2 dx3 dx4 dx5 dx6 - // All y-deltas for first/last control and endpoint are zero or implied. - if (s.Top < 7) { s.ClearStack(); return; } - double curX = s.CX, curY = s.CY; - double x1 = curX + s.Stack[0]; double y1 = curY; - double x2 = x1 + s.Stack[1]; double y2 = y1 + s.Stack[2]; - double x3 = x2 + s.Stack[3]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - double x4 = x3 + s.Stack[4]; double y4 = y3; - double x5 = x4 + s.Stack[5]; double y5 = curY; // same y as start - double x6 = x5 + s.Stack[6]; double y6 = curY; - s.Painter.CurveTo(new CurveTo(x4, y4, x5, y5, x6, y6)); - s.CX = x6; s.CY = y6; - s.ClearStack(); - } - - private static void ExecHFlex1(InterpState s) - { - // dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 - if (s.Top < 9) { s.ClearStack(); return; } - double curX = s.CX, curY = s.CY; - double x1 = curX + s.Stack[0]; double y1 = curY + s.Stack[1]; - double x2 = x1 + s.Stack[2]; double y2 = y1 + s.Stack[3]; - double x3 = x2 + s.Stack[4]; double y3 = y2; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - double x4 = x3 + s.Stack[5]; double y4 = y3; - double x5 = x4 + s.Stack[6]; double y5 = y4 + s.Stack[7]; - double x6 = x5 + s.Stack[8]; double y6 = curY; - s.Painter.CurveTo(new CurveTo(x4, y4, x5, y5, x6, y6)); - s.CX = x6; s.CY = y6; - s.ClearStack(); - } - - private static void ExecFlex1(InterpState s) - { - // dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 - // d6 is dx or dy depending on which direction moved more overall. - if (s.Top < 11) { s.ClearStack(); return; } - double curX = s.CX, curY = s.CY; - double x1 = curX + s.Stack[0]; double y1 = curY + s.Stack[1]; - double x2 = x1 + s.Stack[2]; double y2 = y1 + s.Stack[3]; - double x3 = x2 + s.Stack[4]; double y3 = y2 + s.Stack[5]; - s.Painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - double x4 = x3 + s.Stack[6]; double y4 = y3 + s.Stack[7]; - double x5 = x4 + s.Stack[8]; double y5 = y4 + s.Stack[9]; - // Determine d6 direction - double dx = x5 - curX, dy = y5 - curY; - double x6, y6; - if (Math.Abs(dx) > Math.Abs(dy)) - { x6 = x5 + s.Stack[10]; y6 = curY; } - else - { x6 = curX; y6 = y5 + s.Stack[10]; } - s.Painter.CurveTo(new CurveTo(x4, y4, x5, y5, x6, y6)); - s.CX = x6; s.CY = y6; - s.ClearStack(); - } - - // ── Interpreter state ───────────────────────────────────────────────── - - private sealed class InterpState - { - public readonly IGlyphOutlinePainter Painter; - public readonly double[] Stack = new double[48]; - public readonly double[] Storage = new double[32]; - public int Top; // stack top index (Stack[0..Top-1] are valid) - public double CX, CY; // current point - public double SX, SY; // start of current subpath (for ClosePath) - public int StemCount; - public bool FirstOpSeen; // true after first stem/moveto - public bool HasWidth; - public double Width; - public double NominalWidth; - public bool InPath; - public readonly byte[][]? LocalSubrs; - public readonly byte[][]? GlobalSubrs; - public readonly int LocalBias; - public readonly int GlobalBias; - - public InterpState(IGlyphOutlinePainter painter, CffPrivateDict priv, byte[][]? globalSubrs) - { - Painter = painter; - NominalWidth = priv.NominalWidthX; - Width = priv.DefaultWidthX; - LocalSubrs = priv.LocalSubrs; - GlobalSubrs = globalSubrs; - LocalBias = CalcBias(priv.LocalSubrs?.Length ?? 0); - GlobalBias = CalcBias(globalSubrs?.Length ?? 0); - } - - public void Push(double v) - { - if (Top < Stack.Length) Stack[Top++] = v; - } - - public double Pop() - { - if (Top == 0) return 0; - return Stack[--Top]; - } - - public double Peek() => Top > 0 ? Stack[Top - 1] : 0; - public double PeekAt(int fromTop) => (Top - 1 - fromTop) >= 0 ? Stack[Top - 1 - fromTop] : 0; - - public void ClearStack() => Top = 0; - - public void Roll(int n, int j) - { - if (n <= 0 || Top < n) return; - int start = Top - n; - j = ((j % n) + n) % n; // normalize - Reverse(start, Top - 1); - Reverse(start, start + j - 1); - Reverse(start + j, Top - 1); - } - - private void Reverse(int lo, int hi) - { - while (lo < hi) { double tmp = Stack[lo]; Stack[lo] = Stack[hi]; Stack[hi] = tmp; lo++; hi--; } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/FontFaceCollection.cs b/src/MiniPdf/Drawing/Font/Core/FontFaceCollection.cs deleted file mode 100644 index deab553a..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontFaceCollection.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Collections; -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// An ordered collection of font faces loaded from a font collection file (e.g. TTC). - /// - public sealed class FontFaceCollection : IReadOnlyList - { - private readonly IReadOnlyList _fonts; - - /// - /// Initializes a new from the specified list of fonts. - /// - /// The list of fonts in the collection. - public FontFaceCollection(IReadOnlyList fonts) - { - _fonts = fonts ?? throw new System.ArgumentNullException(nameof(fonts)); - } - - /// - public IFont this[int index] => _fonts[index]; - - /// - public int Count => _fonts.Count; - - /// - public IEnumerator GetEnumerator() => _fonts.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_fonts).GetEnumerator(); - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/FontFaceStyle.cs b/src/MiniPdf/Drawing/Font/Core/FontFaceStyle.cs deleted file mode 100644 index 917710ce..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontFaceStyle.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Describes the typographic style of a font face. - /// - public enum FontFaceStyle - { - /// - /// Normal font weight and style. - /// - Regular = 0, - - /// - /// Bold font weight. - /// - Bold = 1, - - /// - /// Italic font style. - /// - Italic = 2, - - /// - /// Bold and italic font weight and style. - /// - BoldItalic = 3, - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Font/Core/FontMetrics.cs b/src/MiniPdf/Drawing/Font/Core/FontMetrics.cs deleted file mode 100644 index f70cb873..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontMetrics.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Concrete, mutable implementation of . - /// Table parsers set the properties directly; glyph-width queries are - /// delegated to a resolver function supplied at construction time. - /// - public sealed class FontMetrics : IFontMetrics - { - private readonly Func _glyphWidthResolver; - - /// - /// A function that, given a , returns the advance - /// width of that glyph in design units. Called once per unique glyph; - /// callers are responsible for caching if needed. - /// - public FontMetrics(Func glyphWidthResolver) - { - _glyphWidthResolver = glyphWidthResolver - ?? throw new ArgumentNullException(nameof(glyphWidthResolver)); - } - - /// - public double Ascender { get; set; } - - /// - public double Descender { get; set; } - - /// - public double TypoAscender { get; set; } - - /// - public double TypoDescender { get; set; } - - /// - public double LineGap { get; set; } - - /// - public double UnitsPerEM { get; set; } - - /// - public double GetGlyphWidth(GlyphId glyphId) - { - if (glyphId is null) throw new ArgumentNullException(nameof(glyphId)); - return _glyphWidthResolver(glyphId); - } - - /// - public double UnderlinePosition { get; set; } - - /// - public double UnderlineThickness { get; set; } - - /// - public double StrikeoutPosition { get; set; } - - /// - public double StrikeoutSize { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/FontType.cs b/src/MiniPdf/Drawing/Font/Core/FontType.cs deleted file mode 100644 index ca570261..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontType.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Identifies the format of a font file. - /// - public enum FontType - { - /// TrueType font (.ttf). - TTF, - - /// OpenType font with TrueType outlines (.otf treated as TTF internally). - OTF, - - /// OpenType font with CFF/Type 2 outlines (.otf with "CFF " table). - CFF, - - /// Adobe Type 1 font (.pfb / .pfa). - Type1, - - /// Web Open Font Format 1 (.woff) — zlib-compressed sfnt tables. - WOFF, - - /// Web Open Font Format 2 (.woff2) — Brotli-compressed sfnt tables. - WOFF2, - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/FontVariationAxis.cs b/src/MiniPdf/Drawing/Font/Core/FontVariationAxis.cs deleted file mode 100644 index 803002af..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontVariationAxis.cs +++ /dev/null @@ -1,40 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Describes a single design-variation axis in a variable font (OpenType "fvar" table). - /// - public sealed class FontVariationAxis - { - /// Four-character axis tag, e.g. "wght", "wdth", "ital". - public string Tag { get; } - - /// Minimum user-space value along this axis. - public double MinValue { get; } - - /// Default user-space value along this axis. - public double DefaultValue { get; } - - /// Maximum user-space value along this axis. - public double MaxValue { get; } - - /// Human-readable name of the axis (resolved from well-known tags or the name table). - public string AxisName { get; } - - /// - /// Initializes a new with the specified parameters. - /// - /// Four-character axis tag, e.g. "wght", "wdth", "ital". - /// Minimum user-space value along this axis. - /// Default user-space value along this axis. - /// Maximum user-space value along this axis. - /// Human-readable name of the axis. - public FontVariationAxis(string tag, double minValue, double defaultValue, double maxValue, string axisName) - { - Tag = tag; - MinValue = minValue; - DefaultValue = defaultValue; - MaxValue = maxValue; - AxisName = axisName; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/FontVariationInstance.cs b/src/MiniPdf/Drawing/Font/Core/FontVariationInstance.cs deleted file mode 100644 index 444c38ea..00000000 --- a/src/MiniPdf/Drawing/Font/Core/FontVariationInstance.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Represents a named instance (a specific set of axis coordinates) in a variable font. - /// - public sealed class FontVariationInstance - { - /// Human-readable name for this instance (e.g. "Bold", "Light Condensed"). - public string Name { get; } - - /// - /// Per-axis coordinate values for this instance, keyed by axis tag (e.g. "wght" → 700.0). - /// - public IReadOnlyDictionary Coordinates { get; } - - /// - /// Initializes a new with the specified name and coordinates. - /// - /// Human-readable name for this instance. - /// Per-axis coordinate values for this instance. - public FontVariationInstance(string name, IReadOnlyDictionary coordinates) - { - Name = name; - Coordinates = coordinates; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/GlyphClass.cs b/src/MiniPdf/Drawing/Font/Core/GlyphClass.cs deleted file mode 100644 index 1c0a596c..00000000 --- a/src/MiniPdf/Drawing/Font/Core/GlyphClass.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// OpenType glyph classification as defined in the GDEF table (§6.3.1). - /// Ref: https://learn.microsoft.com/en-us/typography/opentype/spec/gdef - /// - public enum GlyphClass - { - /// Glyph is not assigned to any specific class. - Unclassified = 0, - - /// Base glyph — a single character that may have combining marks attached. - Base = 1, - - /// Ligature glyph — formed from two or more characters. - Ligature = 2, - - /// Combining mark glyph. - Mark = 3, - - /// Component glyph — part of a ligature not individually encoded. - Component = 4, - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/IFont.cs b/src/MiniPdf/Drawing/Font/Core/IFont.cs deleted file mode 100644 index 1d9c9c60..00000000 --- a/src/MiniPdf/Drawing/Font/Core/IFont.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Encoding; -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Represents a loaded font face and provides access to its metadata, metrics, - /// encoding map, and glyph data. - /// - public interface IFont - { - /// Full name of the font, e.g. "Montserrat Regular". - string FontName { get; } - - /// Family name of the font, e.g. "Montserrat". - string FontFamily { get; } - - /// Total number of glyphs in the font. - int NumGlyphs { get; } - - /// Typographic style of this font face. - FontFaceStyle Style { get; } - - /// Font-level metrics (ascender, descender, units per em, etc.). - IFontMetrics Metrics { get; } - - /// Encoding map that translates Unicode code points to glyph identifiers. - IFontEncoding Encoding { get; } - - /// Provides access to individual glyphs by identifier or index. - IGlyphAccessor GlyphAccessor { get; } - - /// Serialises the (possibly modified) font to . - void Save(Stream stream); - - /// Serialises the (possibly modified) font to the file at . - void Save(string filePath); - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/IFontMetrics.cs b/src/MiniPdf/Drawing/Font/Core/IFontMetrics.cs deleted file mode 100644 index 56531c42..00000000 --- a/src/MiniPdf/Drawing/Font/Core/IFontMetrics.cs +++ /dev/null @@ -1,68 +0,0 @@ -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Provides access to horizontal and typographic font metrics in design units. - /// - public interface IFontMetrics - { - /// - /// Maximum ascender value above the baseline, in design units (from hhea.Ascender). - /// - double Ascender { get; } - - /// - /// Maximum descender value below the baseline, in design units (from hhea.Descender, - /// typically negative). - /// - double Descender { get; } - - /// - /// Typographic ascender from the OS/2 sTypoAscender field, in design units. - /// - double TypoAscender { get; } - - /// - /// Typographic descender from the OS/2 sTypoDescender field, in design units - /// (typically negative). - /// - double TypoDescender { get; } - - /// - /// Line gap (leading) recommended by the font, in design units (from hhea.LineGap). - /// - double LineGap { get; } - - /// - /// Number of design units that make up one em square. - /// - double UnitsPerEM { get; } - - /// - /// Returns the horizontal advance width of the glyph identified by - /// , in design units. - /// - double GetGlyphWidth(GlyphId glyphId); - - // ── Decoration metrics (design units) ────────────────────────────────────── - - /// - /// Offset of the top of the underline stroke from the baseline, in design units - /// (from the 'post' table). Negative values place the underline below the baseline. - /// - double UnderlinePosition { get; } - - /// Thickness of the underline stroke, in design units (from the 'post' table). - double UnderlineThickness { get; } - - /// - /// Distance from the baseline to the top of the strikeout stroke, in design units - /// (from OS/2 yStrikeoutPosition). Positive values are above the baseline. - /// - double StrikeoutPosition { get; } - - /// Thickness of the strikeout stroke, in design units (from OS/2 yStrikeoutSize). - double StrikeoutSize { get; } - } -} diff --git a/src/MiniPdf/Drawing/Font/Core/LicenseFlags.cs b/src/MiniPdf/Drawing/Font/Core/LicenseFlags.cs deleted file mode 100644 index 3d4c57b8..00000000 --- a/src/MiniPdf/Drawing/Font/Core/LicenseFlags.cs +++ /dev/null @@ -1,78 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Core -{ - /// - /// Represents the embedding and licensing restrictions declared in the - /// OS/2 table's fsType field (OpenType spec §5.7). - /// - /// - /// Obtain an instance via TtfOs2Table.GetLicenseFlags(). - /// A null return from that method indicates the OS/2 table is absent. - /// When the instance is non-null but is true, - /// the font declares no embedding restrictions (fsType == 0). - /// - public sealed class LicenseFlags - { - /// Raw OS/2 fsType value. - public ushort FsType { get; } - - /// - /// Initializes a new instance from the specified fsType value. - /// - /// The raw OS/2 fsType value. - public LicenseFlags(ushort fsType) - { - FsType = fsType; - } - - // ── Embedding-type bits (bits 1–3 are the key restriction flags) ────── - - /// - /// True if fsType == 0, meaning the font declares no embedding - /// restrictions and may be freely embedded. - /// - public bool FSTypeAbsent => FsType == 0; - - /// - /// Bit 1 (mask 0x0002). The font must not be modified or embedded in any - /// manner without explicit permission of the legal owner. - /// - public bool IsRestrictedLicenseEmbedding => (FsType & 0x0002) != 0; - - /// - /// Bit 2 (mask 0x0004), bit 1 clear. The font may be embedded for preview - /// and print but must not be installed on the target system. - /// - public bool IsPreviewAndPrintEmbedding => - (FsType & 0x0004) != 0 && (FsType & 0x0002) == 0; - - /// - /// Bit 3 (mask 0x0008), bits 1–2 clear. The font may be embedded and - /// documents using it may be edited on the target system. - /// - public bool IsEditableEmbedding => - (FsType & 0x0008) != 0 && (FsType & 0x0006) == 0; - - /// - /// No restriction bits (1–3) are set; the font may be permanently installed - /// on target systems (installable embedding). - /// - public bool IsInstallableEmbedding => - !FSTypeAbsent - && !IsRestrictedLicenseEmbedding - && !IsPreviewAndPrintEmbedding - && !IsEditableEmbedding; - - // ── Additional flags ────────────────────────────────────────────────── - - /// - /// Bit 8 (mask 0x0100). The font may not be subsetted prior to embedding. - /// - public bool NoSubsetting => (FsType & 0x0100) != 0; - - /// - /// Bit 9 (mask 0x0200). Only bitmaps contained in the font may be embedded; - /// no outline data may be embedded. - /// - public bool BitmapEmbeddingOnly => (FsType & 0x0200) != 0; - } -} diff --git a/src/MiniPdf/Drawing/Font/Encoding/IFontEncoding.cs b/src/MiniPdf/Drawing/Font/Encoding/IFontEncoding.cs deleted file mode 100644 index e33b3df2..00000000 --- a/src/MiniPdf/Drawing/Font/Encoding/IFontEncoding.cs +++ /dev/null @@ -1,72 +0,0 @@ -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Encoding -{ - /// - /// Maps Unicode code points (and characters) to glyph identifiers within a font. - /// Typically backed by a CMap subtable selected from the font's "cmap" table. - /// - public interface IFontEncoding - { - /// - /// Resolves the Unicode to a glyph identifier. - /// Returns when the font has no glyph - /// for the given code point, or null when the encoding map is absent. - /// - GlyphId? DecodeToGid(uint codePoint); - - /// - /// Convenience overload that accepts a (UTF-16 BMP code unit). - /// For code points outside the BMP, use directly. - /// - GlyphId? DecodeToGid(char ch); - - /// - /// Returns true when the font provides a real glyph (not .notdef) - /// for . Used by the fallback resolver to decide - /// whether to substitute a fallback font. - /// - /// The Unicode code point to test. - /// - /// When this method returns true, the resolved glyph identifier; otherwise 0. - /// - bool TryGetGlyph(uint codePoint, out uint glyphId); - - /// - /// Returns true when the font provides a real glyph (not .notdef) - /// for . - /// - bool HasGlyph(uint codePoint); - } - - /// - /// Default implementation of and - /// that derives coverage from - /// . Implementers that can - /// distinguish "no cmap entry" from "cmap entry → glyph 0" should override - /// these methods directly. - /// - public static class FontEncodingDefaults - { - /// - /// Default implementation. - /// - public static bool TryGetGlyph(IFontEncoding encoding, uint codePoint, out uint glyphId) - { - var gid = encoding.DecodeToGid(codePoint); - if (gid is GlyphUInt32Id u32 && u32.Value != 0) - { - glyphId = u32.Value; - return true; - } - glyphId = 0; - return false; - } - - /// - /// Default implementation. - /// - public static bool HasGlyph(IFontEncoding encoding, uint codePoint) - => TryGetGlyph(encoding, codePoint, out _); - } -} diff --git a/src/MiniPdf/Drawing/Font/Encoding/NullEncoding.cs b/src/MiniPdf/Drawing/Font/Encoding/NullEncoding.cs deleted file mode 100644 index e7624715..00000000 --- a/src/MiniPdf/Drawing/Font/Encoding/NullEncoding.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Encoding -{ - /// - /// A no-op encoding that always returns . - /// Used as a placeholder before a real CMap table is parsed. - /// - public sealed class NullEncoding : IFontEncoding - { - /// Shared singleton instance. - public static readonly NullEncoding Instance = new NullEncoding(); - - private NullEncoding() { } - - /// - public GlyphId? DecodeToGid(uint codePoint) => GlyphUInt32Id.NotDefId; - - /// - public GlyphId? DecodeToGid(char ch) => GlyphUInt32Id.NotDefId; - - /// - public bool TryGetGlyph(uint codePoint, out uint glyphId) - { - glyphId = 0; - return false; - } - - /// - public bool HasGlyph(uint codePoint) => false; - } -} diff --git a/src/MiniPdf/Drawing/Font/Encoding/TtfUnicodeEncoding.cs b/src/MiniPdf/Drawing/Font/Encoding/TtfUnicodeEncoding.cs deleted file mode 100644 index 93afef4f..00000000 --- a/src/MiniPdf/Drawing/Font/Encoding/TtfUnicodeEncoding.cs +++ /dev/null @@ -1,49 +0,0 @@ -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Ttf.Tables; - -namespace MiniSoftware.Drawing.Font.Encoding -{ - /// - /// Implements by delegating to a CMap format subtable - /// () selected from a TrueType/OpenType font's - /// "cmap" table. - /// - public sealed class TtfUnicodeEncoding : IFontEncoding - { - private readonly TtfCMapFormatBaseTable _cmapTable; - - /// - /// The best Unicode-capable subtable as returned by - /// . - /// Must not be null. - /// - public TtfUnicodeEncoding(TtfCMapFormatBaseTable cmapTable) - { - _cmapTable = cmapTable; - } - - /// - /// - /// Returns (glyph index 0) for code - /// points not present in the font. - /// - public GlyphId? DecodeToGid(uint codePoint) - { - uint glyphIndex = _cmapTable.GetGlyphIndex(codePoint); - return new GlyphUInt32Id(glyphIndex); - } - - /// - public GlyphId? DecodeToGid(char ch) => DecodeToGid((uint)ch); - - /// - public bool TryGetGlyph(uint codePoint, out uint glyphId) - { - glyphId = _cmapTable.GetGlyphIndex(codePoint); - return glyphId != 0; - } - - /// - public bool HasGlyph(uint codePoint) => _cmapTable.GetGlyphIndex(codePoint) != 0; - } -} diff --git a/src/MiniPdf/Drawing/Font/FontFactory.cs b/src/MiniPdf/Drawing/Font/FontFactory.cs deleted file mode 100644 index 3bcfbd0f..00000000 --- a/src/MiniPdf/Drawing/Font/FontFactory.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Cff; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.IO; -using MiniSoftware.Drawing.Font.Sources; -using MiniSoftware.Drawing.Font.Ttf; -using MiniSoftware.Drawing.Font.Type1; - -namespace MiniSoftware.Drawing.Font -{ - /// - /// Entry point for loading fonts. Dispatches to the appropriate reader - /// based on and the stream magic bytes. - /// - public static class FontFactory - { - /// - /// Opens a single font face from the supplied . - /// - /// - /// An implementation appropriate for the font type - /// (e.g. TtfFont, CffFont, Type1Font). - /// - /// - /// is null. - /// - /// - /// The font format is not yet supported. - /// - /// - /// The font data is corrupt or cannot be parsed. - /// - public static IFont Open(FontDefinition definition) - { - if (definition is null) throw new ArgumentNullException(nameof(definition)); - - var source = definition.FileDefinitions[0].Source; - using var stream = source.GetFontStream(); - - switch (definition.FontType) - { - case FontType.TTF: - case FontType.OTF: - return TtfFontReader.Read(stream); - - case FontType.CFF: - return CffFontReader.Read(stream); - - case FontType.Type1: - return new Type1Font(Type1Parser.Parse(ReadAllBytes(stream))); - - case FontType.WOFF: - { - byte[] sfntBytes = WoffReader.Decompress(stream); - using var sfntStream = new MemoryStream(sfntBytes); - return TtfFontReader.Read(sfntStream); - } - - case FontType.WOFF2: - // WoffReader.Decompress always throws NotSupportedException on netstandard2.0. - Woff2Reader.Decompress(stream); - // unreachable - throw new InvalidOperationException("Unreachable."); - - default: - throw new NotSupportedException( - $"Font format '{definition.FontType}' is not yet implemented."); - } - } - - /// - /// Opens all font faces from a font collection file (TTC). - /// - /// - /// A containing one per face. - /// - public static FontFaceCollection OpenCollection(IStreamSource source) - { - if (source is null) throw new ArgumentNullException(nameof(source)); - - using var stream = source.GetFontStream(); - byte[] data = ReadAllBytes(stream); - - if (data.Length < 4) - throw new InvalidOperationException("Font data is too short to identify the format."); - - uint magic = ((uint)data[0] << 24) | ((uint)data[1] << 16) - | ((uint)data[2] << 8) | data[3]; - - if (magic == TtcReader.Signature) - { - using var ttcStream = new MemoryStream(data, writable: false); - return new FontFaceCollection(TtcReader.Read(ttcStream)); - } - - // Single-font file — detect format and wrap in a one-element collection. - IFont single = OpenSingleFontFromBytes(magic, data); - return new FontFaceCollection(new[] { single }); - } - - // Opens a single IFont from already-buffered bytes, dispatching on magic. - // FontStreamReader.Detect handles WOFF decompression internally and returns - // the inner sfnt bytes with TTF/OTF type — no separate WOFF case needed. - private static IFont OpenSingleFontFromBytes(uint magic, byte[] data) - { - var (fontBytes, detectedType) = FontStreamReader.Detect(data); - - switch (detectedType) - { - case FontType.TTF: - case FontType.OTF: - { - using var ms = new MemoryStream(fontBytes, writable: false); - return TtfFontReader.Read(ms); - } - - case FontType.CFF: - { - using var ms = new MemoryStream(fontBytes, writable: false); - return CffFontReader.Read(ms); - } - - case FontType.Type1: - return new Type1Font(Type1Parser.Parse(fontBytes)); - - default: - throw new NotSupportedException( - $"Font format (magic 0x{magic:X8}) is not yet supported in OpenCollection."); - } - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static byte[] ReadAllBytes(System.IO.Stream stream) - { - using var ms = new System.IO.MemoryStream(); - stream.CopyTo(ms); - return ms.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Glyphs/Glyph.cs b/src/MiniPdf/Drawing/Font/Glyphs/Glyph.cs deleted file mode 100644 index bf142c79..00000000 --- a/src/MiniPdf/Drawing/Font/Glyphs/Glyph.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Glyphs -{ - /// - /// Represents a single glyph with its metrics and bounding box. - /// Obtain instances via . - /// - public sealed class Glyph - { - /// - /// Initializes a new with the specified identifier, bounding box, and advance width. - /// - /// The identifier of this glyph within its font. - /// Axis-aligned bounding box of the glyph outline, in design units. - /// Horizontal advance width in design units. - public Glyph(GlyphId id, GlyphBoundingBox glyphBBox, double advanceWidth) - { - Id = id ?? throw new ArgumentNullException(nameof(id)); - GlyphBBox = glyphBBox ?? throw new ArgumentNullException(nameof(glyphBBox)); - AdvanceWidth = advanceWidth; - } - - /// The identifier of this glyph within its font. - public GlyphId Id { get; } - - /// Axis-aligned bounding box of the glyph outline, in design units. - public GlyphBoundingBox GlyphBBox { get; } - - /// - /// Horizontal advance width in design units (how far the text cursor moves after - /// rendering this glyph). - /// - public double AdvanceWidth { get; } - - /// - /// Returns a string representation of this glyph. - /// - public override string ToString() => - $"Glyph({Id}, AdvW={AdvanceWidth}, {GlyphBBox})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Glyphs/GlyphBoundingBox.cs b/src/MiniPdf/Drawing/Font/Glyphs/GlyphBoundingBox.cs deleted file mode 100644 index 5b6b35ae..00000000 --- a/src/MiniPdf/Drawing/Font/Glyphs/GlyphBoundingBox.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Glyphs -{ - /// - /// Axis-aligned bounding box of a glyph outline, in design units. - /// - public sealed class GlyphBoundingBox - { - /// - /// An empty bounding box with zero dimensions. - /// - public static readonly GlyphBoundingBox Empty = new GlyphBoundingBox(0, 0, 0, 0); - - /// - /// Initializes a new with the specified coordinates. - /// - /// Leftmost x-coordinate of the glyph outline. - /// Bottommost y-coordinate of the glyph outline. - /// Rightmost x-coordinate of the glyph outline. - /// Topmost y-coordinate of the glyph outline. - public GlyphBoundingBox(double xMin, double yMin, double xMax, double yMax) - { - XMin = xMin; - YMin = yMin; - XMax = xMax; - YMax = yMax; - } - - /// Leftmost x-coordinate of the glyph outline. - public double XMin { get; } - - /// Bottommost y-coordinate of the glyph outline. - public double YMin { get; } - - /// Rightmost x-coordinate of the glyph outline. - public double XMax { get; } - - /// Topmost y-coordinate of the glyph outline. - public double YMax { get; } - - /// Width of the bounding box (XMax − XMin). - public double Width => XMax - XMin; - - /// Height of the bounding box (YMax − YMin). - public double Height => YMax - YMin; - - /// - /// Returns a string representation of this bounding box. - /// - public override string ToString() => - $"BBox(XMin={XMin}, YMin={YMin}, XMax={XMax}, YMax={YMax})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Glyphs/GlyphId.cs b/src/MiniPdf/Drawing/Font/Glyphs/GlyphId.cs deleted file mode 100644 index 231cf2af..00000000 --- a/src/MiniPdf/Drawing/Font/Glyphs/GlyphId.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Glyphs -{ - /// - /// Abstract base class for all glyph identifiers. - /// Concrete implementations: (index-based). - /// - public abstract class GlyphId - { - // Prevent instantiation outside this assembly hierarchy. - internal GlyphId() { } - - /// - public abstract override bool Equals(object? obj); - - /// - public abstract override int GetHashCode(); - - /// - /// Determines whether two instances are equal. - /// - public static bool operator ==(GlyphId? left, GlyphId? right) - { - if (ReferenceEquals(left, right)) return true; - if (left is null || right is null) return false; - return left.Equals(right); - } - - /// - /// Determines whether two instances are not equal. - /// - public static bool operator !=(GlyphId? left, GlyphId? right) => !(left == right); - } -} diff --git a/src/MiniPdf/Drawing/Font/Glyphs/GlyphUInt32Id.cs b/src/MiniPdf/Drawing/Font/Glyphs/GlyphUInt32Id.cs deleted file mode 100644 index 62f72a8d..00000000 --- a/src/MiniPdf/Drawing/Font/Glyphs/GlyphUInt32Id.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Glyphs -{ - /// - /// A glyph identifier backed by an unsigned 32-bit glyph index, - /// as used in TrueType, OpenType and CFF fonts. - /// - public sealed class GlyphUInt32Id : GlyphId - { - /// - /// The sentinel value that represents the ".notdef" glyph (index 0). - /// Encoding lookups return this when the requested code point has no mapping. - /// - public static readonly GlyphUInt32Id NotDefId = new GlyphUInt32Id(0); - - /// Zero-based glyph index within the font. - public uint Value { get; } - - /// - /// Initializes a new with the specified glyph index. - /// - /// Zero-based glyph index within the font. - public GlyphUInt32Id(uint value) - { - Value = value; - } - - /// - public override bool Equals(object? obj) => - obj is GlyphUInt32Id other && other.Value == Value; - - /// - public override int GetHashCode() => Value.GetHashCode(); - - /// - public override string ToString() => $"GlyphId({Value})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Glyphs/IGlyphAccessor.cs b/src/MiniPdf/Drawing/Font/Glyphs/IGlyphAccessor.cs deleted file mode 100644 index be4b6df5..00000000 --- a/src/MiniPdf/Drawing/Font/Glyphs/IGlyphAccessor.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Glyphs -{ - /// - /// Provides access to individual glyphs within a font. - /// - public interface IGlyphAccessor - { - /// - /// Returns the for the given , - /// or null if the glyph is not present in the font. - /// - Glyph? GetGlyphById(GlyphId glyphId); - - /// - /// Returns the for the given zero-based glyph - /// , or null if out of range. - /// - Glyph? GetGlyphByIndex(uint index); - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/FontBinaryReader.cs b/src/MiniPdf/Drawing/Font/IO/FontBinaryReader.cs deleted file mode 100644 index 87bd6f72..00000000 --- a/src/MiniPdf/Drawing/Font/IO/FontBinaryReader.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.IO; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// A big-endian binary reader for OpenType/TrueType font data. - /// All multi-byte integers are read in network byte order (most-significant byte first), - /// as required by the OpenType specification. - /// - public sealed class FontBinaryReader : IDisposable - { - private readonly BinaryReader _reader; - private readonly bool _leaveOpen; - - /// The stream to read from. Must support seeking. - /// - /// When true the underlying stream is NOT disposed when this reader is disposed. - /// Use this when the stream's lifetime is managed by an outer scope. - /// - public FontBinaryReader(Stream stream, bool leaveOpen = false) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - _reader = new BinaryReader(stream, SysEncoding.ASCII, leaveOpen: true); - _leaveOpen = leaveOpen; - } - - // ── Stream control ──────────────────────────────────────────────────── - - /// Current byte position within the underlying stream. - public long Position => _reader.BaseStream.Position; - - /// Total length of the underlying stream in bytes. - public long Length => _reader.BaseStream.Length; - - /// Seeks to an absolute byte offset from the beginning of the stream. - public void Seek(long offset) => - _reader.BaseStream.Seek(offset, SeekOrigin.Begin); - - /// Advances the read position by bytes. - public void Skip(int count) => - _reader.BaseStream.Seek(count, SeekOrigin.Current); - - // ── Primitive reads (big-endian) ────────────────────────────────────── - - /// Reads one unsigned byte. - public byte ReadUInt8() => _reader.ReadByte(); - - /// Reads an unsigned 16-bit integer (big-endian). - public ushort ReadUInt16() - { - uint b0 = _reader.ReadByte(); - uint b1 = _reader.ReadByte(); - return (ushort)((b0 << 8) | b1); - } - - /// Reads a signed 16-bit integer (big-endian). - public short ReadInt16() => (short)ReadUInt16(); - - /// Reads an unsigned 32-bit integer (big-endian). - public uint ReadUInt32() - { - uint b0 = _reader.ReadByte(); - uint b1 = _reader.ReadByte(); - uint b2 = _reader.ReadByte(); - uint b3 = _reader.ReadByte(); - return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; - } - - /// Reads a signed 32-bit integer (big-endian). - public int ReadInt32() => (int)ReadUInt32(); - - /// - /// Reads a signed 64-bit integer (big-endian). - /// Used for LONGDATETIME fields (e.g. head.created / head.modified). - /// - public long ReadInt64() - { - ulong hi = ReadUInt32(); - ulong lo = ReadUInt32(); - return (long)((hi << 32) | lo); - } - - // ── Fixed-point reads ───────────────────────────────────────────────── - - /// - /// Reads a 16.16 fixed-point number (signed 32-bit integer divided by 65536). - /// Used for the sfVersion field, post.italicAngle, etc. - /// - public double ReadFixed() => ReadInt32() / 65536.0; - - /// - /// Reads a 2.14 fixed-point number (signed 16-bit integer divided by 16384). - /// Used for normalised variation coordinates in gvar/avar. - /// - public double ReadF2Dot14() => ReadInt16() / 16384.0; - - // ── Composite reads ─────────────────────────────────────────────────── - - /// - /// Reads a 4-byte ASCII tag string (e.g. "head", "cmap", "OTTO"). - /// - public string ReadTag() - { - byte[] bytes = _reader.ReadBytes(4); - return SysEncoding.ASCII.GetString(bytes); - } - - /// Reads exactly bytes from the current position. - public byte[] ReadBytes(int count) => _reader.ReadBytes(count); - - // ── IDisposable ─────────────────────────────────────────────────────── - - /// - public void Dispose() - { - if (_leaveOpen) - // Only dispose the BinaryReader wrapper, not the underlying stream. - // BinaryReader.Dispose(false) is private, so we just suppress finalisation. - GC.SuppressFinalize(this); - else - _reader.Dispose(); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/FontBinaryWriter.cs b/src/MiniPdf/Drawing/Font/IO/FontBinaryWriter.cs deleted file mode 100644 index 40bb5112..00000000 --- a/src/MiniPdf/Drawing/Font/IO/FontBinaryWriter.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.IO; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// A big-endian binary writer for OpenType/TrueType font data. - /// All multi-byte integers are written in network byte order (most-significant byte first), - /// as required by the OpenType specification. - /// - public sealed class FontBinaryWriter : IDisposable - { - private readonly BinaryWriter _writer; - private readonly bool _leaveOpen; - - /// The stream to write to. - /// - /// When true the underlying stream is NOT disposed when this writer is disposed. - /// - public FontBinaryWriter(Stream stream, bool leaveOpen = false) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - _writer = new BinaryWriter(stream, SysEncoding.ASCII, leaveOpen: true); - _leaveOpen = leaveOpen; - } - - // ── Stream control ──────────────────────────────────────────────────── - - /// Current byte position within the underlying stream. - public long Position => _writer.BaseStream.Position; - - /// Seeks to an absolute byte offset from the beginning of the stream. - public void Seek(long offset) => - _writer.BaseStream.Seek(offset, SeekOrigin.Begin); - - /// - /// Pads the current position forward with zero bytes until the stream position - /// is aligned to a 4-byte boundary. No-op when already aligned. - /// Required by OpenType: every table must begin on a 4-byte boundary. - /// - public void Align4() - { - long pos = _writer.BaseStream.Position; - int rem = (int)(pos % 4); - if (rem != 0) - { - for (int i = 0; i < 4 - rem; i++) - _writer.Write((byte)0); - } - } - - // ── Primitive writes (big-endian) ───────────────────────────────────── - - /// Writes one unsigned byte. - public void WriteUInt8(byte value) => _writer.Write(value); - - /// Writes an unsigned 16-bit integer (big-endian). - public void WriteUInt16(ushort value) - { - _writer.Write((byte)(value >> 8)); - _writer.Write((byte)(value & 0xFF)); - } - - /// Writes a signed 16-bit integer (big-endian). - public void WriteInt16(short value) => WriteUInt16((ushort)value); - - /// Writes an unsigned 32-bit integer (big-endian). - public void WriteUInt32(uint value) - { - _writer.Write((byte)((value >> 24) & 0xFF)); - _writer.Write((byte)((value >> 16) & 0xFF)); - _writer.Write((byte)((value >> 8) & 0xFF)); - _writer.Write((byte)( value & 0xFF)); - } - - /// Writes a signed 32-bit integer (big-endian). - public void WriteInt32(int value) => WriteUInt32((uint)value); - - /// Writes a signed 64-bit integer (big-endian). - public void WriteInt64(long value) - { - WriteUInt32((uint)((ulong)value >> 32)); - WriteUInt32((uint)((ulong)value & 0xFFFFFFFF)); - } - - // ── Fixed-point writes ──────────────────────────────────────────────── - - /// Writes a 16.16 fixed-point number. - public void WriteFixed(double value) => WriteInt32((int)(value * 65536.0)); - - /// Writes a 2.14 fixed-point number. - public void WriteF2Dot14(double value) => WriteInt16((short)(value * 16384.0)); - - // ── Composite writes ────────────────────────────────────────────────── - - /// - /// Writes a 4-byte ASCII tag. If is shorter than - /// 4 characters it is right-padded with spaces; if longer it is truncated. - /// - public void WriteTag(string tag) - { - if (tag is null) throw new ArgumentNullException(nameof(tag)); - byte[] bytes = SysEncoding.ASCII.GetBytes(tag.PadRight(4).Substring(0, 4)); - _writer.Write(bytes); - } - - /// Writes a raw byte array verbatim. - public void WriteBytes(byte[] data) - { - if (data is null) throw new ArgumentNullException(nameof(data)); - _writer.Write(data); - } - - /// Flushes the underlying stream. - public void Flush() => _writer.Flush(); - - // ── IDisposable ─────────────────────────────────────────────────────── - - /// - public void Dispose() - { - if (!_leaveOpen) - _writer.Dispose(); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/FontStreamReader.cs b/src/MiniPdf/Drawing/Font/IO/FontStreamReader.cs deleted file mode 100644 index 683a4ef9..00000000 --- a/src/MiniPdf/Drawing/Font/IO/FontStreamReader.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Core; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// Reads the magic bytes of a font data buffer to identify its format, - /// decompresses WOFF containers as needed, and returns the raw sfnt bytes - /// together with the detected . - /// - /// - /// Supported magic values: - /// - /// 0x00010000TrueType 1.0 - /// 0x74727565 ('true')Apple TrueType - /// 0x4F54544F ('OTTO')OpenType/CFF - /// 0x74746366 ('ttcf')TrueType Collection (Batch 12) - /// 0x774F4646 ('wOFF')WOFF 1.0 — decompressed inline - /// 0x774F4632 ('wOF2')WOFF 2.0 — NotSupportedException on netstandard2.0 - /// - /// - internal static class FontStreamReader - { - // sfnt magic constants - private const uint MagicTTF = 0x00010000u; // TrueType 1.0 - private const uint MagicTRUE = 0x74727565u; // 'true' (Apple TrueType) - private const uint MagicOTF = 0x4F54544Fu; // 'OTTO' (OpenType/CFF) - private const uint MagicTTC = 0x74746366u; // 'ttcf' (TTC collection) - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Reads from its current position, identifies the - /// font format, decompresses WOFF if needed, and returns the sfnt bytes. - /// - /// - /// The raw sfnt bytes (or original bytes for uncompressed formats) and the - /// detected . - /// - /// - /// The format magic bytes are not recognised. - /// - /// - /// WOFF2 was detected (requires .NET 6+), or TTC was detected (use - /// FontFactory.OpenCollection for collections). - /// - internal static (byte[] FontBytes, FontType DetectedType) Detect(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - - using var ms = new MemoryStream(); - stream.CopyTo(ms); - return Detect(ms.ToArray()); - } - - /// - /// Identifies the font format from , decompresses WOFF - /// if needed, and returns the raw sfnt bytes. - /// - internal static (byte[] FontBytes, FontType DetectedType) Detect(byte[] data) - { - if (data is null) throw new ArgumentNullException(nameof(data)); - if (data.Length < 4) - throw new InvalidOperationException( - "Data is too short to identify font format (need at least 4 bytes)."); - - uint magic = ((uint)data[0] << 24) | ((uint)data[1] << 16) - | ((uint)data[2] << 8) | data[3]; - - switch (magic) - { - case MagicTTF: - case MagicTRUE: - return (data, FontType.TTF); - - case MagicOTF: - return (data, FontType.OTF); - - case MagicTTC: - throw new NotSupportedException( - "TrueType Collections (TTC) must be opened via FontFactory.OpenCollection, " + - "not FontFactory.Open. (Full TTC support arrives in Batch 12.)"); - - case WoffReader.Signature: - { - byte[] sfnt = WoffReader.Decompress(data); - - // Determine inner type from sfnt magic. - uint innerMagic = ((uint)sfnt[0] << 24) | ((uint)sfnt[1] << 16) - | ((uint)sfnt[2] << 8) | sfnt[3]; - - FontType innerType = innerMagic == MagicOTF ? FontType.OTF : FontType.TTF; - return (sfnt, innerType); - } - - case Woff2Reader.Signature: - // Propagate the descriptive NotSupportedException from Woff2Reader. - Woff2Reader.Decompress(data); - // unreachable — Decompress always throws - throw new InvalidOperationException("Unreachable."); - - default: - // Adobe Type 1 PFB: first byte 0x80, second byte 0x01 - if (data[0] == 0x80 && data[1] == 0x01) - return (data, FontType.Type1); - - throw new InvalidOperationException( - $"Unrecognised font format (magic bytes 0x{magic:X8})."); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/OpenTypeOffsetTable.cs b/src/MiniPdf/Drawing/Font/IO/OpenTypeOffsetTable.cs deleted file mode 100644 index 0183fb40..00000000 --- a/src/MiniPdf/Drawing/Font/IO/OpenTypeOffsetTable.cs +++ /dev/null @@ -1,89 +0,0 @@ -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// The OpenType offset table (the first 12 bytes of every sfnt-based font file). - /// It describes the font's table directory and is used to locate each font table. - /// - public sealed class OpenTypeOffsetTable - { - // ── Well-known sfVersion magic values ──────────────────────────────── - - /// 0x00010000 — Standard TrueType / OpenType with TrueType outlines. - public const uint SfVersionTrueType = 0x00010000u; - - /// 0x4F54544F — "OTTO" — OpenType font with CFF/Type 2 outlines. - public const uint SfVersionCff = 0x4F54544Fu; - - /// 0x74727565 — "true" — Apple TrueType. - public const uint SfVersionAppleTrue = 0x74727565u; - - /// 0x74797031 — "typ1" — Legacy Apple Type 1 wrapper (rare). - public const uint SfVersionAppleTyp1 = 0x74797031u; - - // ── Fields ─────────────────────────────────────────────────────────── - - /// - /// The sfnt version, also called the 'sfVersion' or 'sfntVersion' field. - /// Compare against the SfVersion* constants above. - /// - public uint SfVersion { get; } - - /// Number of tables in this font. - public ushort NumTables { get; } - - /// - /// (Maximum power of 2 ≤ NumTables) × 16. - /// Pre-computed binary search value; informational only. - /// - public ushort SearchRange { get; } - - /// - /// Log₂ of the maximum power of 2 ≤ NumTables. - /// Pre-computed binary search value; informational only. - /// - public ushort EntrySelector { get; } - - /// - /// NumTables × 16 − SearchRange. - /// Pre-computed binary search value; informational only. - /// - public ushort RangeShift { get; } - - // ── Derived helpers ────────────────────────────────────────────────── - - /// True when the sfnt container holds TrueType outlines (glyf table). - public bool IsTrueType => - SfVersion == SfVersionTrueType || SfVersion == SfVersionAppleTrue; - - /// True when the sfnt container holds CFF (Type 2 charstring) outlines. - public bool IsCff => SfVersion == SfVersionCff; - - /// - /// Initializes a new with the specified values. - /// - /// The sfnt version. - /// Number of tables in this font. - /// Pre-computed binary search value. - /// Log₂ of the maximum power of 2 ≤ NumTables. - /// NumTables × 16 − SearchRange. - public OpenTypeOffsetTable( - uint sfVersion, - ushort numTables, - ushort searchRange, - ushort entrySelector, - ushort rangeShift) - { - SfVersion = sfVersion; - NumTables = numTables; - SearchRange = searchRange; - EntrySelector = entrySelector; - RangeShift = rangeShift; - } - - /// - /// Returns a string representation of this offset table. - /// - public override string ToString() => - $"OffsetTable(sfVersion=0x{SfVersion:X8}, numTables={NumTables}, isCff={IsCff})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/OpenTypeTableDirectory.cs b/src/MiniPdf/Drawing/Font/IO/OpenTypeTableDirectory.cs deleted file mode 100644 index 4ab712c2..00000000 --- a/src/MiniPdf/Drawing/Font/IO/OpenTypeTableDirectory.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// Parses the OpenType table directory and provides helpers for reading raw table bytes. - /// - /// - /// The table directory immediately follows the 12-byte offset table in an sfnt file. - /// Each entry is 16 bytes: 4-byte tag, 4-byte checksum, 4-byte offset, 4-byte length. - /// - public static class OpenTypeTableDirectory - { - /// - /// Reads the offset table and the complete table directory from the current - /// position of (expected to be at byte 0 of the font). - /// - /// - /// A tuple of the parsed header and a - /// case-sensitive dictionary mapping each table tag to its - /// . - /// - /// - /// Thrown when the sfnt magic bytes are not recognised as a supported font format. - /// - public static (OpenTypeOffsetTable Header, - IReadOnlyDictionary Records) - Parse(FontBinaryReader reader) - { - if (reader is null) throw new ArgumentNullException(nameof(reader)); - - uint sfVersion = reader.ReadUInt32(); - ushort numTables = reader.ReadUInt16(); - ushort searchRange = reader.ReadUInt16(); - ushort entrySelector = reader.ReadUInt16(); - ushort rangeShift = reader.ReadUInt16(); - - // Validate the sfnt magic (relaxed: warn but don't throw for unknown values - // to allow future extension; hard check is done in TtfFontReader). - var header = new OpenTypeOffsetTable( - sfVersion, numTables, searchRange, entrySelector, rangeShift); - - var records = new Dictionary(numTables, - StringComparer.Ordinal); - - for (int i = 0; i < numTables; i++) - { - string tag = reader.ReadTag(); - uint checksum = reader.ReadUInt32(); - uint offset = reader.ReadUInt32(); - uint length = reader.ReadUInt32(); - records[tag] = new OpenTypeTableRecord(tag, checksum, offset, length); - } - - return (header, records); - } - - /// - /// Seeks to a table's data and reads its raw bytes. - /// - public static byte[] ReadTableBytes( - FontBinaryReader reader, - OpenTypeTableRecord record) - { - if (reader is null) throw new ArgumentNullException(nameof(reader)); - if (record is null) throw new ArgumentNullException(nameof(record)); - - reader.Seek(record.Offset); - return reader.ReadBytes((int)record.Length); - } - - /// - /// Reads the raw bytes of every table listed in - /// and returns them keyed by tag. - /// - public static IReadOnlyDictionary ReadAllTableBytes( - FontBinaryReader reader, - IReadOnlyDictionary records) - { - if (reader is null) throw new ArgumentNullException(nameof(reader)); - if (records is null) throw new ArgumentNullException(nameof(records)); - - var result = new Dictionary(records.Count, StringComparer.Ordinal); - foreach (var kvp in records) - { - reader.Seek(kvp.Value.Offset); - result[kvp.Key] = reader.ReadBytes((int)kvp.Value.Length); - } - return result; - } - - /// - /// Computes the OpenType table checksum for a block of bytes. - /// Algorithm: sum all 32-bit big-endian words (zero-padding the last word if needed), - /// modulo 2^32. - /// - public static uint ComputeChecksum(byte[] tableData) - { - if (tableData is null) throw new ArgumentNullException(nameof(tableData)); - - uint sum = 0; - int wordCount = (tableData.Length + 3) / 4; - for (int i = 0; i < wordCount; i++) - { - int pos = i * 4; - uint word = 0; - for (int b = 0; b < 4; b++) - { - word = (word << 8) | - (uint)(pos + b < tableData.Length ? tableData[pos + b] : 0); - } - sum += word; - } - return sum; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/OpenTypeTableRecord.cs b/src/MiniPdf/Drawing/Font/IO/OpenTypeTableRecord.cs deleted file mode 100644 index f6bb1fb8..00000000 --- a/src/MiniPdf/Drawing/Font/IO/OpenTypeTableRecord.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// One entry in the OpenType table directory: identifies a table by its four-character - /// tag and records its checksum, absolute byte offset, and byte length within the font file. - /// - public sealed class OpenTypeTableRecord - { - /// - /// Four-character ASCII identifier, e.g. "head", "cmap", "glyf", "CFF ". - /// - public string Tag { get; } - - /// - /// Checksum of the table data as defined in the OpenType specification. - /// (Sum of all uint32 values in the table, modulo 2^32.) - /// - public uint Checksum { get; } - - /// Absolute byte offset of the table data from the beginning of the font file. - public uint Offset { get; } - - /// Length of the table data in bytes (before any 4-byte padding). - public uint Length { get; } - - /// - /// Initializes a new with the specified values. - /// - /// Four-character ASCII identifier. - /// Checksum of the table data. - /// Absolute byte offset of the table data. - /// Length of the table data in bytes. - public OpenTypeTableRecord(string tag, uint checksum, uint offset, uint length) - { - Tag = tag; - Checksum = checksum; - Offset = offset; - Length = length; - } - - /// - /// Returns a string representation of this table record. - /// - public override string ToString() => - $"[{Tag}] offset=0x{Offset:X6} length={Length} checksum=0x{Checksum:X8}"; - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/TtcReader.cs b/src/MiniPdf/Drawing/Font/IO/TtcReader.cs deleted file mode 100644 index 448cfc73..00000000 --- a/src/MiniPdf/Drawing/Font/IO/TtcReader.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Ttf; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// Parses a TrueType Collection (TTC) file and returns all contained font faces. - /// - /// - /// TTC header layout (version 1.0 and 2.0): - /// - /// Offset 0ttcTag — 4 bytes, must be 'ttcf' (0x74746366) - /// Offset 4version — 4 bytes (0x00010000 or 0x00020000) - /// Offset 8numFonts — 4 bytes - /// Offset 12offsetTable[numFonts] — 4 bytes each, absolute offsets to sfnt headers - /// - /// Version 2.0 appends three extra DSIG fields after the offset array; they are - /// ignored here (we only need the sfnt offsets). - /// - /// All table-record offsets inside each embedded sfnt are absolute offsets from - /// the start of the TTC file, so the same seekable stream can be shared across - /// all font reads. - /// - /// Specification: https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header - /// - internal static class TtcReader - { - /// TTC magic bytes 't','t','c','f' = 0x74746366. - internal const uint Signature = 0x74746366u; - - // ── Public surface ──────────────────────────────────────────────────── - - /// - /// Reads all font faces from a TTC stream. - /// - /// A seekable stream positioned at the start of the TTC data. - /// - /// A list containing one per face in the collection. - /// The list contains at least one entry. - /// - /// stream is null. - /// - /// The data is not a valid TTC file, or a contained sfnt cannot be parsed. - /// - internal static IReadOnlyList Read(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - - // Buffer the entire file so we can seek freely while reading multiple fonts. - byte[] data = ReadAllBytes(stream); - - if (data.Length < 12) - throw new InvalidOperationException( - "Data is too short to be a TTC file (minimum 12 bytes for header)."); - - // ── TTC header ──────────────────────────────────────────────────── - uint sig = ReadU32(data, 0); - if (sig != Signature) - throw new InvalidOperationException( - $"Not a TTC file (signature 0x{sig:X8}, expected 0x74746366 'ttcf')."); - - /* version */ ReadU32(data, 4); // 0x00010000 or 0x00020000 — not needed - uint numFonts = ReadU32(data, 8); - - if (numFonts == 0) - throw new InvalidOperationException("TTC file reports zero fonts."); - - int minHeaderSize = 12 + (int)numFonts * 4; - if (data.Length < minHeaderSize) - throw new InvalidOperationException( - $"TTC file is too short to hold the offset table " + - $"(numFonts={numFonts}, need {minHeaderSize} bytes, have {data.Length})."); - - // ── Read sfnt offset array ──────────────────────────────────────── - var offsets = new uint[numFonts]; - for (int i = 0; i < (int)numFonts; i++) - offsets[i] = ReadU32(data, 12 + i * 4); - - // ── Parse each embedded sfnt ────────────────────────────────────── - // All table-data offsets inside each sfnt are absolute positions within - // the TTC file, so we share one MemoryStream across all font reads. - using var ms = new MemoryStream(data, writable: false); - var fonts = new List((int)numFonts); - - for (int i = 0; i < (int)numFonts; i++) - { - uint sfntOffset = offsets[i]; - - if (sfntOffset >= data.Length) - throw new InvalidOperationException( - $"TTC font[{i}] sfnt offset 0x{sfntOffset:X} is beyond the end of the file."); - - ms.Position = sfntOffset; - fonts.Add(TtfFontReader.Read(ms)); - } - - return fonts; - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static uint ReadU32(byte[] d, int offset) => - ((uint)d[offset] << 24) | ((uint)d[offset + 1] << 16) | - ((uint)d[offset + 2] << 8) | d[offset + 3]; - - private static byte[] ReadAllBytes(Stream stream) - { - using var ms = new MemoryStream(); - stream.CopyTo(ms); - return ms.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/Woff2Reader.cs b/src/MiniPdf/Drawing/Font/IO/Woff2Reader.cs deleted file mode 100644 index 8dbfd7a8..00000000 --- a/src/MiniPdf/Drawing/Font/IO/Woff2Reader.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// WOFF2 container decompression stub. - /// - /// - /// WOFF2 uses Brotli compression, which requires System.IO.Compression.BrotliStream - /// available on .NET 6 and later. This library targets netstandard2.0, so WOFF2 - /// decompression is not available; every entry point throws - /// . - /// - /// Specification: https://www.w3.org/TR/WOFF2/ - /// - internal static class Woff2Reader - { - /// WOFF2 magic bytes 'w','O','F','2' = 0x774F4632. - internal const uint Signature = 0x774F4632u; - - private const string NotSupportedMessage = - "WOFF2 decompression requires .NET 6 or later (System.IO.Compression.BrotliStream). " + - "To load a WOFF2 font on this platform, supply the pre-decompressed sfnt bytes " + - "via ByteContentStreamSource with FontType.TTF or FontType.OTF instead."; - - /// - /// Not supported on netstandard2.0; always throws . - /// - internal static byte[] Decompress(byte[] data) - { - _ = data; - throw new NotSupportedException(NotSupportedMessage); - } - - /// - /// Not supported on netstandard2.0; always throws . - /// - internal static byte[] Decompress(Stream stream) - { - _ = stream; - throw new NotSupportedException(NotSupportedMessage); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/IO/WoffReader.cs b/src/MiniPdf/Drawing/Font/IO/WoffReader.cs deleted file mode 100644 index 51bbafb5..00000000 --- a/src/MiniPdf/Drawing/Font/IO/WoffReader.cs +++ /dev/null @@ -1,271 +0,0 @@ -using System; -using System.IO; -using System.IO.Compression; - -namespace MiniSoftware.Drawing.Font.IO -{ - /// - /// Decompresses a WOFF 1.0 container into a raw sfnt byte array that can be - /// passed to or . - /// - /// - /// Each WOFF table is individually compressed using raw DEFLATE (RFC 1951). - /// Many tools (e.g., fonttools) instead produce zlib-wrapped DEFLATE (RFC 1950). - /// Both are detected automatically by checking for the two-byte zlib header. - /// - /// Specification: https://www.w3.org/TR/WOFF/ - /// - internal static class WoffReader - { - /// WOFF 1.0 magic bytes 'w','O','F','F' = 0x774F4646. - internal const uint Signature = 0x774F4646u; - - // ── Public surface ──────────────────────────────────────────────────── - - /// - /// Reads a WOFF 1.0 stream and returns the reconstructed sfnt bytes. - /// - /// - /// The data is not a valid WOFF 1.0 file or a table cannot be decompressed. - /// - internal static byte[] Decompress(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - - using var ms = new MemoryStream(); - stream.CopyTo(ms); - return Decompress(ms.ToArray()); - } - - /// - /// Parses a WOFF 1.0 byte array and returns the reconstructed sfnt bytes. - /// - internal static byte[] Decompress(byte[] data) - { - if (data is null) throw new ArgumentNullException(nameof(data)); - if (data.Length < 44) - throw new InvalidOperationException( - "Data is too short to be a WOFF file (minimum 44 bytes for header)."); - - int pos = 0; - - // ── WOFF header (44 bytes total) ────────────────────────────────── - uint sig = ReadU32(data, ref pos); - if (sig != Signature) - throw new InvalidOperationException( - $"Not a WOFF 1.0 file (signature 0x{sig:X8}, expected 0x774F4646)."); - - uint flavor = ReadU32(data, ref pos); - /* length */ ReadU32(data, ref pos); // total WOFF file size - ushort numTables = ReadU16(data, ref pos); - /* reserved */ ReadU16(data, ref pos); - /* totalSfntSize*/ ReadU32(data, ref pos); // hint only; we rebuild - /* majorVersion */ ReadU16(data, ref pos); - /* minorVersion */ ReadU16(data, ref pos); - /* metaOffset */ ReadU32(data, ref pos); - /* metaLength */ ReadU32(data, ref pos); - /* metaOrigLen */ ReadU32(data, ref pos); - /* privOffset */ ReadU32(data, ref pos); - /* privLength */ ReadU32(data, ref pos); - // pos == 44 here - - // ── Table directory entries (20 bytes each) ─────────────────────── - var entries = new WoffEntry[numTables]; - var tableData = new byte[numTables][]; - - for (int i = 0; i < numTables; i++) - { - string tag = ReadTag(data, ref pos); - uint woffOff = ReadU32(data, ref pos); - uint compLen = ReadU32(data, ref pos); - uint origLen = ReadU32(data, ref pos); - uint checksum = ReadU32(data, ref pos); - entries[i] = new WoffEntry(tag, woffOff, compLen, origLen, checksum); - } - - // ── Decompress each table ───────────────────────────────────────── - for (int i = 0; i < numTables; i++) - { - var e = entries[i]; - - if ((long)e.WoffOffset + e.CompLen > data.Length) - throw new InvalidOperationException( - $"WOFF table '{e.Tag}' data extends beyond file bounds " + - $"(offset={e.WoffOffset}, compLen={e.CompLen}, fileLen={data.Length})."); - - tableData[i] = e.CompLen < e.OrigLen - ? DecompressTable(data, (int)e.WoffOffset, (int)e.CompLen, (int)e.OrigLen, e.Tag) - : Slice(data, (int)e.WoffOffset, (int)e.CompLen); - } - - // ── Reconstruct sfnt binary ─────────────────────────────────────── - return BuildSfnt(flavor, entries, tableData); - } - - // ── Private helpers ─────────────────────────────────────────────────── - - /// - /// Decompresses one WOFF table block. - /// Handles both raw DEFLATE and zlib-wrapped DEFLATE automatically. - /// - private static byte[] DecompressTable( - byte[] data, int offset, int compLen, int origLen, string tag) - { - // Detect zlib header: first byte CM nibble == 8 (DEFLATE) and - // the two-byte big-endian value is divisible by 31 (FCHECK). - bool hasZlibHeader = compLen >= 2 - && (data[offset] & 0x0F) == 8 - && ((data[offset] << 8) | data[offset + 1]) % 31 == 0; - - int start = hasZlibHeader ? offset + 2 : offset; - int length = compLen - (hasZlibHeader ? 2 : 0); - - using var ms = new MemoryStream(data, start, length); - using var deflate = new DeflateStream(ms, CompressionMode.Decompress); - - var result = new byte[origLen]; - int totalRead = 0; - while (totalRead < origLen) - { - int n = deflate.Read(result, totalRead, origLen - totalRead); - if (n == 0) break; - totalRead += n; - } - - if (totalRead != origLen) - throw new InvalidOperationException( - $"WOFF table '{tag}': expected {origLen} decompressed bytes, got {totalRead}."); - - return result; - } - - /// - /// Assembles the decompressed tables into a standard sfnt binary. - /// - private static byte[] BuildSfnt(uint flavor, WoffEntry[] entries, byte[][] tableData) - { - int n = entries.Length; - - // sfnt requires tables sorted lexicographically by tag. - Array.Sort(entries, tableData, - System.Collections.Generic.Comparer.Create( - (a, b) => string.Compare(a.Tag, b.Tag, StringComparison.Ordinal))); - - // Calculate the offset of each table in the output sfnt. - // Layout: 12-byte offset table + n×16-byte directory + padded table data. - int directoryEnd = 12 + n * 16; - var sfntOffsets = new uint[n]; - uint cursor = (uint)directoryEnd; - - for (int i = 0; i < n; i++) - { - sfntOffsets[i] = cursor; - cursor += (uint)tableData[i].Length; - if (cursor % 4 != 0) cursor += 4 - cursor % 4; // 4-byte align - } - - var sfnt = new byte[cursor]; - int w = 0; - - // ── sfnt offset table (12 bytes) ────────────────────────────────── - WriteU32(sfnt, ref w, flavor); - WriteU16(sfnt, ref w, (ushort)n); - - // Binary-search parameters: - int p2 = 1; - while (p2 * 2 <= n) p2 *= 2; - - int log2 = 0, t = p2; - while (t > 1) { log2++; t >>= 1; } - - WriteU16(sfnt, ref w, (ushort)(p2 * 16)); // searchRange - WriteU16(sfnt, ref w, (ushort)log2); // entrySelector - WriteU16(sfnt, ref w, (ushort)(n * 16 - p2 * 16)); // rangeShift - - // ── Table directory (16 bytes per entry) ────────────────────────── - for (int i = 0; i < n; i++) - { - WriteTag(sfnt, ref w, entries[i].Tag); - WriteU32(sfnt, ref w, entries[i].Checksum); - WriteU32(sfnt, ref w, sfntOffsets[i]); - WriteU32(sfnt, ref w, entries[i].OrigLen); - } - - // ── Table data ──────────────────────────────────────────────────── - for (int i = 0; i < n; i++) - Array.Copy(tableData[i], 0, sfnt, (int)sfntOffsets[i], tableData[i].Length); - // Padding bytes between tables are zero from array initialisation. - - return sfnt; - } - - // ── Low-level byte I/O ──────────────────────────────────────────────── - - private static uint ReadU32(byte[] d, ref int p) - { - uint v = ((uint)d[p] << 24) | ((uint)d[p + 1] << 16) - | ((uint)d[p + 2] << 8) | d[p + 3]; - p += 4; - return v; - } - - private static ushort ReadU16(byte[] d, ref int p) - { - ushort v = (ushort)((d[p] << 8) | d[p + 1]); - p += 2; - return v; - } - - private static string ReadTag(byte[] d, ref int p) - { - var s = new string(new[] { (char)d[p], (char)d[p + 1], (char)d[p + 2], (char)d[p + 3] }); - p += 4; - return s; - } - - private static byte[] Slice(byte[] d, int offset, int length) - { - var r = new byte[length]; - Array.Copy(d, offset, r, 0, length); - return r; - } - - private static void WriteU32(byte[] b, ref int p, uint v) - { - b[p++] = (byte)(v >> 24); b[p++] = (byte)(v >> 16); - b[p++] = (byte)(v >> 8); b[p++] = (byte)v; - } - - private static void WriteU16(byte[] b, ref int p, ushort v) - { - b[p++] = (byte)(v >> 8); b[p++] = (byte)v; - } - - private static void WriteTag(byte[] b, ref int p, string tag) - { - b[p++] = (byte)tag[0]; b[p++] = (byte)tag[1]; - b[p++] = (byte)tag[2]; b[p++] = (byte)tag[3]; - } - - // ── WoffEntry value type ────────────────────────────────────────────── - - private struct WoffEntry - { - public string Tag; - public uint WoffOffset; - public uint CompLen; - public uint OrigLen; - public uint Checksum; - - public WoffEntry(string tag, uint woffOffset, - uint compLen, uint origLen, uint checksum) - { - Tag = tag; - WoffOffset = woffOffset; - CompLen = compLen; - OrigLen = origLen; - Checksum = checksum; - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/CurveTo.cs b/src/MiniPdf/Drawing/Font/Rendering/CurveTo.cs deleted file mode 100644 index 114c35e5..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/CurveTo.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// A "curve to" drawing command representing a cubic Bézier segment. - /// Draws from the current point using two explicit control points to the - /// specified endpoint. - /// - /// (, ) — first control point. - /// (, ) — second control point. - /// (, ) — endpoint (new current point). - /// - /// TrueType quadratic Bézier segments are converted to this cubic form before - /// being emitted (see ). - /// Coordinates are in font design units. - /// - public readonly struct CurveTo - { - /// First cubic control point X. - public double X1 { get; } - /// First cubic control point Y. - public double Y1 { get; } - - /// Second cubic control point X. - public double X2 { get; } - /// Second cubic control point Y. - public double Y2 { get; } - - /// Endpoint X (becomes new current point). - public double X3 { get; } - /// Endpoint Y (becomes new current point). - public double Y3 { get; } - - /// - /// Initializes a new with the specified control points and endpoint. - /// - /// First cubic control point X. - /// First cubic control point Y. - /// Second cubic control point X. - /// Second cubic control point Y. - /// Endpoint X. - /// Endpoint Y. - public CurveTo(double x1, double y1, double x2, double y2, double x3, double y3) - { - X1 = x1; Y1 = y1; - X2 = x2; Y2 = y2; - X3 = x3; Y3 = y3; - } - - /// - /// Returns a string representation of this curve command. - /// - public override string ToString() => - $"CurveTo(cp1=({X1:F2},{Y1:F2}) cp2=({X2:F2},{Y2:F2}) end=({X3:F2},{Y3:F2}))"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/GlyphOutlineRenderer.cs b/src/MiniPdf/Drawing/Font/Rendering/GlyphOutlineRenderer.cs deleted file mode 100644 index 665a7ecd..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/GlyphOutlineRenderer.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Cff; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Ttf; -using MiniSoftware.Drawing.Font.Type1; - -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// High-level entry point for glyph outline rendering. - /// Wraps an and dispatches each - /// call to the appropriate low-level renderer: - /// - /// → - /// CffFont → CffOutlineRenderer (added in Batch 9) - /// - /// - public sealed class GlyphOutlineRenderer - { - private readonly IFont _font; - - /// The font whose glyphs will be rendered. - public GlyphOutlineRenderer(IFont font) - { - _font = font ?? throw new ArgumentNullException(nameof(font)); - } - - /// - /// Decomposes the outline of the glyph identified by - /// and delivers drawing commands to . - /// - /// Glyph identifier, typically from . - /// Receives the MoveTo / LineTo / CurveTo / ClosePath calls. - /// or is null. - /// - /// The font type does not yet have an outline renderer implementation. - /// - public void RenderGlyph(GlyphId gid, IGlyphOutlinePainter painter) - { - if (gid is null) throw new ArgumentNullException(nameof(gid)); - if (painter is null) throw new ArgumentNullException(nameof(painter)); - - if (_font is TtfFont ttfFont) - { - RenderTtfGlyph(ttfFont, gid, painter); - return; - } - - if (_font is CffFont cffFont) - { - RenderCffGlyph(cffFont, gid, painter); - return; - } - - if (_font is Type1Font t1Font) - { - RenderType1Glyph(t1Font, gid, painter); - return; - } - - throw new NotSupportedException( - $"GlyphOutlineRenderer does not yet support font type '{_font.GetType().Name}'."); - } - - // ── TrueType / OTF/TT ──────────────────────────────────────────────── - - private static void RenderTtfGlyph( - TtfFont font, GlyphId gid, IGlyphOutlinePainter painter) - { - if (!(gid is GlyphUInt32Id uid)) return; - - var glyfTable = font.TtfTables.GlyfTable; - if (glyfTable == null) return; // CFF-flavored OTF has no glyf table - - var outline = glyfTable.GetGlyphOutline((int)uid.Value); - if (outline != null) - TtfOutlineRenderer.Render(outline, painter, glyfTable); - } - - // ── CFF / OTF+CFF ───────────────────────────────────────────────────── - - private static void RenderCffGlyph( - CffFont font, GlyphId gid, IGlyphOutlinePainter painter) - { - if (!(gid is GlyphUInt32Id uid)) return; - - var data = font.CffData; - int idx = (int)uid.Value; - if (idx < 0 || idx >= data.CharStrings.Length) return; - - CffPrivateDict priv = GetCffPrivateDict(data, idx); - var interp = new Type2Interpreter(); - interp.Interpret(data.CharStrings[idx], painter, priv, data.GlobalSubrs); - } - - private static CffPrivateDict GetCffPrivateDict(CffData data, int gid) - { - if (data.IsCIDFont && data.GlyphFDIndex != null && data.CIDFontDicts != null) - { - int fdIdx = gid < data.GlyphFDIndex.Length ? data.GlyphFDIndex[gid] : 0; - if (fdIdx >= 0 && fdIdx < data.CIDFontDicts.Length) - return data.CIDFontDicts[fdIdx].PrivateDict; - } - return data.PrivateDict; - } - - // ── Type 1 ──────────────────────────────────────────────────────────── - - private static void RenderType1Glyph( - Type1Font font, GlyphId gid, IGlyphOutlinePainter painter) - { - if (!(gid is GlyphUInt32Id uid)) return; - - var data = font.Data; - int idx = (int)uid.Value; - if (idx < 0 || idx >= data.GlyphOrder.Length) return; - - string name = data.GlyphOrder[idx]; - if (!data.CharStrings.TryGetValue(name, out byte[]? cs)) return; - - var interp = new Type1CharStringInterpreter(); - interp.Interpret(cs, painter, data.Subrs, data.CharStrings); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/IGlyphOutlinePainter.cs b/src/MiniPdf/Drawing/Font/Rendering/IGlyphOutlinePainter.cs deleted file mode 100644 index fb4b0a30..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/IGlyphOutlinePainter.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// Receives decomposed glyph outline drawing commands from an outline renderer. - /// Implement this interface to paint, record, or convert glyph paths - /// (e.g. to a GraphicsPath, PDF stream, or SVG path). - /// - public interface IGlyphOutlinePainter - { - /// - /// Lifts the pen and begins a new sub-path at the given point. - /// Must be called at the start of each contour. - /// - void MoveTo(MoveTo cmd); - - /// Draws a straight line to the given endpoint. - void LineTo(LineTo cmd); - - /// - /// Draws a cubic Bézier curve using two control points. - /// TrueType quadratic splines are pre-converted to this cubic form. - /// - void CurveTo(CurveTo cmd); - - /// - /// Closes the current sub-path by drawing a straight line back to the - /// point set by the most recent . - /// Called once at the end of each contour. - /// - void ClosePath(); - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/LineTo.cs b/src/MiniPdf/Drawing/Font/Rendering/LineTo.cs deleted file mode 100644 index 22544a24..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/LineTo.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// A "line to" drawing command: draws a straight line from the current point - /// to (, ). - /// Coordinates are in font design units. - /// - public readonly struct LineTo - { - /// - /// Gets the X coordinate of the line-to point. - /// - public double X { get; } - - /// - /// Gets the Y coordinate of the line-to point. - /// - public double Y { get; } - - /// - /// Initializes a new with the specified coordinates. - /// - /// The X coordinate. - /// The Y coordinate. - public LineTo(double x, double y) { X = x; Y = y; } - - /// - /// Returns a string representation of this . - /// - /// A string in the format "LineTo(x, y)". - public override string ToString() => $"LineTo({X:F2}, {Y:F2})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/MoveTo.cs b/src/MiniPdf/Drawing/Font/Rendering/MoveTo.cs deleted file mode 100644 index 70a93702..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/MoveTo.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// A "move to" drawing command: lifts the pen and sets the current point - /// to (, ) without drawing anything. - /// Coordinates are in font design units. - /// - public readonly struct MoveTo - { - /// - /// Gets the X coordinate of the move-to point. - /// - public double X { get; } - - /// - /// Gets the Y coordinate of the move-to point. - /// - public double Y { get; } - - /// - /// Initializes a new with the specified coordinates. - /// - /// The X coordinate. - /// The Y coordinate. - public MoveTo(double x, double y) { X = x; Y = y; } - - /// - /// Returns a string representation of this . - /// - /// A string in the format "MoveTo(x, y)". - public override string ToString() => $"MoveTo({X:F2}, {Y:F2})"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Rendering/TtfOutlineRenderer.cs b/src/MiniPdf/Drawing/Font/Rendering/TtfOutlineRenderer.cs deleted file mode 100644 index d3e56136..00000000 --- a/src/MiniPdf/Drawing/Font/Rendering/TtfOutlineRenderer.cs +++ /dev/null @@ -1,268 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Ttf.Glyphs; -using MiniSoftware.Drawing.Font.Ttf.Tables; - -namespace MiniSoftware.Drawing.Font.Rendering -{ - /// - /// Decomposes a TrueType glyph outline () into - /// commands. - /// - /// Simple glyphs — each closed contour is walked and quadratic - /// Bézier control points are converted to cubic form before being emitted. - /// - /// Composite glyphs — each component is resolved recursively via - /// the supplied and rendered with the component's - /// 2×3 affine transform composed into the current transform. - /// - /// Quadratic → cubic conversion (standard formula): - /// - /// C1 = (Q0 + 2·Q1) / 3 - /// C2 = (2·Q1 + Q2) / 3 - /// - /// - public static class TtfOutlineRenderer - { - private const int MaxRecursionDepth = 8; // guard against malformed fonts - - // ── Public entry ────────────────────────────────────────────────────── - - /// - /// Renders using the identity transform. - /// - /// Parsed glyph outline from . - /// Target that receives drawing commands. - /// - /// Required for composite glyphs (component look-up); may be null for simple glyphs. - /// - public static void Render( - GlyphOutlineData outline, - IGlyphOutlinePainter painter, - TtfGlyfTable? glyfTable = null) - { - if (outline is null) throw new ArgumentNullException(nameof(outline)); - if (painter is null) throw new ArgumentNullException(nameof(painter)); - - RenderInternal(outline, painter, glyfTable, - a: 1f, b: 0f, c: 0f, d: 1f, e: 0f, f: 0f, depth: 0); - } - - // ── Internal recursive dispatcher ───────────────────────────────────── - - private static void RenderInternal( - GlyphOutlineData outline, - IGlyphOutlinePainter painter, - TtfGlyfTable? glyfTable, - float a, float b, float c, float d, float e, float f, - int depth) - { - if (depth > MaxRecursionDepth) return; - - if (outline.IsComposite) - { - if (outline.Composite == null || glyfTable == null) return; - RenderComposite(outline.Composite, painter, glyfTable, a, b, c, d, e, f, depth); - } - else - { - if (outline.Simple == null) return; - RenderSimple(outline.Simple, painter, a, b, c, d, e, f); - } - } - - // ── Composite glyph ─────────────────────────────────────────────────── - - private static void RenderComposite( - TtfCompositeGlyph composite, - IGlyphOutlinePainter painter, - TtfGlyfTable glyfTable, - float a, float b, float c, float d, float e, float f, - int depth) - { - foreach (var component in composite.Components) - { - var compOutline = glyfTable.GetGlyphOutline(component.GlyphIndex); - if (compOutline == null) continue; - - // Component local transform: T (2×3 affine matrix) - // row 0: T[0,0]=ca, T[0,1]=cb, T[0,2]=ce - // row 1: T[1,0]=cc, T[1,1]=cd, T[1,2]=cf - // Transform order: design → component → outer (current). - // Point: x'' = a*(ca*x + cb*y + ce) + b*(cc*x + cd*y + cf) + e - var T = component.Transform; - float ca = T[0, 0], cb = T[0, 1], ce = T[0, 2]; - float cc = T[1, 0], cd = T[1, 1], cf = T[1, 2]; - - float na = a * ca + b * cc; - float nb = a * cb + b * cd; - float ne = a * ce + b * cf + e; - - float nc = c * ca + d * cc; - float nd = c * cb + d * cd; - float nf = c * ce + d * cf + f; - - RenderInternal(compOutline, painter, glyfTable, na, nb, nc, nd, ne, nf, depth + 1); - } - } - - // ── Simple glyph ────────────────────────────────────────────────────── - - private static void RenderSimple( - TtfSimpleGlyph glyph, - IGlyphOutlinePainter painter, - float a, float b, float c, float d, float e, float f) - { - if (glyph.NumberOfContours <= 0) return; - - int from = 0; - for (int ci = 0; ci < glyph.NumberOfContours; ci++) - { - int end = glyph.EndPtsOfContours[ci]; - int count = end - from + 1; - if (count > 0) - RenderContour(glyph.Points, from, count, painter, a, b, c, d, e, f); - from = end + 1; - } - } - - // ── Contour rendering ───────────────────────────────────────────────── - - /// - /// Renders one closed contour from [ - /// .. from+count−1]. - /// - /// - /// Algorithm: - /// - /// Find the first on-curve point to use as the MoveTo start. - /// If no on-curve point exists (all-off-curve contour), use the midpoint - /// of the last and first point as the implicit start. - /// Walk count points cyclically from the start; for each: - /// - /// on-curve after on-curve → LineTo - /// on-curve after off-curve → emit quad→cubic CurveTo - /// off-curve after off-curve → emit quad→cubic to implicit midpoint, - /// then begin new control point - /// - /// - /// If a control point is pending after the loop, emit the closing curve - /// back to the start. - /// ClosePath. - /// - /// - private static void RenderContour( - TtfPoint[] pts, int from, int count, - IGlyphOutlinePainter painter, - float a, float b, float c, float d, float e, float f) - { - if (count <= 0) return; - - // Inline affine transform: x' = a·x + b·y + e, y' = c·x + d·y + f - void Tx(double px, double py, out double rx, out double ry) - { - rx = a * px + b * py + e; - ry = c * px + d * py + f; - } - - // ── Find start ──────────────────────────────────────────────────── - int firstOnCurve = -1; - for (int i = 0; i < count; i++) - if (pts[from + i].OnCurve) { firstOnCurve = i; break; } - - double startX, startY; - int startIndex; // first index to process in the cyclic walk - - if (firstOnCurve < 0) - { - // All-off-curve contour: implicit start at midpoint of last and first point. - double mx = (pts[from].X + pts[from + count - 1].X) / 2.0; - double my = (pts[from].Y + pts[from + count - 1].Y) / 2.0; - Tx(mx, my, out startX, out startY); - startIndex = 0; // process all n off-curve points - } - else - { - Tx(pts[from + firstOnCurve].X, pts[from + firstOnCurve].Y, out startX, out startY); - startIndex = firstOnCurve + 1; - } - - painter.MoveTo(new MoveTo(startX, startY)); - - double curX = startX; - double curY = startY; - double ctrlX = 0; - double ctrlY = 0; - bool hasCtrl = false; - - // ── Walk count points cyclically (natural close-back) ───────────── - for (int step = 0; step < count; step++) - { - var pt = pts[from + (startIndex + step) % count]; - Tx(pt.X, pt.Y, out double px, out double py); - - if (pt.OnCurve) - { - if (hasCtrl) - { - EmitQuadAsCubic(curX, curY, ctrlX, ctrlY, px, py, painter); - hasCtrl = false; - } - else - { - painter.LineTo(new LineTo(px, py)); - } - curX = px; - curY = py; - } - else // off-curve - { - if (hasCtrl) - { - // Two consecutive off-curve points → implicit on-curve at midpoint. - // Midpoint in transformed space = transform of midpoint in design space - // (affine transforms preserve midpoints). - double midX = (ctrlX + px) / 2.0; - double midY = (ctrlY + py) / 2.0; - EmitQuadAsCubic(curX, curY, ctrlX, ctrlY, midX, midY, painter); - curX = midX; - curY = midY; - } - ctrlX = px; - ctrlY = py; - hasCtrl = true; - } - } - - // If a pending control remains (only possible in all-off-curve contours), - // close back to the start with a final curve. - if (hasCtrl) - EmitQuadAsCubic(curX, curY, ctrlX, ctrlY, startX, startY, painter); - - painter.ClosePath(); - } - - // ── Quadratic → cubic Bézier conversion ────────────────────────────── - - /// - /// Converts a quadratic Bézier (Q0 = current, Q1 = control, Q2 = end) to a - /// cubic Bézier and emits it. - /// - /// C1 = (Q0 + 2·Q1) / 3
- /// C2 = (2·Q1 + Q2) / 3 - ///
- ///
- private static void EmitQuadAsCubic( - double q0X, double q0Y, // current position (Q0) - double q1X, double q1Y, // quadratic off-curve control (Q1) - double q2X, double q2Y, // segment endpoint (Q2) - IGlyphOutlinePainter painter) - { - double c1X = (q0X + 2.0 * q1X) / 3.0; - double c1Y = (q0Y + 2.0 * q1Y) / 3.0; - double c2X = (2.0 * q1X + q2X) / 3.0; - double c2Y = (2.0 * q1Y + q2Y) / 3.0; - - painter.CurveTo(new CurveTo(c1X, c1Y, c2X, c2Y, q2X, q2Y)); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Sources/ByteContentStreamSource.cs b/src/MiniPdf/Drawing/Font/Sources/ByteContentStreamSource.cs deleted file mode 100644 index 3b98e196..00000000 --- a/src/MiniPdf/Drawing/Font/Sources/ByteContentStreamSource.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Sources -{ - /// - /// Reads a font from a byte array already held in memory. - /// - public sealed class ByteContentStreamSource : IStreamSource - { - private readonly byte[] _data; - - /// - /// Initializes a new with the specified byte array. - /// - /// The byte array containing font data. - public ByteContentStreamSource(byte[] data) - { - _data = data ?? throw new ArgumentNullException(nameof(data)); - } - - /// - /// Returns a new each time; the caller must dispose it. - public Stream GetFontStream() => new MemoryStream(_data, writable: false); - } -} diff --git a/src/MiniPdf/Drawing/Font/Sources/FileSystemStreamSource.cs b/src/MiniPdf/Drawing/Font/Sources/FileSystemStreamSource.cs deleted file mode 100644 index 9dfb9dde..00000000 --- a/src/MiniPdf/Drawing/Font/Sources/FileSystemStreamSource.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Sources -{ - /// - /// Reads a font from a file on the local file system. - /// - public sealed class FileSystemStreamSource : IStreamSource - { - /// - /// Gets the absolute or relative path to the font file. - /// - public string FilePath { get; } - - /// - /// Initializes a new with the specified file path. - /// - /// The path to the font file. - public FileSystemStreamSource(string filePath) - { - if (string.IsNullOrWhiteSpace(filePath)) - throw new ArgumentException("File path must not be empty.", nameof(filePath)); - FilePath = filePath; - } - - /// - public Stream GetFontStream() => File.OpenRead(FilePath); - } -} diff --git a/src/MiniPdf/Drawing/Font/Sources/FontDefinition.cs b/src/MiniPdf/Drawing/Font/Sources/FontDefinition.cs deleted file mode 100644 index a1c80a14..00000000 --- a/src/MiniPdf/Drawing/Font/Sources/FontDefinition.cs +++ /dev/null @@ -1,43 +0,0 @@ -using MiniSoftware.Drawing.Font.Core; -using System; - -namespace MiniSoftware.Drawing.Font.Sources -{ - /// - /// Fully describes how to locate and load a font: its declared - /// and one or more entries (most fonts have a single - /// file; Type 1 may supply a .pfb and an optional .afm). - /// - public sealed class FontDefinition - { - /// Declared format of the font. - public FontType FontType { get; } - - /// Ordered list of file definitions that together make up the font. - public FontFileDefinition[] FileDefinitions { get; } - - /// - /// Convenience constructor for single-file fonts (TTF, OTF, CFF, WOFF, WOFF2). - /// - public FontDefinition(FontType fontType, FontFileDefinition fileDefinition) - { - FontType = fontType; - FileDefinitions = new[] - { - fileDefinition ?? throw new ArgumentNullException(nameof(fileDefinition)) - }; - } - - /// - /// Constructor for fonts that span multiple files (e.g. Type 1: .pfb + .afm). - /// - public FontDefinition(FontType fontType, FontFileDefinition[] fileDefinitions) - { - if (fileDefinitions == null || fileDefinitions.Length == 0) - throw new ArgumentException( - "At least one file definition is required.", nameof(fileDefinitions)); - FontType = fontType; - FileDefinitions = fileDefinitions; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Sources/FontFileDefinition.cs b/src/MiniPdf/Drawing/Font/Sources/FontFileDefinition.cs deleted file mode 100644 index 4d8d4266..00000000 --- a/src/MiniPdf/Drawing/Font/Sources/FontFileDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Sources -{ - /// - /// Pairs a file-extension hint (e.g. "ttf", "otf", "cff", "pfb") with the - /// that provides the raw font bytes. - /// - public sealed class FontFileDefinition - { - /// - /// File extension without the leading dot, lower-case (e.g. "ttf", "woff2"). - /// Used as a hint when the font format cannot be inferred from the stream magic bytes. - /// - public string FileExtension { get; } - - /// - /// Gets the source from which the font bytes are obtained. - /// - public IStreamSource Source { get; } - - /// - /// Initializes a new with the specified file extension and source. - /// - /// The file extension without the leading dot (e.g. "ttf", "otf"). - /// The source from which the font bytes are obtained. - public FontFileDefinition(string fileExtension, IStreamSource source) - { - if (string.IsNullOrWhiteSpace(fileExtension)) - throw new ArgumentException("File extension must not be empty.", nameof(fileExtension)); - FileExtension = fileExtension.TrimStart('.').ToLowerInvariant(); - Source = source ?? throw new ArgumentNullException(nameof(source)); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Sources/IStreamSource.cs b/src/MiniPdf/Drawing/Font/Sources/IStreamSource.cs deleted file mode 100644 index d8677750..00000000 --- a/src/MiniPdf/Drawing/Font/Sources/IStreamSource.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.IO; - -namespace MiniSoftware.Drawing.Font.Sources -{ - /// - /// Provides a readable containing raw font bytes. - /// Each call to must return a freshly opened, - /// independently positioned stream that the caller owns and must dispose. - /// - public interface IStreamSource - { - /// - /// Opens and returns a stream over the font data. - /// The caller is responsible for disposing the returned stream. - /// - Stream GetFontStream(); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/GlyphOutlineData.cs b/src/MiniPdf/Drawing/Font/Ttf/Glyphs/GlyphOutlineData.cs deleted file mode 100644 index 12c95f3d..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/GlyphOutlineData.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Ttf.Glyphs -{ - /// - /// Parsed outline data for one glyph, as extracted from the "glyf" table. - /// - public sealed class GlyphOutlineData - { - /// True for composite glyphs (numberOfContours == −1 in the glyf header). - public bool IsComposite { get; } - - /// - /// Non-null for simple (non-composite) glyphs, including zero-contour empty glyphs. - /// - public TtfSimpleGlyph? Simple { get; } - - /// Non-null for composite glyphs. - public TtfCompositeGlyph? Composite { get; } - - /// Design-space bounding box read from the glyph header. - public GlyphBoundingBox BBox { get; } - - /// - /// Initializes a new with the specified values. - /// - /// True for composite glyphs. - /// Non-null for simple (non-composite) glyphs. - /// Non-null for composite glyphs. - /// Design-space bounding box read from the glyph header. - public GlyphOutlineData( - bool isComposite, - TtfSimpleGlyph? simple, - TtfCompositeGlyph? composite, - GlyphBoundingBox bbox) - { - IsComposite = isComposite; - Simple = simple; - Composite = composite; - BBox = bbox; - } - - /// Outline for an empty glyph (e.g. space — no contours, no bbox). - public static readonly GlyphOutlineData Empty = - new GlyphOutlineData(false, TtfSimpleGlyph.Empty, null, GlyphBoundingBox.Empty); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfCompositeGlyph.cs b/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfCompositeGlyph.cs deleted file mode 100644 index 29e09331..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfCompositeGlyph.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Ttf.Glyphs -{ - /// - /// One component entry within a TrueType composite glyph. - /// - public sealed class TtfCompositeComponent - { - /// Glyph index of the referenced component glyph. - public ushort GlyphIndex { get; } - - /// - /// 2×3 affine transformation matrix applied to the component: - /// - /// | Transform[0,0] Transform[0,1] Transform[0,2] | | a b dx | - /// | Transform[1,0] Transform[1,1] Transform[1,2] | = | c d dy | - /// - /// Point transform: x' = a·x + b·y + dx, y' = c·x + d·y + dy.
- /// Identity (pure translation): a=1, b=0, c=0, d=1. - ///
- public float[,] Transform { get; } - - /// - /// True when Transform[0,2] and Transform[1,2] are xy offsets. - /// False when Arg1/Arg2 are matched point indices (anchor alignment). - /// - public bool ArgsAreXYValues { get; } - - /// - /// Raw Arg1 from the component record. - /// When is false, this is a point index in the - /// composite glyph outline (matched to in the component). - /// - public short Arg1 { get; } - - /// - /// Raw Arg2 from the component record. - /// When is false, this is a point index in the - /// component glyph outline. - /// - public short Arg2 { get; } - - internal TtfCompositeComponent( - ushort glyphIndex, - float[,] transform, - bool argsAreXYValues, - short arg1, short arg2) - { - GlyphIndex = glyphIndex; - Transform = transform; - ArgsAreXYValues = argsAreXYValues; - Arg1 = arg1; - Arg2 = arg2; - } - } - - // ───────────────────────────────────────────────────────────────────────── - - /// - /// Represents a composite TrueType glyph: an ordered list of component - /// glyphs each with its own affine transformation. - /// - public sealed class TtfCompositeGlyph - { - /// Component records in render order. - public TtfCompositeComponent[] Components { get; } - - /// Hinting instructions for the assembled composite (may be empty). - public byte[] Instructions { get; } - - internal TtfCompositeGlyph(TtfCompositeComponent[] components, byte[] instructions) - { - Components = components ?? Array.Empty(); - Instructions = instructions ?? Array.Empty(); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfPoint.cs b/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfPoint.cs deleted file mode 100644 index 037d2b54..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfPoint.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Ttf.Glyphs -{ - /// - /// A single point in a TrueType glyph outline contour. - /// Coordinates are in font design units (integers). - /// - public readonly struct TtfPoint - { - /// X coordinate in design units. - public short X { get; } - - /// Y coordinate in design units. - public short Y { get; } - - /// - /// True if this point lies on the curve (explicit line segment endpoint or spline endpoint). - /// False if this is an off-curve quadratic Bézier control point. - /// - public bool OnCurve { get; } - - /// - /// True if this point is the last point of its contour - /// (i.e. its index appears in endPtsOfContours). - /// - public bool IsEndPoint { get; } - - /// - /// Initializes a new with the specified coordinates and flags. - /// - /// The X coordinate in design units. - /// The Y coordinate in design units. - /// True if this point lies on the curve; false if it is an off-curve control point. - /// True if this point is the last point of its contour. - public TtfPoint(short x, short y, bool onCurve, bool isEndPoint) - { - X = x; - Y = y; - OnCurve = onCurve; - IsEndPoint = isEndPoint; - } - - /// - /// Returns a string representation of this . - /// - /// A string in the format "(x, y) on/off end". - public override string ToString() => - $"({X}, {Y}) {(OnCurve ? "on" : "off")}{(IsEndPoint ? " end" : "")}"; - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfSimpleGlyph.cs b/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfSimpleGlyph.cs deleted file mode 100644 index 00ecd3ea..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Glyphs/TtfSimpleGlyph.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Ttf.Glyphs -{ - /// - /// Represents a TrueType simple-glyph outline: contour data parsed from - /// a non-composite, non-empty entry in the "glyf" table. - /// - public sealed class TtfSimpleGlyph - { - /// Number of closed contours. - public int NumberOfContours { get; } - - /// - /// All points of all contours, in order. - /// Use to determine contour boundaries. - /// - public TtfPoint[] Points { get; } - - /// - /// Index (into ) of the last point of each contour. - /// Length == . - /// - public ushort[] EndPtsOfContours { get; } - - /// TrueType hinting instructions (may be empty). - public byte[] Instructions { get; } - - /// - /// Initializes a new with the specified contour data. - /// - /// Number of closed contours. - /// All points of all contours, in order. - /// Index into Points of the last point of each contour. - /// TrueType hinting instructions. - public TtfSimpleGlyph( - int numberOfContours, - TtfPoint[] points, - ushort[] endPtsOfContours, - byte[] instructions) - { - NumberOfContours = numberOfContours; - Points = points ?? Array.Empty(); - EndPtsOfContours = endPtsOfContours ?? Array.Empty(); - Instructions = instructions ?? Array.Empty(); - } - - /// A zero-contour simple glyph (e.g. space character). - public static readonly TtfSimpleGlyph Empty = - new TtfSimpleGlyph(0, Array.Empty(), Array.Empty(), Array.Empty()); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfAvarTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfAvarTable.cs deleted file mode 100644 index d118fffe..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfAvarTable.cs +++ /dev/null @@ -1,152 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "avar" (axis variations) table. - /// Stores piecewise-linear segment maps that remap default-normalized axis - /// values to final normalized values. - /// Ref: OpenType spec §table-avar. - /// - public sealed class TtfAvarTable : TtfTableBase - { - /// - /// The table tag for the avar table. - /// - public const string TableTag = "avar"; - - // ── Internal structures ─────────────────────────────────────────────── - - private readonly struct AxisValueMap - { - public readonly short From; // F2Dot14: signed, /16384.0 → [-2, ~2) - public readonly short To; - public AxisValueMap(short from, short to) { From = from; To = to; } - } - - /// Per-axis segment maps (indexed in fvar axis order). - private readonly AxisValueMap[]?[] _segments; - - private TtfAvarTable(byte[] rawBytes, AxisValueMap[]?[] segments) - : base(TableTag, rawBytes) - { - _segments = segments; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// Number of segment maps (one per variation axis, in fvar order). - public int SegmentCount => _segments.Length; - - /// - /// Applies the avar piecewise-linear segment map for the given axis index to - /// (a default-normalized value in [-1, 1]). - /// Returns unchanged if the axis index is - /// out of range or no segment map is defined for it. - /// - public double ApplySegmentMap(int axisIndex, double normalizedValue) - { - if (axisIndex < 0 || axisIndex >= _segments.Length) - return normalizedValue; - - AxisValueMap[]? maps = _segments[axisIndex]; - if (maps == null || maps.Length == 0) - return normalizedValue; - - return Interpolate(maps, normalizedValue); - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "avar" table from its raw bytes. - public static TtfAvarTable Parse(byte[] rawBytes) - { - // avar v1 header: majorVersion(2) + minorVersion(2) + reserved(2) + segmentCount(2) = 8 bytes - if (rawBytes == null || rawBytes.Length < 8) - return Empty(rawBytes ?? Array.Empty()); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - ushort majorVersion = reader.ReadUInt16(); - ushort minorVersion = reader.ReadUInt16(); - ushort reserved = reader.ReadUInt16(); - ushort segmentCount = reader.ReadUInt16(); - - // Only v1 is handled; v2 adds a second lookup table after the v1 data. - // For v2, we still parse the v1 segment maps. - if (majorVersion != 1 && majorVersion != 2) - return Empty(rawBytes); - - var segments = new AxisValueMap[segmentCount][]; - for (int s = 0; s < segmentCount; s++) - { - if (reader.Position + 2 > reader.Length) - break; - - ushort pairCount = reader.ReadUInt16(); - if (reader.Position + (long)pairCount * 4 > reader.Length) - break; - - var maps = new AxisValueMap[pairCount]; - for (int p = 0; p < pairCount; p++) - { - short from = reader.ReadInt16(); - short to = reader.ReadInt16(); - maps[p] = new AxisValueMap(from, to); - } - segments[s] = maps; - } - - // Fill any segments not yet parsed (corrupt table) with empty arrays. - for (int s = 0; s < segmentCount; s++) - if (segments[s] == null) - segments[s] = Array.Empty(); - - return new TtfAvarTable(rawBytes, (AxisValueMap[]?[])segments); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static TtfAvarTable Empty(byte[] rawBytes) => - new TtfAvarTable(rawBytes, Array.Empty()); - - /// - /// Applies piecewise linear interpolation using F2Dot14-encoded segment maps. - /// The input and output are floating-point values in [-1.0, 1.0]. - /// - private static double Interpolate(AxisValueMap[] maps, double value) - { - int n = maps.Length; - if (n == 0) return value; - - double fromFirst = maps[0].From / 16384.0; - double fromLast = maps[n - 1].From / 16384.0; - - // Clamp to the mapped range. - if (value <= fromFirst) return maps[0].To / 16384.0; - if (value >= fromLast) return maps[n - 1].To / 16384.0; - - // Binary search for the segment containing value. - int lo = 0, hi = n - 2; - while (lo < hi) - { - int mid = (lo + hi + 1) / 2; - if (maps[mid].From / 16384.0 <= value) - lo = mid; - else - hi = mid - 1; - } - - double f0 = maps[lo].From / 16384.0; - double f1 = maps[lo + 1].From / 16384.0; - double t0 = maps[lo].To / 16384.0; - double t1 = maps[lo + 1].To / 16384.0; - - // Linear interpolation within the segment. - double frac = (value - f0) / (f1 - f0); - return t0 + frac * (t1 - t0); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat0Table.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat0Table.cs deleted file mode 100644 index 978c7c43..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat0Table.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// CMap format 0: simple byte-array mapping of code points 0–255. - /// Each entry is a single byte glyph index. - /// Ref: OpenType spec §5.6.1.1.1. - /// - public sealed class TtfCMapFormat0Table : TtfCMapFormatBaseTable - { - private readonly byte[] _glyphIdArray; // 256 entries - - private TtfCMapFormat0Table(ushort platformId, ushort encodingId, byte[] glyphIdArray) - : base(platformId, encodingId, format: 0) - { - _glyphIdArray = glyphIdArray; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Full "cmap" table raw bytes. - /// Byte offset of this subtable within . - internal static TtfCMapFormat0Table Parse( - byte[] cmapBytes, int subtableOffset, - ushort platformId, ushort encodingId) - { - using var reader = new FontBinaryReader(new MemoryStream(cmapBytes)); - reader.Seek(subtableOffset); - reader.Skip(2); // format (= 0) - reader.Skip(2); // length - reader.Skip(2); // language - byte[] glyphIds = reader.ReadBytes(256); - return new TtfCMapFormat0Table(platformId, encodingId, glyphIds); - } - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - public override uint GetGlyphIndex(uint codePoint) - { - if (codePoint > 255) return 0; - return _glyphIdArray[(int)codePoint]; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat12Table.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat12Table.cs deleted file mode 100644 index 697a9db0..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat12Table.cs +++ /dev/null @@ -1,87 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// CMap format 12: segmented coverage mapping for the full Unicode range (U+0000–U+10FFFF). - /// Each group specifies a contiguous run of code points that maps linearly to a - /// contiguous run of glyph indices. - /// Ref: OpenType spec §5.6.1.1.12. - /// - public sealed class TtfCMapFormat12Table : TtfCMapFormatBaseTable - { - private readonly int _groupCount; - private readonly uint[] _startCharCode; - private readonly uint[] _endCharCode; - private readonly uint[] _startGlyphId; - - private TtfCMapFormat12Table( - ushort platformId, ushort encodingId, - int groupCount, - uint[] startCharCode, uint[] endCharCode, uint[] startGlyphId) - : base(platformId, encodingId, format: 12) - { - _groupCount = groupCount; - _startCharCode = startCharCode; - _endCharCode = endCharCode; - _startGlyphId = startGlyphId; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Full "cmap" table raw bytes. - /// Byte offset of this subtable within . - internal static TtfCMapFormat12Table? Parse( - byte[] cmapBytes, int subtableOffset, - ushort platformId, ushort encodingId) - { - using var reader = new FontBinaryReader(new MemoryStream(cmapBytes)); - reader.Seek(subtableOffset); - - reader.Skip(2); // format (= 12) - reader.Skip(2); // reserved (= 0) - reader.Skip(4); // length (uint32) - reader.Skip(4); // language (uint32) - - uint numGroups = reader.ReadUInt32(); - if (numGroups == 0) return null; - - int count = (int)numGroups; - var startCharCode = new uint[count]; - var endCharCode = new uint[count]; - var startGlyphId = new uint[count]; - - for (int i = 0; i < count; i++) - { - startCharCode[i] = reader.ReadUInt32(); - endCharCode[i] = reader.ReadUInt32(); - startGlyphId[i] = reader.ReadUInt32(); - } - - return new TtfCMapFormat12Table( - platformId, encodingId, count, - startCharCode, endCharCode, startGlyphId); - } - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - public override uint GetGlyphIndex(uint codePoint) - { - // Binary search through groups. - int lo = 0, hi = _groupCount - 1; - while (lo <= hi) - { - int mid = (lo + hi) >> 1; - if (codePoint < _startCharCode[mid]) - hi = mid - 1; - else if (codePoint > _endCharCode[mid]) - lo = mid + 1; - else - return _startGlyphId[mid] + (codePoint - _startCharCode[mid]); - } - return 0; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat4Table.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat4Table.cs deleted file mode 100644 index 2979d4bf..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormat4Table.cs +++ /dev/null @@ -1,146 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// CMap format 4: segmented BMP character-to-glyph-index mapping. - /// Covers Unicode code points in the range U+0000–U+FFFF using a - /// series of contiguous segments defined by start/end code arrays. - /// Ref: OpenType spec §5.6.1.1.4. - /// - public sealed class TtfCMapFormat4Table : TtfCMapFormatBaseTable - { - private readonly int _segCount; - private readonly ushort[] _endCount; - private readonly ushort[] _startCount; - private readonly short[] _idDelta; - private readonly ushort[] _idRangeOffset; - private readonly ushort[] _glyphIdArray; - - private TtfCMapFormat4Table( - ushort platformId, ushort encodingId, - int segCount, - ushort[] endCount, ushort[] startCount, - short[] idDelta, ushort[] idRangeOffset, - ushort[] glyphIdArray) - : base(platformId, encodingId, format: 4) - { - _segCount = segCount; - _endCount = endCount; - _startCount = startCount; - _idDelta = idDelta; - _idRangeOffset = idRangeOffset; - _glyphIdArray = glyphIdArray; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Full "cmap" table raw bytes. - /// Byte offset of this subtable within . - internal static TtfCMapFormat4Table? Parse( - byte[] cmapBytes, int subtableOffset, - ushort platformId, ushort encodingId) - { - using var reader = new FontBinaryReader(new MemoryStream(cmapBytes)); - reader.Seek(subtableOffset); - - reader.Skip(2); // format (= 4) - ushort length = reader.ReadUInt16(); - reader.Skip(2); // language - ushort segCountX2 = reader.ReadUInt16(); - reader.Skip(6); // searchRange, entrySelector, rangeShift - - int segCount = segCountX2 / 2; - if (segCount <= 0) return null; - - var endCount = new ushort[segCount]; - for (int i = 0; i < segCount; i++) - endCount[i] = reader.ReadUInt16(); - - reader.Skip(2); // reservedPad - - var startCount = new ushort[segCount]; - for (int i = 0; i < segCount; i++) - startCount[i] = reader.ReadUInt16(); - - var idDelta = new short[segCount]; - for (int i = 0; i < segCount; i++) - idDelta[i] = reader.ReadInt16(); - - var idRangeOffset = new ushort[segCount]; - for (int i = 0; i < segCount; i++) - idRangeOffset[i] = reader.ReadUInt16(); - - // glyphIdArray fills the remaining bytes in the subtable. - // Header bytes consumed: 2(fmt)+2(len)+2(lang)+2(segCountX2)+6(search fields) = 14 - // + segCount×2(endCount) + 2(pad) + segCount×2(start) + segCount×2(delta) + segCount×2(range) = 2 + segCount×8 - // Total = 16 + segCount×8 - int glyphIdArrayBytes = (int)length - 16 - segCount * 8; - int glyphIdCount = glyphIdArrayBytes > 0 ? glyphIdArrayBytes / 2 : 0; - - var glyphIdArray = new ushort[glyphIdCount]; - for (int i = 0; i < glyphIdCount; i++) - glyphIdArray[i] = reader.ReadUInt16(); - - return new TtfCMapFormat4Table( - platformId, encodingId, segCount, - endCount, startCount, idDelta, idRangeOffset, glyphIdArray); - } - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - /// - /// Standard OpenType format 4 lookup: - /// binary-searches segments by endCount, then applies - /// idDelta or the glyphIdArray indirection. - /// - public override uint GetGlyphIndex(uint codePoint) - { - if (codePoint > 0xFFFF) return 0; - ushort cp = (ushort)codePoint; - - // Binary search: find the leftmost segment where endCount[i] >= cp. - int lo = 0, hi = _segCount - 1, segIndex = -1; - while (lo <= hi) - { - int mid = (lo + hi) >> 1; - if (_endCount[mid] < cp) - lo = mid + 1; - else - { - segIndex = mid; - hi = mid - 1; // keep searching left for leftmost match - } - } - - if (segIndex < 0 || _startCount[segIndex] > cp) - return 0; - - if (_idRangeOffset[segIndex] == 0) - { - // Simple offset: apply idDelta (mod 65536). - return (uint)(((int)cp + _idDelta[segIndex]) & 0xFFFF); - } - else - { - // Pointer indirection via glyphIdArray. - // Index = (segIndex + idRangeOffset[i]/2 + (cp - startCount[i])) - segCount - // See OpenType spec §5.6.1.1.4 for the derivation of this formula. - int glyphIdArrayIndex = - segIndex - + _idRangeOffset[segIndex] / 2 - + (cp - _startCount[segIndex]) - - _segCount; - - if (glyphIdArrayIndex < 0 || glyphIdArrayIndex >= _glyphIdArray.Length) - return 0; - - ushort rawGlyphId = _glyphIdArray[glyphIdArrayIndex]; - if (rawGlyphId == 0) return 0; - return (uint)((rawGlyphId + _idDelta[segIndex]) & 0xFFFF); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormatBaseTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormatBaseTable.cs deleted file mode 100644 index 3d77bba8..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapFormatBaseTable.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Abstract base for a parsed OpenType CMap format subtable. - /// Concrete implementations: (format 0), - /// (format 4, BMP), - /// (format 12, full Unicode). - /// - public abstract class TtfCMapFormatBaseTable - { - /// Platform identifier (0=Unicode, 1=Macintosh, 3=Windows). - public ushort PlatformId { get; } - - /// Platform-specific encoding identifier. - public ushort PlatformSpecificId { get; } - - /// CMap subtable format number (0, 4, 12, etc.). - public ushort Format { get; } - - /// - /// Initializes a new with the specified parameters. - /// - /// Platform identifier (0=Unicode, 1=Macintosh, 3=Windows). - /// Platform-specific encoding identifier. - /// CMap subtable format number. - protected TtfCMapFormatBaseTable(ushort platformId, ushort platformSpecificId, ushort format) - { - PlatformId = platformId; - PlatformSpecificId = platformSpecificId; - Format = format; - } - - /// - /// Maps a Unicode code point to a glyph index. - /// Returns 0 (.notdef) when no glyph is mapped for the code point. - /// - public abstract uint GetGlyphIndex(uint codePoint); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapTable.cs deleted file mode 100644 index f9dfed51..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCMapTable.cs +++ /dev/null @@ -1,136 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "cmap" table (character-to-glyph-index mapping). - /// Reads all encoding records from the table directory and parses the - /// unique subtables; exposes to select the - /// best subtable for Unicode text shaping. - /// Ref: OpenType spec §5.6. - /// - public sealed class TtfCMapTable : TtfTableBase - { - /// - /// The table tag for the cmap table. - /// - public const string TableTag = "cmap"; - - private readonly IReadOnlyList _subtables; - - private TtfCMapTable(byte[] rawBytes, IReadOnlyList subtables) - : base(TableTag, rawBytes) - { - _subtables = subtables; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "cmap" table from its raw bytes. - public static TtfCMapTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - reader.Skip(2); // version (USHORT, should be 0) - ushort numTables = reader.ReadUInt16(); - - // Read encoding records. - var encodingRecords = new (ushort platformId, ushort encodingId, uint offset)[numTables]; - for (int i = 0; i < numTables; i++) - { - ushort platformId = reader.ReadUInt16(); - ushort encodingId = reader.ReadUInt16(); - uint offset = reader.ReadUInt32(); - encodingRecords[i] = (platformId, encodingId, offset); - } - - // Parse unique subtables (multiple encoding records may share the same subtable). - var seenOffsets = new HashSet(); - var subtables = new List(); - - foreach (var rec in encodingRecords) - { - if (!seenOffsets.Add(rec.offset)) continue; - if (rec.offset + 2 > (uint)rawBytes.Length) continue; - - var subtable = ParseSubtable(rawBytes, (int)rec.offset, rec.platformId, rec.encodingId); - if (subtable != null) - subtables.Add(subtable); - } - - return new TtfCMapTable(rawBytes, subtables); - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// All parsed CMap subtables. - public IReadOnlyList Subtables => _subtables; - - /// - /// Finds the best Unicode-capable subtable. - /// Priority order: - /// - /// Format 12, platform 0 or 3 (full Unicode coverage) - /// Format 12, any platform - /// Format 4, platform 3 (Windows BMP) - /// Format 4, platform 0 (Unicode BMP) - /// Format 4, any platform - /// - /// Returns null if no usable Unicode subtable is found. - /// - public TtfCMapFormatBaseTable? FindUnicodeTable() - { - TtfCMapFormatBaseTable? best = null; - int bestPriority = -1; - - foreach (var subtable in _subtables) - { - int priority = GetPriority(subtable); - if (priority > bestPriority) - { - best = subtable; - bestPriority = priority; - } - } - - return best; - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static int GetPriority(TtfCMapFormatBaseTable t) - { - if (t.Format == 12 && (t.PlatformId == 0 || t.PlatformId == 3)) return 100; - if (t.Format == 12) return 90; - if (t.Format == 4 && t.PlatformId == 3) return 80; - if (t.Format == 4 && t.PlatformId == 0) return 70; - if (t.Format == 4) return 60; - return -1; // formats 0, 6 etc. are never preferred over 4/12 - } - - private static TtfCMapFormatBaseTable? ParseSubtable( - byte[] cmapBytes, int subtableOffset, - ushort platformId, ushort encodingId) - { - if (subtableOffset < 0 || subtableOffset + 2 > cmapBytes.Length) - return null; - - // Read the format field (big-endian ushort) from the raw bytes. - ushort format = (ushort)((cmapBytes[subtableOffset] << 8) | cmapBytes[subtableOffset + 1]); - - switch (format) - { - case 0: - return TtfCMapFormat0Table.Parse(cmapBytes, subtableOffset, platformId, encodingId); - case 4: - return TtfCMapFormat4Table.Parse(cmapBytes, subtableOffset, platformId, encodingId); - case 12: - return TtfCMapFormat12Table.Parse(cmapBytes, subtableOffset, platformId, encodingId); - default: - return null; // unsupported format; not an error - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCbdtTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCbdtTable.cs deleted file mode 100644 index c690be48..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCbdtTable.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "CBDT" (Color Bitmap Data) table. - /// Exposes colour bitmap images (typically PNG) for individual glyphs. - /// Requires the companion "CBLC" table to be parsed first; pass a - /// to . - /// Ref: OpenType spec §table-CBDT. - /// - public sealed class TtfCbdtTable : TtfTableBase - { - /// - /// The table tag for the CBDT table. - /// - public const string TableTag = "CBDT"; - - private readonly TtfCblcTable _cblc; - - /// - /// Raw bytes of the companion "CBLC" table, needed when re-serialising the font. - /// - internal byte[] CblcRawBytes { get; } - - private TtfCbdtTable(byte[] rawBytes, byte[] cblcRawBytes, TtfCblcTable cblc) - : base(TableTag, rawBytes) - { - CblcRawBytes = cblcRawBytes ?? throw new ArgumentNullException(nameof(cblcRawBytes)); - _cblc = cblc; - } - - // ── Properties ──────────────────────────────────────────────────────── - - /// Number of bitmap strikes exposed by the CBLC companion table. - public int StrikeCount => _cblc.StrikeCount; - - /// Pixels-per-em (X axis) for the given strike, or 0 when out of range. - public int GetStrikePpemX(int strikeIndex) => _cblc.GetStrikePpemX(strikeIndex); - - /// Pixels-per-em (Y axis) for the given strike, or 0 when out of range. - public int GetStrikePpemY(int strikeIndex) => _cblc.GetStrikePpemY(strikeIndex); - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - /// Returns the raw image bytes (PNG) for in - /// , or when the glyph - /// is absent from that strike. - /// - /// - /// The metrics header prepended by CBDT image formats 17/18/19 is stripped; - /// the returned bytes always begin with the raw PNG signature when the - /// underlying image is encoded as PNG. - /// - public byte[]? GetGlyphBitmap(int glyphIndex, int strikeIndex = 0) - { - var loc = _cblc.GetGlyphLocation(glyphIndex, strikeIndex); - if (loc == null) return null; - - var location = loc.Value; - if (location.Length == 0) return null; - - int blobStart = (int)location.CbdtOffset; - int blobLen = (int)location.Length; - - if (blobStart < 0 || (long)blobStart + blobLen > RawBytes.Length) return null; - - // Strip the per-format metrics/length header so callers always receive - // the raw image data (PNG signature at byte 0). - // - // Format 17: SmallGlyphMetrics (5) + dataLen (4) = 9 bytes - // Format 18: BigGlyphMetrics (8) + dataLen (4) = 12 bytes - // Format 19: dataLen (4) = 4 bytes - int skip = location.ImageFormat switch - { - 17 => 9, - 18 => 12, - 19 => 4, - _ => 0 - }; - - if (skip >= blobLen) return null; - - int dataLen = blobLen - skip; - var result = new byte[dataLen]; - Array.Copy(RawBytes, blobStart + skip, result, 0, dataLen); - return result; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// - /// Parses the "CBDT" table together with a pre-parsed - /// . - /// - /// Raw bytes of the CBDT table. - /// Raw bytes of the companion CBLC table (stored for serialisation). - /// Pre-parsed CBLC companion table. - internal static TtfCbdtTable Parse(byte[] rawBytes, byte[] cblcRawBytes, TtfCblcTable cblcTable) - { - if (rawBytes == null) rawBytes = Array.Empty(); - if (cblcRawBytes == null) cblcRawBytes = Array.Empty(); - if (cblcTable == null) throw new ArgumentNullException(nameof(cblcTable)); - return new TtfCbdtTable(rawBytes, cblcRawBytes, cblcTable); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCblcTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCblcTable.cs deleted file mode 100644 index d89bc258..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfCblcTable.cs +++ /dev/null @@ -1,263 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "CBLC" (Color Bitmap Location) table. - /// Stores per-glyph offset information that is used together with "CBDT" - /// to retrieve colour bitmap images. - /// This type is an internal helper; callers use . - /// Ref: OpenType spec §table-CBLC. - /// - internal sealed class TtfCblcTable - { - internal const string TableTag = "CBLC"; - - // ── Internal location result ────────────────────────────────────────── - - internal struct GlyphBitmapLocation - { - /// Byte offset from the start of the CBDT byte array. - internal uint CbdtOffset; - /// Number of bytes in the CBDT blob for this glyph. - internal uint Length; - /// CBDT image format (17 = SmallMetrics+PNG, 18 = BigMetrics+PNG, 19 = raw PNG). - internal int ImageFormat; - } - - // ── Internal data structures ────────────────────────────────────────── - - private struct SubTableEntry - { - internal int FirstGlyphIndex; - internal int LastGlyphIndex; - internal int IndexFormat; // 1, 2, or 3 - internal int ImageFormat; - internal uint ImageDataOffset; // offset in CBDT - // Formats 1 & 3: offset[glyphCount + 1] (relative to ImageDataOffset) - internal uint[]? GlyphOffsets; - // Format 2: constant image size - internal uint ImageSize; - } - - private struct StrikeInfo - { - internal int StartGlyphIndex; - internal int EndGlyphIndex; - internal int PpemX; - internal int PpemY; - internal SubTableEntry[] SubTables; - } - - private readonly StrikeInfo[] _strikes; - - private TtfCblcTable(StrikeInfo[] strikes) { _strikes = strikes; } - - // ── Properties ──────────────────────────────────────────────────────── - - /// Number of bitmap strikes (one per ppem size) in this font. - internal int StrikeCount => _strikes.Length; - - internal int GetStrikePpemX(int strikeIndex) => - strikeIndex >= 0 && strikeIndex < _strikes.Length ? _strikes[strikeIndex].PpemX : 0; - - internal int GetStrikePpemY(int strikeIndex) => - strikeIndex >= 0 && strikeIndex < _strikes.Length ? _strikes[strikeIndex].PpemY : 0; - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - /// Returns the CBDT location for the given glyph in the given strike, or - /// if the glyph is not present in that strike. - /// - internal GlyphBitmapLocation? GetGlyphLocation(int glyphIndex, int strikeIndex) - { - if (strikeIndex < 0 || strikeIndex >= _strikes.Length) return null; - - var strike = _strikes[strikeIndex]; - if (glyphIndex < strike.StartGlyphIndex || glyphIndex > strike.EndGlyphIndex) - return null; - - foreach (var sub in strike.SubTables) - { - if (glyphIndex < sub.FirstGlyphIndex || glyphIndex > sub.LastGlyphIndex) - continue; - - int idx = glyphIndex - sub.FirstGlyphIndex; - - if (sub.IndexFormat == 2) - { - // All glyphs in this subtable have the same size. - uint start = sub.ImageDataOffset + (uint)idx * sub.ImageSize; - return new GlyphBitmapLocation - { - CbdtOffset = start, - Length = sub.ImageSize, - ImageFormat = sub.ImageFormat - }; - } - - if (sub.GlyphOffsets == null || idx + 1 >= sub.GlyphOffsets.Length) - return null; - - uint gStart = sub.GlyphOffsets[idx]; - uint gEnd = sub.GlyphOffsets[idx + 1]; - if (gEnd <= gStart) return null; - - return new GlyphBitmapLocation - { - CbdtOffset = sub.ImageDataOffset + gStart, - Length = gEnd - gStart, - ImageFormat = sub.ImageFormat - }; - } - return null; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - private static readonly TtfCblcTable _empty = new TtfCblcTable(Array.Empty()); - - internal static TtfCblcTable Parse(byte[] rawBytes) - { - if (rawBytes == null || rawBytes.Length < 8) - return _empty; - - try - { - return ParseCore(rawBytes); - } - catch - { - return _empty; - } - } - - private static TtfCblcTable ParseCore(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // CBLC header - ushort majorVersion = reader.ReadUInt16(); - ushort minorVersion = reader.ReadUInt16(); - uint numSizes = reader.ReadUInt32(); - - if (numSizes == 0 || numSizes > 256) return _empty; - - var strikes = new StrikeInfo[numSizes]; - - // BitmapSize records start at offset 8 (immediately after the header). - for (uint s = 0; s < numSizes; s++) - { - // Each BitmapSize record is 48 bytes. - long bsBase = 8L + s * 48L; - if (bsBase + 48 > rawBytes.Length) break; - - reader.Seek(bsBase); - - uint isaOffset = reader.ReadUInt32(); // offset from CBLC start to IndexSubTableArray - uint indexTablesSize = reader.ReadUInt32(); - uint numberOfSubTables = reader.ReadUInt32(); - uint colorRef = reader.ReadUInt32(); // reserved - - // SbitLineMetrics hori (12 bytes) + vert (12 bytes) — skip - reader.Skip(24); - - ushort startGlyph = reader.ReadUInt16(); - ushort endGlyph = reader.ReadUInt16(); - byte ppemX = reader.ReadUInt8(); - byte ppemY = reader.ReadUInt8(); - byte bitDepth = reader.ReadUInt8(); - byte flags = reader.ReadUInt8(); - - if (numberOfSubTables == 0 || numberOfSubTables > 4096) continue; - - var subTables = new SubTableEntry[numberOfSubTables]; - - // IndexSubTableArray starts at isaOffset from the start of CBLC. - long isaBase = isaOffset; - if (isaBase + numberOfSubTables * 8L > rawBytes.Length) continue; - - for (uint st = 0; st < numberOfSubTables; st++) - { - // Each IndexSubTableArray entry: firstGlyphIndex(2) + lastGlyphIndex(2) + additionalOffset(4) - long entryOff = isaBase + st * 8L; - reader.Seek(entryOff); - - ushort firstG = reader.ReadUInt16(); - ushort lastG = reader.ReadUInt16(); - uint addOffset = reader.ReadUInt32(); - - // additionalOffset is relative to the start of the IndexSubTableArray. - long istBase = isaBase + addOffset; - if (istBase + 8 > rawBytes.Length) continue; - - reader.Seek(istBase); - - ushort indexFormat = reader.ReadUInt16(); - ushort imageFormat = reader.ReadUInt16(); - uint imageDataOffset = reader.ReadUInt32(); - - int glyphCount = lastG - firstG + 1; - if (glyphCount <= 0 || glyphCount > 65536) continue; - - var entry = new SubTableEntry - { - FirstGlyphIndex = firstG, - LastGlyphIndex = lastG, - IndexFormat = indexFormat, - ImageFormat = imageFormat, - ImageDataOffset = imageDataOffset - }; - - if (indexFormat == 1) - { - // Format 1: variable-width images, uint32 offsets array - int offsetCount = glyphCount + 1; - long arrEnd = istBase + 8L + offsetCount * 4L; - if (arrEnd > rawBytes.Length) { subTables[st] = entry; continue; } - - entry.GlyphOffsets = new uint[offsetCount]; - for (int oi = 0; oi < offsetCount; oi++) - entry.GlyphOffsets[oi] = reader.ReadUInt32(); - } - else if (indexFormat == 2) - { - // Format 2: constant-size images - if (istBase + 8 + 12 > rawBytes.Length) { subTables[st] = entry; continue; } - entry.ImageSize = reader.ReadUInt32(); - // BigGlyphMetrics (8 bytes) — skip - reader.Skip(8); - } - else if (indexFormat == 3) - { - // Format 3: variable-width images, uint16 offsets array - int offsetCount = glyphCount + 1; - long arrEnd = istBase + 8L + offsetCount * 2L; - if (arrEnd > rawBytes.Length) { subTables[st] = entry; continue; } - - entry.GlyphOffsets = new uint[offsetCount]; - for (int oi = 0; oi < offsetCount; oi++) - entry.GlyphOffsets[oi] = reader.ReadUInt16(); - } - // Formats 4/5 are not common; leave GlyphOffsets null (returns null on lookup). - - subTables[st] = entry; - } - - strikes[s] = new StrikeInfo - { - StartGlyphIndex = startGlyph, - EndGlyphIndex = endGlyph, - PpemX = ppemX, - PpemY = ppemY, - SubTables = subTables - }; - } - - return new TtfCblcTable(strikes); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfFvarTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfFvarTable.cs deleted file mode 100644 index 4d647616..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfFvarTable.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "fvar" (font variations) table. - /// Exposes the variation axes and named instances of a variable font. - /// Ref: OpenType spec §table-fvar. - /// - public sealed class TtfFvarTable : TtfTableBase - { - /// - /// The table tag for the fvar table. - /// - public const string TableTag = "fvar"; - - /// Design-variation axes defined in the font. - public IReadOnlyList Axes { get; } - - /// Named design instances (e.g. "Light", "Bold Condensed"). - public IReadOnlyList Instances { get; } - - private TtfFvarTable( - byte[] rawBytes, - List axes, - List instances) - : base(TableTag, rawBytes) - { - Axes = axes; - Instances = instances; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "fvar" table from its raw bytes. - public static TtfFvarTable Parse(byte[] rawBytes) - { - if (rawBytes == null || rawBytes.Length < 16) - return Empty(rawBytes ?? Array.Empty()); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // fvar header (16 bytes) - ushort majorVersion = reader.ReadUInt16(); // = 1 - ushort minorVersion = reader.ReadUInt16(); // = 0 - ushort axesArrayOffset = reader.ReadUInt16(); // offset from table start to axes array - ushort reserved = reader.ReadUInt16(); // = 2, ignored - ushort axisCount = reader.ReadUInt16(); - ushort axisSize = reader.ReadUInt16(); // should be 20 - ushort instanceCount = reader.ReadUInt16(); - ushort instanceSize = reader.ReadUInt16(); - - if (axisSize < 20 || axesArrayOffset + (long)axisCount * axisSize > rawBytes.Length) - return Empty(rawBytes); - - // ── Parse axes ──────────────────────────────────────────────────── - reader.Seek(axesArrayOffset); - var axes = new List(axisCount); - for (int i = 0; i < axisCount; i++) - { - long axisStart = reader.Position; - - string tag = reader.ReadTag().TrimEnd(); // 4 bytes - double minValue = reader.ReadFixed(); // 4 bytes, 16.16 fixed - double defaultValue = reader.ReadFixed(); // 4 bytes - double maxValue = reader.ReadFixed(); // 4 bytes - ushort axisFlags = reader.ReadUInt16(); // 2 bytes - ushort axisNameId = reader.ReadUInt16(); // 2 bytes → name table ID - - string axisName = GetWellKnownAxisName(tag); - axes.Add(new FontVariationAxis(tag, minValue, defaultValue, maxValue, axisName)); - - // Skip any extra bytes if axisSize > 20. - int consumed = (int)(reader.Position - axisStart); - if (consumed < axisSize) - reader.Skip(axisSize - consumed); - } - - // ── Parse named instances ───────────────────────────────────────── - // Each instance record: subfamilyNameID(2) + flags(2) + coordinates[axisCount](4 each) - // optionally: + postScriptNameID(2) when instanceSize == axisCount*4 + 6 - var instances = new List(instanceCount); - for (int i = 0; i < instanceCount; i++) - { - long instStart = reader.Position; - - ushort subfamilyNameId = reader.ReadUInt16(); - ushort instFlags = reader.ReadUInt16(); - - var coords = new Dictionary(axisCount); - for (int a = 0; a < axisCount; a++) - { - double coord = reader.ReadFixed(); - if (a < axes.Count) - coords[axes[a].Tag] = coord; - } - - // Skip optional postScriptNameID or any extra bytes. - int consumed = (int)(reader.Position - instStart); - if (consumed < instanceSize) - reader.Skip(instanceSize - consumed); - - // Instance name would require resolving subfamilyNameId via the name table. - // Use a placeholder; callers may resolve via TtfFont.Tables.Name. - instances.Add(new FontVariationInstance($"Instance {i + 1}", coords)); - } - - return new TtfFvarTable(rawBytes, axes, instances); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static TtfFvarTable Empty(byte[] rawBytes) => - new TtfFvarTable(rawBytes, - new List(), - new List()); - - /// Returns a human-readable name for well-known registered axis tags. - private static string GetWellKnownAxisName(string tag) - { - switch (tag) - { - case "wght": return "Weight"; - case "wdth": return "Width"; - case "ital": return "Italic"; - case "slnt": return "Slant"; - case "opsz": return "Optical Size"; - case "GRAD": return "Grade"; - case "MONO": return "Monospace"; - case "CASL": return "Casual"; - case "CRSV": return "Cursive"; - case "FILL": return "Fill"; - default: return tag; - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGdefTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGdefTable.cs deleted file mode 100644 index a2880f61..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGdefTable.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "GDEF" table — Glyph Definition table. - /// Exposes per-glyph classification (Base, Ligature, Mark, Component) via - /// . - /// - /// - /// Supports GDEF versions 1.0, 1.2, and 1.3. - /// Only the GlyphClassDef sub-table is parsed; AttachList, LigCaretList, - /// MarkAttachClassDef, MarkGlyphSets and ItemVarStore are skipped. - /// - /// ClassDef format 1 (contiguous range): stored as a flat array. - /// ClassDef format 2 (range records): stored as a sorted array and binary-searched. - /// - /// Ref: https://learn.microsoft.com/en-us/typography/opentype/spec/gdef - /// - public sealed class TtfGdefTable : TtfTableBase - { - /// - /// The table tag for the GDEF table. - /// - public const string TableTag = "GDEF"; - - // ── Storage for ClassDef ────────────────────────────────────────────── - - // Format 1: flat class array starting at _f1Start. - private readonly ushort _f1Start; - private readonly GlyphClass[]? _f1Classes; // non-null ↔ format 1 - - // Format 2: sorted range records. - private readonly ClassRange[]? _f2Ranges; // non-null ↔ format 2 - - private readonly struct ClassRange - { - public readonly ushort Start; - public readonly ushort End; - public readonly GlyphClass Class; - - public ClassRange(ushort start, ushort end, GlyphClass cls) - { - Start = start; - End = end; - Class = cls; - } - } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfGdefTable( - byte[] rawBytes, - ushort f1Start, - GlyphClass[]? f1Classes, - ClassRange[]? f2Ranges) - : base(TableTag, rawBytes) - { - _f1Start = f1Start; - _f1Classes = f1Classes; - _f2Ranges = f2Ranges; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Returns the of . - /// Returns when the glyph is not listed. - /// - public GlyphClass GetClass(ushort glyphId) - { - if (_f1Classes != null) - { - int idx = glyphId - _f1Start; - return (idx >= 0 && idx < _f1Classes.Length) - ? _f1Classes[idx] - : GlyphClass.Unclassified; - } - - if (_f2Ranges != null) - { - // Binary search over sorted range array. - int lo = 0, hi = _f2Ranges.Length - 1; - while (lo <= hi) - { - int mid = (lo + hi) >> 1; - var r = _f2Ranges[mid]; - if (glyphId < r.Start) hi = mid - 1; - else if (glyphId > r.End) lo = mid + 1; - else return r.Class; - } - } - - return GlyphClass.Unclassified; - } - - // ── Parser ──────────────────────────────────────────────────────────── - - /// Parses the "GDEF" table from its raw bytes. - public static TtfGdefTable Parse(byte[] rawBytes) - { - if (rawBytes is null) throw new ArgumentNullException(nameof(rawBytes)); - - if (rawBytes.Length < 12) - return Empty(rawBytes); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - /* majorVersion */ reader.ReadUInt16(); // 0 - /* minorVersion */ reader.ReadUInt16(); // 2 - ushort glyphClassDefOffset = reader.ReadUInt16(); // 4 — from table start; 0=absent - /* attachListOffset */ reader.ReadUInt16(); // 6 - /* ligCaretListOffset */ reader.ReadUInt16(); // 8 - /* markAttachClassDefOffset */ reader.ReadUInt16(); // 10 - - if (glyphClassDefOffset == 0 || glyphClassDefOffset >= rawBytes.Length) - return Empty(rawBytes); - - // ── ClassDef sub-table ──────────────────────────────────────────── - reader.Seek(glyphClassDefOffset); - - if (reader.Position + 2 > rawBytes.Length) return Empty(rawBytes); - - ushort classFormat = reader.ReadUInt16(); - - if (classFormat == 1) - { - // Format 1: contiguous glyph range. - if (reader.Position + 4 > rawBytes.Length) return Empty(rawBytes); - - ushort startGlyphID = reader.ReadUInt16(); - ushort glyphCount = reader.ReadUInt16(); - - var classes = new GlyphClass[glyphCount]; - for (int i = 0; i < glyphCount; i++) - { - if (reader.Position + 2 > rawBytes.Length) break; - classes[i] = (GlyphClass)reader.ReadUInt16(); - } - return new TtfGdefTable(rawBytes, startGlyphID, classes, null); - } - else if (classFormat == 2) - { - // Format 2: range records (startGlyphID, endGlyphID, class). - if (reader.Position + 2 > rawBytes.Length) return Empty(rawBytes); - - ushort rangeCount = reader.ReadUInt16(); - var ranges = new ClassRange[rangeCount]; - - for (int i = 0; i < rangeCount; i++) - { - if (reader.Position + 6 > rawBytes.Length) break; - ushort start = reader.ReadUInt16(); - ushort end = reader.ReadUInt16(); - ushort cls = reader.ReadUInt16(); - ranges[i] = new ClassRange(start, end, (GlyphClass)cls); - } - return new TtfGdefTable(rawBytes, 0, null, ranges); - } - - return Empty(rawBytes); - } - - private static TtfGdefTable Empty(byte[] rawBytes) => - new TtfGdefTable(rawBytes, 0, null, null); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGlyfTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGlyfTable.cs deleted file mode 100644 index 2fc0b379..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGlyfTable.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.IO; -using MiniSoftware.Drawing.Font.Ttf.Glyphs; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "glyf" table. - /// Provides lazy on-demand parsing of individual glyph outlines using the - /// "loca" table to locate each glyph's data within the raw byte array. - /// Ref: OpenType spec §5.3.3. - /// - public sealed class TtfGlyfTable : TtfTableBase - { - /// - /// The table tag for the glyf table. - /// - public const string TableTag = "glyf"; - - private readonly TtfLocaTable _loca; - - // ── Simple-glyph flag bits ──────────────────────────────────────────── - private const byte FlagOnCurve = 0x01; - private const byte FlagXShortVector = 0x02; - private const byte FlagYShortVector = 0x04; - private const byte FlagRepeat = 0x08; - private const byte FlagXSameOrPositive = 0x10; - private const byte FlagYSameOrPositive = 0x20; - - // ── Composite-glyph flag bits ───────────────────────────────────────── - private const ushort CompArg1And2AreWords = 0x0001; - private const ushort CompArgsAreXYValues = 0x0002; - private const ushort CompWeHaveAScale = 0x0008; - private const ushort CompMoreComponents = 0x0020; - private const ushort CompWeHaveAnXAndYScale = 0x0040; - private const ushort CompWeHaveATwoByTwo = 0x0080; - private const ushort CompWeHaveInstructions = 0x0100; - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfGlyfTable(byte[] rawBytes, TtfLocaTable loca) - : base(TableTag, rawBytes) - { - _loca = loca; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// - /// Wraps the raw "glyf" table bytes together with the parsed "loca" table. - /// No parsing is performed at construction time; glyphs are parsed on demand. - /// - public static TtfGlyfTable Create(byte[] rawBytes, TtfLocaTable loca) - { - if (rawBytes == null) throw new ArgumentNullException(nameof(rawBytes)); - if (loca == null) throw new ArgumentNullException(nameof(loca)); - return new TtfGlyfTable(rawBytes, loca); - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Parses and returns the outline data for the glyph at - /// . - /// Returns for glyphs with no outlines - /// (e.g. the space character) and null for out-of-range indices or - /// corrupt data. - /// - public GlyphOutlineData? GetGlyphOutline(int glyphIndex) - { - if (glyphIndex < 0) return null; - - uint offset = _loca.GetGlyphOffset(glyphIndex); - uint length = _loca.GetGlyphLength(glyphIndex); - - // A zero-length entry means no outline data (e.g. space). - if (length == 0) return GlyphOutlineData.Empty; - - if (offset + length > (uint)RawBytes.Length) return null; - - try - { - // Create a sub-stream view over this glyph's bytes only. - using var ms = new MemoryStream(RawBytes, (int)offset, (int)length, writable: false); - using var reader = new FontBinaryReader(ms); - - short numberOfContours = reader.ReadInt16(); - short xMin = reader.ReadInt16(); - short yMin = reader.ReadInt16(); - short xMax = reader.ReadInt16(); - short yMax = reader.ReadInt16(); - var bbox = new GlyphBoundingBox(xMin, yMin, xMax, yMax); - - if (numberOfContours >= 0) - { - var simple = numberOfContours == 0 - ? TtfSimpleGlyph.Empty - : ParseSimpleGlyph(reader, numberOfContours); - return new GlyphOutlineData(false, simple, null, bbox); - } - else // numberOfContours == -1 - { - var composite = ParseCompositeGlyph(reader); - return new GlyphOutlineData(true, null, composite, bbox); - } - } - catch - { - return null; // corrupt glyph data - } - } - - // ── Simple glyph parsing ────────────────────────────────────────────── - - private static TtfSimpleGlyph ParseSimpleGlyph(FontBinaryReader reader, short numberOfContours) - { - // 1. End-point indices (one per contour). - var endPts = new ushort[numberOfContours]; - for (int i = 0; i < numberOfContours; i++) - endPts[i] = reader.ReadUInt16(); - - int numPoints = endPts[numberOfContours - 1] + 1; - - // 2. Instructions. - ushort instrLen = reader.ReadUInt16(); - byte[] instrs = instrLen > 0 ? reader.ReadBytes(instrLen) : Array.Empty(); - - // 3. Flags (run-length encoded with the REPEAT bit). - byte[] flags = new byte[numPoints]; - for (int i = 0; i < numPoints; ) - { - byte flag = reader.ReadUInt8(); - flags[i++] = flag; - if ((flag & FlagRepeat) != 0) - { - byte count = reader.ReadUInt8(); - for (int r = 0; r < count; r++) - flags[i++] = flag; - } - } - - // 4. X-coordinate deltas → absolute coordinates. - short[] xCoords = ReadCoordinates(reader, flags, numPoints, - shortBit: FlagXShortVector, sameOrPosBit: FlagXSameOrPositive); - - // 5. Y-coordinate deltas → absolute coordinates. - short[] yCoords = ReadCoordinates(reader, flags, numPoints, - shortBit: FlagYShortVector, sameOrPosBit: FlagYSameOrPositive); - - // 6. Build TtfPoint array. - // Determine which indices are contour endpoints. - var endPtSet = new HashSet(); - foreach (ushort ep in endPts) endPtSet.Add(ep); - - var points = new TtfPoint[numPoints]; - for (int i = 0; i < numPoints; i++) - { - bool onCurve = (flags[i] & FlagOnCurve) != 0; - bool isEndPt = endPtSet.Contains(i); - points[i] = new TtfPoint(xCoords[i], yCoords[i], onCurve, isEndPt); - } - - return new TtfSimpleGlyph(numberOfContours, points, endPts, instrs); - } - - /// - /// Reads delta-encoded signed coordinates and accumulates them into - /// absolute values. - /// - private static short[] ReadCoordinates( - FontBinaryReader reader, byte[] flags, int count, - byte shortBit, byte sameOrPosBit) - { - var coords = new short[count]; - short current = 0; - - for (int i = 0; i < count; i++) - { - byte flag = flags[i]; - bool isShort = (flag & shortBit) != 0; - bool sameOrPos = (flag & sameOrPosBit) != 0; - - if (isShort) - { - // 1-byte unsigned magnitude; direction from sameOrPos. - byte delta = reader.ReadUInt8(); - current += (short)(sameOrPos ? delta : -delta); - } - else if (!sameOrPos) - { - // 2-byte signed delta. - current += reader.ReadInt16(); - } - // else: sameOrPos && !isShort → delta = 0 (same coordinate). - - coords[i] = current; - } - - return coords; - } - - // ── Composite glyph parsing ─────────────────────────────────────────── - - private static TtfCompositeGlyph ParseCompositeGlyph(FontBinaryReader reader) - { - var components = new List(); - bool moreComponents; - bool hasInstructions = false; - - do - { - ushort flags = reader.ReadUInt16(); - ushort glyphIndex = reader.ReadUInt16(); - - moreComponents = (flags & CompMoreComponents) != 0; - hasInstructions = hasInstructions || - (flags & CompWeHaveInstructions) != 0; - - bool argsAreWords = (flags & CompArg1And2AreWords) != 0; - bool argsAreXY = (flags & CompArgsAreXYValues) != 0; - - short arg1, arg2; - if (argsAreWords) - { - arg1 = reader.ReadInt16(); - arg2 = reader.ReadInt16(); - } - else - { - arg1 = (sbyte)reader.ReadUInt8(); // signed byte - arg2 = (sbyte)reader.ReadUInt8(); - } - - // Build the 2×3 affine transform: | a b dx | - // | c d dy | - float a = 1f, b = 0f, c = 0f, d = 1f; - - if ((flags & CompWeHaveATwoByTwo) != 0) - { - a = (float)reader.ReadF2Dot14(); - b = (float)reader.ReadF2Dot14(); - c = (float)reader.ReadF2Dot14(); - d = (float)reader.ReadF2Dot14(); - } - else if ((flags & CompWeHaveAnXAndYScale) != 0) - { - a = (float)reader.ReadF2Dot14(); - d = (float)reader.ReadF2Dot14(); - } - else if ((flags & CompWeHaveAScale) != 0) - { - a = d = (float)reader.ReadF2Dot14(); - } - - float dx = argsAreXY ? arg1 : 0f; - float dy = argsAreXY ? arg2 : 0f; - - var transform = new float[2, 3] - { - { a, b, dx }, - { c, d, dy } - }; - - components.Add(new TtfCompositeComponent(glyphIndex, transform, argsAreXY, arg1, arg2)); - - } while (moreComponents); - - // Optional trailing instructions. - byte[] instrs = Array.Empty(); - if (hasInstructions) - { - ushort instrLen = reader.ReadUInt16(); - instrs = instrLen > 0 ? reader.ReadBytes(instrLen) : Array.Empty(); - } - - return new TtfCompositeGlyph(components.ToArray(), instrs); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGposTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGposTable.cs deleted file mode 100644 index 88ab0191..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGposTable.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "GPOS" table header and feature tag list. - /// Exposes (e.g. "kern", "mark", "mkmk") so callers - /// can detect which positioning features are available. - /// Full positioning lookup application is deferred to a future batch. - /// - /// - /// Ref: https://learn.microsoft.com/en-us/typography/opentype/spec/gpos - /// - public sealed class TtfGposTable : TtfTableBase - { - /// - /// The table tag for the GPOS table. - /// - public const string TableTag = "GPOS"; - - private readonly IReadOnlyList _featureTags; - - private TtfGposTable(byte[] rawBytes, IReadOnlyList featureTags) - : base(TableTag, rawBytes) - { - _featureTags = featureTags; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Distinct, lexicographically sorted OpenType feature tags present in the - /// GPOS table's FeatureList (e.g. "cpsp", "kern", "mark", "mkmk"). - /// May be empty for fonts with a malformed or absent FeatureList. - /// - public IReadOnlyList FeatureTags => _featureTags; - - // ── Parser ──────────────────────────────────────────────────────────── - - /// Parses the "GPOS" table from its raw bytes. - public static TtfGposTable Parse(byte[] rawBytes) - { - if (rawBytes is null) throw new ArgumentNullException(nameof(rawBytes)); - return new TtfGposTable(rawBytes, TtfGsubTable.ParseFeatureTags(rawBytes)); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGsubTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGsubTable.cs deleted file mode 100644 index 61df79a8..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGsubTable.cs +++ /dev/null @@ -1,93 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "GSUB" table header and feature tag list. - /// Exposes (e.g. "liga", "calt", "dlig") so callers - /// can detect which substitution features are available. - /// Full substitution lookup application is deferred to a future batch. - /// - /// - /// Ref: https://learn.microsoft.com/en-us/typography/opentype/spec/gsub - /// - public sealed class TtfGsubTable : TtfTableBase - { - /// - /// The table tag for the GSUB table. - /// - public const string TableTag = "GSUB"; - - private readonly IReadOnlyList _featureTags; - - private TtfGsubTable(byte[] rawBytes, IReadOnlyList featureTags) - : base(TableTag, rawBytes) - { - _featureTags = featureTags; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Distinct, lexicographically sorted OpenType feature tags present in the - /// GSUB table's FeatureList (e.g. "calt", "dlig", "liga", "rlig"). - /// May be empty for fonts with a malformed or absent FeatureList. - /// - public IReadOnlyList FeatureTags => _featureTags; - - // ── Parser ──────────────────────────────────────────────────────────── - - /// Parses the "GSUB" table from its raw bytes. - public static TtfGsubTable Parse(byte[] rawBytes) - { - if (rawBytes is null) throw new ArgumentNullException(nameof(rawBytes)); - return new TtfGsubTable(rawBytes, ParseFeatureTags(rawBytes)); - } - - // ── Internal helper ─────────────────────────────────────────────────── - - // Reads the FeatureList from a GSUB or GPOS table and returns the - // distinct, sorted feature tags. - internal static List ParseFeatureTags(byte[] rawBytes) - { - if (rawBytes is null || rawBytes.Length < 10) - return new List(); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - /* majorVersion */ reader.ReadUInt16(); // 0 - /* minorVersion */ reader.ReadUInt16(); // 2 - /* scriptListOffset */ reader.ReadUInt16(); // 4 - ushort featureListOffset = reader.ReadUInt16(); // 6 — from table start - - if (featureListOffset == 0 || featureListOffset >= rawBytes.Length) - return new List(); - - reader.Seek(featureListOffset); - - if (reader.Position + 2 > rawBytes.Length) return new List(); - - ushort featureCount = reader.ReadUInt16(); - - var seen = new HashSet(StringComparer.Ordinal); - for (int i = 0; i < featureCount; i++) - { - if (reader.Position + 6 > rawBytes.Length) break; - - // FeatureRecord: featureTag(4 bytes) + featureOffset(2 bytes) - string tag = reader.ReadTag().TrimEnd(); - reader.ReadUInt16(); // featureOffset — not needed - - if (!string.IsNullOrWhiteSpace(tag)) - seen.Add(tag); - } - - var list = new List(seen); - list.Sort(StringComparer.Ordinal); - return list; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGvarTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGvarTable.cs deleted file mode 100644 index ef927caf..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfGvarTable.cs +++ /dev/null @@ -1,149 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "gvar" (glyph variations) table header. - /// Exposes per-glyph raw tuple variation data; full interpolation is deferred. - /// Ref: OpenType spec §table-gvar. - /// - public sealed class TtfGvarTable : TtfTableBase - { - /// - /// The table tag for the gvar table. - /// - public const string TableTag = "gvar"; - - /// Major version of the gvar table (should be 1). - public int MajorVersion { get; } - - /// Minor version of the gvar table (should be 0). - public int MinorVersion { get; } - - /// Number of variation axes (matches fvar axis count). - public int AxisCount { get; } - - /// Number of shared tuple records in the shared tuple table. - public int SharedTupleCount { get; } - - /// Number of glyphs in the font (matches maxp.numGlyphs). - public int GlyphCount { get; } - - // Raw per-glyph variation data blobs. - private readonly byte[][] _glyphVariations; - - private TtfGvarTable( - byte[] rawBytes, - int majorVersion, int minorVersion, - int axisCount, int sharedTupleCount, int glyphCount, - byte[][] glyphVariations) - : base(TableTag, rawBytes) - { - MajorVersion = majorVersion; - MinorVersion = minorVersion; - AxisCount = axisCount; - SharedTupleCount = sharedTupleCount; - GlyphCount = glyphCount; - _glyphVariations = glyphVariations; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// - /// Returns the raw tuple variation data blob for the given glyph, or an - /// empty array if the glyph has no variation data. Returns null if the - /// index is out of range. - /// - public byte[]? GetGlyphVariationData(int glyphIndex) - { - if (glyphIndex < 0 || glyphIndex >= _glyphVariations.Length) - return null; - return _glyphVariations[glyphIndex]; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "gvar" table from its raw bytes. - public static TtfGvarTable Parse(byte[] rawBytes) - { - // gvar header is 20 bytes minimum. - if (rawBytes == null || rawBytes.Length < 20) - return Empty(rawBytes ?? Array.Empty()); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // Header (20 bytes): - // majorVersion(2) + minorVersion(2) + axisCount(2) + sharedTupleCount(2) - // + offsetToSharedTuples(4) + glyphCount(2) + flags(2) - // + offsetToGlyphVariationData(4) - int majorVersion = reader.ReadUInt16(); - int minorVersion = reader.ReadUInt16(); - int axisCount = reader.ReadUInt16(); - int sharedTupleCount = reader.ReadUInt16(); - uint offsetToSharedTuples = reader.ReadUInt32(); - int glyphCount = reader.ReadUInt16(); - int flags = reader.ReadUInt16(); - uint offsetToGlyphVariData = reader.ReadUInt32(); - - // flags bit 0: 0 = uint16 offsets (×2), 1 = uint32 offsets. - bool longOffsets = (flags & 1) != 0; - - // glyphVariationDataOffsets[glyphCount + 1] immediately follows the header. - int offsetCount = glyphCount + 1; - int bytesPerEntry = longOffsets ? 4 : 2; - if (20L + (long)offsetCount * bytesPerEntry > rawBytes.Length) - return Empty(rawBytes); - - uint[] glyphOffsets = new uint[offsetCount]; - - if (longOffsets) - { - for (int i = 0; i < offsetCount; i++) - glyphOffsets[i] = reader.ReadUInt32(); - } - else - { - for (int i = 0; i < offsetCount; i++) - glyphOffsets[i] = (uint)(reader.ReadUInt16() * 2); - } - - // Extract per-glyph raw variation data. - // offsets are relative to offsetToGlyphVariationData (from table start). - var glyphVariations = new byte[glyphCount][]; - for (int i = 0; i < glyphCount; i++) - { - uint start = glyphOffsets[i]; - uint end = glyphOffsets[i + 1]; - - if (start == end) - { - glyphVariations[i] = Array.Empty(); - continue; - } - - long absStart = (long)offsetToGlyphVariData + start; - long length = end - start; - - if (absStart < 0 || absStart + length > rawBytes.Length) - { - glyphVariations[i] = Array.Empty(); - continue; - } - - byte[] data = new byte[length]; - Array.Copy(rawBytes, absStart, data, 0, length); - glyphVariations[i] = data; - } - - return new TtfGvarTable(rawBytes, majorVersion, minorVersion, - axisCount, sharedTupleCount, glyphCount, glyphVariations); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static TtfGvarTable Empty(byte[] rawBytes) => - new TtfGvarTable(rawBytes, 0, 0, 0, 0, 0, Array.Empty()); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHeadTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHeadTable.cs deleted file mode 100644 index a7ecdbc9..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHeadTable.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "head" table (font header). - /// Ref: OpenType spec §5.2.1 / TrueType Reference §'head'. - /// - public sealed class TtfHeadTable : TtfTableBase - { - /// - /// The table tag for the head table. - /// - public const string TableTag = "head"; - - // ── Parsed fields ───────────────────────────────────────────────────── - - /// Units per EM square. Typically 1000 or 2048. - public double UnitsPerEm { get; } - - /// - /// Bit flags describing font style: bit 0=Bold, 1=Italic, 2=Underline, - /// 3=Outline, 4=Shadow, 5=Condensed, 6=Extended. - /// - public ushort MacStyle { get; } - - /// - /// Determines the format of the "loca" table: - /// 0 = short offsets (×2); 1 = long offsets. - /// - public short IndexToLocFormat { get; } - - /// Design-space bounding box that encloses all glyphs. - public GlyphBoundingBox Bounds { get; } - - /// Creation timestamp (seconds since 1904-01-01 00:00:00 UTC). - public long Created { get; } - - /// Last-modified timestamp (seconds since 1904-01-01 00:00:00 UTC). - public long Modified { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfHeadTable( - byte[] rawBytes, - double unitsPerEm, - ushort macStyle, - short indexToLocFormat, - GlyphBoundingBox bounds, - long created, - long modified) - : base(TableTag, rawBytes) - { - UnitsPerEm = unitsPerEm; - MacStyle = macStyle; - IndexToLocFormat = indexToLocFormat; - Bounds = bounds; - Created = created; - Modified = modified; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "head" table from its raw bytes. - public static TtfHeadTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - reader.Skip(4); // version (Fixed 1.0) - reader.Skip(4); // fontRevision (Fixed) - reader.Skip(4); // checkSumAdjustment (ULONG) - reader.Skip(4); // magicNumber (ULONG, should be 0x5F0F3CF5) - reader.Skip(2); // flags (USHORT) - - ushort unitsPerEm = reader.ReadUInt16(); - long created = reader.ReadInt64(); - long modified = reader.ReadInt64(); - - short xMin = reader.ReadInt16(); - short yMin = reader.ReadInt16(); - short xMax = reader.ReadInt16(); - short yMax = reader.ReadInt16(); - - ushort macStyle = reader.ReadUInt16(); - reader.Skip(2); // lowestRecPPEM (USHORT) - reader.Skip(2); // fontDirectionHint (SHORT, deprecated) - short indexToLocFormat = reader.ReadInt16(); - // glyphDataFormat (SHORT) not required here - - return new TtfHeadTable( - rawBytes, - unitsPerEm, - macStyle, - indexToLocFormat, - new GlyphBoundingBox(xMin, yMin, xMax, yMax), - created, - modified); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHheaTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHheaTable.cs deleted file mode 100644 index b2aa5b4f..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHheaTable.cs +++ /dev/null @@ -1,104 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "hhea" table (horizontal header). - /// Contains metrics that describe the overall horizontal layout of the font. - /// Ref: OpenType spec §5.2.3 / TrueType Reference §'hhea'. - /// - public sealed class TtfHheaTable : TtfTableBase - { - /// - /// The table tag for the hhea table. - /// - public const string TableTag = "hhea"; - - // ── Parsed fields ───────────────────────────────────────────────────── - - /// - /// Distance from baseline to top of tallest ascender, in design units. - /// Positive value. - /// - public short Ascender { get; } - - /// - /// Distance from baseline to bottom of lowest descender, in design units. - /// Negative value (below baseline). - /// - public short Descender { get; } - - /// - /// Typographic line gap (additional line spacing beyond Ascender − Descender), - /// in design units. - /// - public short LineGap { get; } - - /// Maximum advance width across all glyphs. - public ushort AdvanceWidthMax { get; } - - /// Minimum left side-bearing across all glyphs. - public short MinLsb { get; } - - /// Minimum right side-bearing across all glyphs. - public short MinRsb { get; } - - /// Maximum x extent (xMin + advanceWidth) across all glyphs. - public short XMaxExtent { get; } - - /// - /// Number of hMetrics entries in the "hmtx" table. - /// Glyphs with index ≥ this value share the last advance width. - /// - public ushort NumberOfHMetrics { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfHheaTable( - byte[] rawBytes, - short ascender, short descender, short lineGap, - ushort advanceWidthMax, - short minLsb, short minRsb, short xMaxExtent, - ushort numberOfHMetrics) - : base(TableTag, rawBytes) - { - Ascender = ascender; - Descender = descender; - LineGap = lineGap; - AdvanceWidthMax = advanceWidthMax; - MinLsb = minLsb; - MinRsb = minRsb; - XMaxExtent = xMaxExtent; - NumberOfHMetrics = numberOfHMetrics; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "hhea" table from its raw bytes. - public static TtfHheaTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - reader.Skip(4); // version (Fixed 1.0) - short ascender = reader.ReadInt16(); - short descender = reader.ReadInt16(); - short lineGap = reader.ReadInt16(); - ushort advanceWidthMax = reader.ReadUInt16(); - short minLsb = reader.ReadInt16(); - short minRsb = reader.ReadInt16(); - short xMaxExtent = reader.ReadInt16(); - reader.Skip(2); // caretSlopeRise (SHORT) - reader.Skip(2); // caretSlopeRun (SHORT) - reader.Skip(2); // caretOffset (SHORT) - reader.Skip(8); // reserved[4] (4 × SHORT) - reader.Skip(2); // metricDataFormat (SHORT) - ushort numberOfHMetrics = reader.ReadUInt16(); - - return new TtfHheaTable( - rawBytes, ascender, descender, lineGap, - advanceWidthMax, minLsb, minRsb, xMaxExtent, - numberOfHMetrics); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHmtxTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHmtxTable.cs deleted file mode 100644 index 3650b6b8..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfHmtxTable.cs +++ /dev/null @@ -1,117 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "hmtx" table (horizontal metrics). - /// Stores advance width and left side-bearing for every glyph. - /// The first numberOfHMetrics glyphs each have their own advance width; - /// glyphs beyond that index share the last advance width value. - /// Ref: OpenType spec §5.2.4. - /// - public sealed class TtfHmtxTable : TtfTableBase - { - /// - /// The table tag for the hmtx table. - /// - public const string TableTag = "hmtx"; - - // ── Private storage ─────────────────────────────────────────────────── - - // Advance widths for glyphs 0 .. numberOfHMetrics−1. - private readonly ushort[] _advanceWidths; - - // Left side-bearings for glyphs 0 .. numberOfHMetrics−1. - private readonly short[] _lsbs; - - // Left side-bearings for glyphs numberOfHMetrics .. numGlyphs−1 - // (these share the last advance width entry above). - private readonly short[] _extraLsbs; - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfHmtxTable( - byte[] rawBytes, - ushort[] advanceWidths, - short[] lsbs, - short[] extraLsbs) - : base(TableTag, rawBytes) - { - _advanceWidths = advanceWidths; - _lsbs = lsbs; - _extraLsbs = extraLsbs; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// - /// Parses the "hmtx" table from its raw bytes. - /// - /// Raw table data. - /// - /// Value from . - /// Determines how many full (width+lsb) entries are present. - /// - /// - /// Total glyph count from . - /// Determines how many extra LSB-only entries follow. - /// - public static TtfHmtxTable Parse(byte[] rawBytes, ushort numberOfHMetrics, ushort numGlyphs) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - var advanceWidths = new ushort[numberOfHMetrics]; - var lsbs = new short[numberOfHMetrics]; - - for (int i = 0; i < numberOfHMetrics; i++) - { - advanceWidths[i] = reader.ReadUInt16(); - lsbs[i] = reader.ReadInt16(); - } - - // Glyphs beyond numberOfHMetrics share the last advance width and - // have individual LSB entries only. - int extraCount = numGlyphs > numberOfHMetrics - ? numGlyphs - numberOfHMetrics - : 0; - - var extraLsbs = new short[extraCount]; - for (int i = 0; i < extraCount; i++) - extraLsbs[i] = reader.ReadInt16(); - - return new TtfHmtxTable(rawBytes, advanceWidths, lsbs, extraLsbs); - } - - // ── Public accessors ────────────────────────────────────────────────── - - /// - /// Returns the advance width for , in design units. - /// Glyphs with index ≥ numberOfHMetrics return the last recorded advance width. - /// - public ushort GetAdvanceWidth(int glyphIndex) - { - if (glyphIndex < 0 || _advanceWidths.Length == 0) return 0; - int idx = Math.Min(glyphIndex, _advanceWidths.Length - 1); - return _advanceWidths[idx]; - } - - /// - /// Returns the left side-bearing for , in design units. - /// - public short GetLsb(int glyphIndex) - { - if (glyphIndex < 0) return 0; - - if (glyphIndex < _lsbs.Length) - return _lsbs[glyphIndex]; - - int extraIndex = glyphIndex - _lsbs.Length; - if (extraIndex < _extraLsbs.Length) - return _extraLsbs[extraIndex]; - - return 0; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfKernTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfKernTable.cs deleted file mode 100644 index 529ac4bf..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfKernTable.cs +++ /dev/null @@ -1,124 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "kern" table — horizontal kerning adjustments between glyph pairs. - /// - /// - /// Only OpenType kern version 0, format 0 (ordered pairs) subtables are loaded. - /// Format 2 (class-pair) subtables and Apple kern version 1 (AAT) tables are - /// silently skipped; will be zero for those fonts. - /// - /// Ref: https://learn.microsoft.com/en-us/typography/opentype/spec/kern - /// - public sealed class TtfKernTable : TtfTableBase - { - /// - /// The table tag for the kern table. - /// - public const string TableTag = "kern"; - - // Key = (leftGlyphId << 16) | rightGlyphId; Value = kern adjustment (FUnits, signed). - private readonly Dictionary _pairs; - - private TtfKernTable(byte[] rawBytes, Dictionary pairs) - : base(TableTag, rawBytes) - { - _pairs = pairs; - } - - // ── Public API ──────────────────────────────────────────────────────── - - /// Total number of kerning pairs loaded from format 0 subtables. - public int PairCount => _pairs.Count; - - /// - /// Returns the kerning value (in design units) for the given glyph pair, - /// or 0 if no kern value is defined for the pair. - /// A negative value means the glyphs are moved closer together. - /// - public short GetKerning(ushort leftGlyphId, ushort rightGlyphId) - { - uint key = ((uint)leftGlyphId << 16) | rightGlyphId; - return _pairs.TryGetValue(key, out short value) ? value : (short)0; - } - - // ── Parser ──────────────────────────────────────────────────────────── - - /// Parses the "kern" table from its raw bytes. - public static TtfKernTable Parse(byte[] rawBytes) - { - if (rawBytes is null) throw new ArgumentNullException(nameof(rawBytes)); - - var pairs = new Dictionary(); - - if (rawBytes.Length < 4) - return new TtfKernTable(rawBytes, pairs); - - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // ── Version detection ───────────────────────────────────────────── - // OpenType kern v0: first uint16 = 0. - // Apple kern v1 : first uint16 = 1 (full uint32 = 0x00010000). - ushort version = reader.ReadUInt16(); - if (version == 1) - { - // Apple AAT kern — not parsed; return empty table. - return new TtfKernTable(rawBytes, pairs); - } - if (version != 0) - return new TtfKernTable(rawBytes, pairs); - - ushort nTables = reader.ReadUInt16(); - - for (int t = 0; t < nTables; t++) - { - long subtableStart = reader.Position; - - if (subtableStart + 6 > rawBytes.Length) break; - - /* subtable version (always 0 in v0) */ reader.ReadUInt16(); - ushort length = reader.ReadUInt16(); // total subtable length incl. header - ushort coverage = reader.ReadUInt16(); - - // coverage high byte = format, low byte = flags - int format = (coverage >> 8) & 0xFF; - bool isHorizontal = (coverage & 0x01) != 0; - - if (format == 0 && isHorizontal) - { - if (reader.Position + 8 > rawBytes.Length) break; - - ushort nPairs = reader.ReadUInt16(); - /* searchRange */ reader.ReadUInt16(); - /* entrySelector */ reader.ReadUInt16(); - /* rangeShift */ reader.ReadUInt16(); - - for (int p = 0; p < nPairs; p++) - { - if (reader.Position + 6 > rawBytes.Length) break; - - ushort left = reader.ReadUInt16(); - ushort right = reader.ReadUInt16(); - short value = reader.ReadInt16(); - - uint key = ((uint)left << 16) | right; - pairs[key] = value; - } - } - - // Advance to next subtable (length is from subtableStart, inclusive of header). - long nextSubtable = subtableStart + length; - if (nextSubtable <= subtableStart) break; // safety: corrupt length - if (nextSubtable > rawBytes.Length) break; - reader.Seek(nextSubtable); - } - - return new TtfKernTable(rawBytes, pairs); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfLocaTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfLocaTable.cs deleted file mode 100644 index 0666e1d0..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfLocaTable.cs +++ /dev/null @@ -1,112 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "loca" table (index to location). - /// Maps glyph indices to their byte offsets within the "glyf" table. - /// - /// - /// The table stores numGlyphs + 1 offsets so the length of any glyph's - /// data can be derived as loca[i+1] − loca[i]. - /// A zero-length entry means the glyph has no outline (e.g. the space character). - /// - /// Format is controlled by head.indexToLocFormat: - /// - /// 0 (short): 16-bit values, each multiplied by 2 to get the byte offset. - /// 1 (long): 32-bit values used as-is. - /// - /// Ref: OpenType spec §5.2.5. - /// - public sealed class TtfLocaTable : TtfTableBase - { - /// - /// The table tag for the loca table. - /// - public const string TableTag = "loca"; - - // ── Private storage ─────────────────────────────────────────────────── - - // Absolute byte offsets, length = numGlyphs + 1. - private readonly uint[] _offsets; - - /// - /// The indexToLocFormat value from the "head" table: - /// 0 = short format, 1 = long format. - /// - public short IndexToLocFormat { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfLocaTable(byte[] rawBytes, uint[] offsets, short indexToLocFormat) - : base(TableTag, rawBytes) - { - _offsets = offsets; - IndexToLocFormat = indexToLocFormat; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "loca" table from its raw bytes. - /// Raw table data. - /// - /// Value from : - /// 0 = short (×2), 1 = long. - /// - /// - /// Total glyph count from . - /// The table will contain numGlyphs + 1 offset entries. - /// - public static TtfLocaTable Parse(byte[] rawBytes, short indexToLocFormat, ushort numGlyphs) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - int count = numGlyphs + 1; // n+1 entries to allow length computation - var offsets = new uint[count]; - - if (indexToLocFormat == 0) - { - // Short format: 16-bit values scaled by 2. - for (int i = 0; i < count; i++) - offsets[i] = (uint)(reader.ReadUInt16() * 2); - } - else - { - // Long format: 32-bit values used as-is. - for (int i = 0; i < count; i++) - offsets[i] = reader.ReadUInt32(); - } - - return new TtfLocaTable(rawBytes, offsets, indexToLocFormat); - } - - // ── Public accessors ────────────────────────────────────────────────── - - /// - /// Returns the absolute byte offset of glyph - /// within the "glyf" table data. - /// Returns 0 for out-of-range indices. - /// - public uint GetGlyphOffset(int glyphIndex) - { - if (glyphIndex < 0 || glyphIndex >= _offsets.Length - 1) - return 0; - return _offsets[glyphIndex]; - } - - /// - /// Returns the byte length of the glyph data for . - /// A return value of 0 indicates a glyph with no outline (e.g. space). - /// - public uint GetGlyphLength(int glyphIndex) - { - if (glyphIndex < 0 || glyphIndex >= _offsets.Length - 1) - return 0; - return _offsets[glyphIndex + 1] - _offsets[glyphIndex]; - } - - /// Total number of glyph entries (excluding the sentinel). - public int GlyphCount => _offsets.Length > 0 ? _offsets.Length - 1 : 0; - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfMaxpTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfMaxpTable.cs deleted file mode 100644 index 22621cdc..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfMaxpTable.cs +++ /dev/null @@ -1,149 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "maxp" table (maximum profile). - /// The version 0.5 variant contains only ; - /// version 1.0 adds glyph-program-stack and component limits used by - /// the TrueType hinting interpreter. - /// Ref: OpenType spec §5.2.6. - /// - public sealed class TtfMaxpTable : TtfTableBase - { - /// - /// The table tag for the maxp table. - /// - public const string TableTag = "maxp"; - - // ── Version magic ───────────────────────────────────────────────────── - - /// Raw version field value for version 0.5 (CFF/OTF fonts). - public const uint Version05 = 0x00005000u; - - /// Raw version field value for version 1.0 (TrueType/glyf fonts). - public const uint Version10 = 0x00010000u; - - // ── Common fields ───────────────────────────────────────────────────── - - /// Raw version field (see / ). - public uint Version { get; } - - /// Total number of glyphs in the font. - public ushort NumGlyphs { get; } - - // ── Version 1.0 optional fields ─────────────────────────────────────── - - /// Maximum number of points in a non-composite glyph (v1.0 only). - public ushort? MaxPoints { get; } - - /// Maximum number of contours in a non-composite glyph (v1.0 only). - public ushort? MaxContours { get; } - - /// Maximum number of points in a composite glyph (v1.0 only). - public ushort? MaxComponentPoints { get; } - - /// Maximum number of contours in a composite glyph (v1.0 only). - public ushort? MaxComponentContours { get; } - - /// Maximum number of hinting zones; 1 or 2 (v1.0 only). - public ushort? MaxZones { get; } - - /// Maximum number of twilight zone points (v1.0 only). - public ushort? MaxTwilightPoints { get; } - - /// Maximum number of storage area locations (v1.0 only). - public ushort? MaxStorage { get; } - - /// Maximum number of function definitions (v1.0 only). - public ushort? MaxFunctionDefs { get; } - - /// Maximum number of instruction definitions (v1.0 only). - public ushort? MaxInstructionDefs { get; } - - /// Maximum stack depth for hinting instructions (v1.0 only). - public ushort? MaxStackElements { get; } - - /// Maximum size of hinting instruction stream per glyph (v1.0 only). - public ushort? MaxSizeOfInstructions { get; } - - /// Maximum number of components in a composite glyph (v1.0 only). - public ushort? MaxComponentElements { get; } - - /// Maximum nesting depth of composite glyphs (v1.0 only). - public ushort? MaxComponentDepth { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfMaxpTable( - byte[] rawBytes, uint version, ushort numGlyphs, - ushort? maxPoints, ushort? maxContours, - ushort? maxComponentPoints, ushort? maxComponentContours, - ushort? maxZones, ushort? maxTwilightPoints, - ushort? maxStorage, ushort? maxFunctionDefs, ushort? maxInstructionDefs, - ushort? maxStackElements, ushort? maxSizeOfInstructions, - ushort? maxComponentElements, ushort? maxComponentDepth) - : base(TableTag, rawBytes) - { - Version = version; - NumGlyphs = numGlyphs; - MaxPoints = maxPoints; - MaxContours = maxContours; - MaxComponentPoints = maxComponentPoints; - MaxComponentContours = maxComponentContours; - MaxZones = maxZones; - MaxTwilightPoints = maxTwilightPoints; - MaxStorage = maxStorage; - MaxFunctionDefs = maxFunctionDefs; - MaxInstructionDefs = maxInstructionDefs; - MaxStackElements = maxStackElements; - MaxSizeOfInstructions = maxSizeOfInstructions; - MaxComponentElements = maxComponentElements; - MaxComponentDepth = maxComponentDepth; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "maxp" table from its raw bytes. - public static TtfMaxpTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - uint version = reader.ReadUInt32(); - ushort numGlyphs = reader.ReadUInt16(); - - // Version 0.5 only has numGlyphs; version 1.0 has additional fields. - if (version != Version10 || rawBytes.Length < 32) - { - return new TtfMaxpTable( - rawBytes, version, numGlyphs, - null, null, null, null, null, null, - null, null, null, null, null, null, null); - } - - ushort maxPoints = reader.ReadUInt16(); - ushort maxContours = reader.ReadUInt16(); - ushort maxComponentPoints = reader.ReadUInt16(); - ushort maxComponentContours = reader.ReadUInt16(); - ushort maxZones = reader.ReadUInt16(); - ushort maxTwilightPoints = reader.ReadUInt16(); - ushort maxStorage = reader.ReadUInt16(); - ushort maxFunctionDefs = reader.ReadUInt16(); - ushort maxInstructionDefs = reader.ReadUInt16(); - ushort maxStackElements = reader.ReadUInt16(); - ushort maxSizeOfInstructions = reader.ReadUInt16(); - ushort maxComponentElements = reader.ReadUInt16(); - ushort maxComponentDepth = reader.ReadUInt16(); - - return new TtfMaxpTable( - rawBytes, version, numGlyphs, - maxPoints, maxContours, - maxComponentPoints, maxComponentContours, - maxZones, maxTwilightPoints, - maxStorage, maxFunctionDefs, maxInstructionDefs, - maxStackElements, maxSizeOfInstructions, - maxComponentElements, maxComponentDepth); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfNameTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfNameTable.cs deleted file mode 100644 index f32d746d..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfNameTable.cs +++ /dev/null @@ -1,172 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.Collections.Generic; -using System.IO; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "name" table. - /// Exposes the most common font name strings, preferring Windows/Unicode - /// platform records (platformID=3, encodingID=1, languageID=0x0409) over - /// Unicode-BMP (platformID=0) and Macintosh (platformID=1) records. - /// Ref: OpenType spec §5.2.9. - /// - public sealed class TtfNameTable : TtfTableBase - { - /// - /// The table tag for the name table. - /// - public const string TableTag = "name"; - - // ── Well-known name IDs ─────────────────────────────────────────────── - - private const ushort NameIdFamily = 1; - private const ushort NameIdStyle = 2; - private const ushort NameIdUniqueId = 3; - private const ushort NameIdFullName = 4; - private const ushort NameIdVersion = 5; - private const ushort NameIdPostScript = 6; - - // ── Exposed strings ─────────────────────────────────────────────────── - - /// Font family name (nameID 1), e.g. "Montserrat". - public string? FamilyName { get; } - - /// Font subfamily / style name (nameID 2), e.g. "Regular". - public string? StyleName { get; } - - /// Unique font identifier string (nameID 3). - public string? UniqueId { get; } - - /// Full human-readable font name (nameID 4), e.g. "Montserrat Regular". - public string? FullName { get; } - - /// Font version string (nameID 5). - public string? Version { get; } - - /// PostScript font name (nameID 6), e.g. "Montserrat-Regular". - public string? PostScriptName { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfNameTable( - byte[] rawBytes, - string? familyName, string? styleName, string? uniqueId, - string? fullName, string? version, string? postScriptName) - : base(TableTag, rawBytes) - { - FamilyName = familyName; - StyleName = styleName; - UniqueId = uniqueId; - FullName = fullName; - Version = version; - PostScriptName = postScriptName; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "name" table from its raw bytes. - public static TtfNameTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - ushort format = reader.ReadUInt16(); - ushort count = reader.ReadUInt16(); - ushort stringOffset = reader.ReadUInt16(); - - // Read all name records (each 12 bytes). - var records = new (ushort platformId, ushort encodingId, ushort languageId, - ushort nameId, ushort length, ushort offset)[count]; - - for (int i = 0; i < count; i++) - { - ushort platformId = reader.ReadUInt16(); - ushort encodingId = reader.ReadUInt16(); - ushort languageId = reader.ReadUInt16(); - ushort nameId = reader.ReadUInt16(); - ushort length = reader.ReadUInt16(); - ushort offset = reader.ReadUInt16(); - records[i] = (platformId, encodingId, languageId, nameId, length, offset); - } - - // For each nameID keep the record with the highest priority encoding. - var best = new Dictionary(); - - foreach (var rec in records) - { - int priority = GetPriority(rec.platformId, rec.encodingId, rec.languageId); - if (priority < 0) continue; - - string str = DecodeString(rawBytes, stringOffset + rec.offset, - rec.length, rec.platformId, rec.encodingId); - - if (!best.TryGetValue(rec.nameId, out var existing) || - priority > existing.priority) - { - best[rec.nameId] = (priority, str); - } - } - - string? Get(ushort nameId) => - best.TryGetValue(nameId, out var v) ? v.str : null; - - return new TtfNameTable( - rawBytes, - Get(NameIdFamily), - Get(NameIdStyle), - Get(NameIdUniqueId), - Get(NameIdFullName), - Get(NameIdVersion), - Get(NameIdPostScript)); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - /// - /// Returns a priority score for a name record. Higher = preferred. - /// Returns -1 for unsupported platform/encoding combinations. - /// - private static int GetPriority(ushort platformId, ushort encodingId, ushort languageId) - { - switch (platformId) - { - case 3: // Windows - if (encodingId == 1 && languageId == 0x0409) return 100; // en-US - if (encodingId == 1) return 90; // other language - return 80; // other encoding - - case 0: // Unicode BMP / full-repertoire - return 70; - - case 1: // Macintosh - return 60; - - default: - return -1; // skip - } - } - - /// - /// Decodes a name string from the raw table byte array. - /// Platform 3 and platform 0 use UTF-16BE; platform 1 (Macintosh) is - /// treated as Latin-1 (adequate for ASCII-range font names). - /// - private static string DecodeString(byte[] data, int offset, int length, - ushort platformId, ushort encodingId) - { - if (length == 0 || offset + length > data.Length) - return string.Empty; - - // Platforms 0 (Unicode) and 3 (Windows) → UTF-16 big-endian. - if (platformId == 0 || platformId == 3) - return SysEncoding.BigEndianUnicode.GetString(data, offset, length); - - // Platform 1 (Macintosh) → Latin-1 approximation (good for ASCII names). - var chars = new char[length]; - for (int i = 0; i < length; i++) - chars[i] = (char)data[offset + i]; - return new string(chars); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfOs2Table.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfOs2Table.cs deleted file mode 100644 index db194a05..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfOs2Table.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "OS/2" table (OS/2 and Windows metrics). - /// Contains typographic metrics and embedding license flags used by - /// both text layout and PDF font embedding consumers. - /// Ref: OpenType spec §5.7. - /// - public sealed class TtfOs2Table : TtfTableBase - { - /// - /// The table tag for the OS/2 table. - /// - public const string TableTag = "OS/2"; - - // ── Parsed fields ───────────────────────────────────────────────────── - - /// - /// Embedding licensing flags (raw fsType value from the table). - /// Use for interpreted per-bit access. - /// - public ushort FsType { get; } - - /// Typographic ascender above baseline, in design units. - public short TypoAscender { get; } - - /// Typographic descender below baseline (negative), in design units. - public short TypoDescender { get; } - - /// Typographic line gap, in design units. - public short TypoLineGap { get; } - - /// Windows-compatible ascender, in design units. - public ushort WinAscent { get; } - - /// Windows-compatible descender (positive), in design units. - public ushort WinDescent { get; } - - /// Code-page coverage bitmask 1 (version ≥ 1 only; null for v0). - public int? CodePageRange1 { get; } - - /// Code-page coverage bitmask 2 (version ≥ 1 only; null for v0). - public int? CodePageRange2 { get; } - - /// Strikeout stroke thickness, in design units (from OS/2 yStrikeoutSize). - public short StrikeoutSize { get; } - - /// - /// Distance from baseline to top of strikeout stroke, in design units - /// (from OS/2 yStrikeoutPosition). Positive values are above the baseline. - /// - public short StrikeoutPosition { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfOs2Table( - byte[] rawBytes, - ushort fsType, - short typoAscender, short typoDescender, short typoLineGap, - ushort winAscent, ushort winDescent, - int? codePageRange1, int? codePageRange2, - short strikeoutSize, short strikeoutPosition) - : base(TableTag, rawBytes) - { - FsType = fsType; - TypoAscender = typoAscender; - TypoDescender = typoDescender; - TypoLineGap = typoLineGap; - WinAscent = winAscent; - WinDescent = winDescent; - CodePageRange1 = codePageRange1; - CodePageRange2 = codePageRange2; - StrikeoutSize = strikeoutSize; - StrikeoutPosition = strikeoutPosition; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "OS/2" table from its raw bytes. - public static TtfOs2Table Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // Byte offsets per spec (all versions share this prefix): - ushort version = reader.ReadUInt16(); // 0 version - reader.Skip(2); // 2 xAvgCharWidth - reader.Skip(2); // 4 usWeightClass - reader.Skip(2); // 6 usWidthClass - ushort fsType = reader.ReadUInt16(); // 8 fsType ← LICENSE FLAGS - reader.Skip(16); // 10–25 ySubscript/ySuperscript (8 shorts) - short strikeoutSize = reader.ReadInt16(); // 26 yStrikeoutSize - short strikeoutPosition = reader.ReadInt16(); // 28 yStrikeoutPosition - reader.Skip(2); // 30 sFamilyClass - reader.Skip(10); // 32 panose[10] - reader.Skip(16); // 42 ulUnicodeRange1–4 - reader.Skip(4); // 58 achVendID - reader.Skip(2); // 62 fsSelection - reader.Skip(2); // 64 usFirstCharIndex - reader.Skip(2); // 66 usLastCharIndex - short typoAscender = reader.ReadInt16(); // 68 - short typoDescender = reader.ReadInt16(); // 70 - short typoLineGap = reader.ReadInt16(); // 72 - ushort winAscent = reader.ReadUInt16(); // 74 - ushort winDescent = reader.ReadUInt16(); // 76 - - int? codePageRange1 = null; - int? codePageRange2 = null; - if (version >= 1 && rawBytes.Length >= 86) - { - codePageRange1 = reader.ReadInt32(); // 78 - codePageRange2 = reader.ReadInt32(); // 82 - } - - return new TtfOs2Table(rawBytes, fsType, - typoAscender, typoDescender, typoLineGap, - winAscent, winDescent, - codePageRange1, codePageRange2, - strikeoutSize, strikeoutPosition); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - /// - /// Returns a instance that exposes per-bit - /// embedding restriction properties derived from . - /// - public LicenseFlags GetLicenseFlags() => new LicenseFlags(FsType); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfPostTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfPostTable.cs deleted file mode 100644 index 690ea35c..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfPostTable.cs +++ /dev/null @@ -1,82 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "post" table (PostScript compatibility). - /// Contains italic angle and underline metrics used for PDF export and - /// display rendering. - /// Ref: OpenType spec §5.2.11. - /// - public sealed class TtfPostTable : TtfTableBase - { - /// - /// The table tag for the post table. - /// - public const string TableTag = "post"; - - // ── Parsed fields ───────────────────────────────────────────────────── - - /// - /// Italic angle in counter-clockwise degrees from the vertical, in design units. - /// Zero for upright fonts; negative for forward-slanting italic fonts. - /// - public double ItalicAngle { get; } - - /// - /// Offset of the top of the underline stroke from the baseline, in design units. - /// Negative values place the underline below the baseline. - /// - public short UnderlinePosition { get; } - - /// Thickness of the underline stroke, in design units. - public short UnderlineThickness { get; } - - /// - /// True if the font is monospaced (all glyphs have the same advance width). - /// Zero in the table means proportional; any non-zero value means monospaced. - /// - public bool IsFixedPitch { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - private TtfPostTable( - byte[] rawBytes, - double italicAngle, - short underlinePosition, - short underlineThickness, - bool isFixedPitch) - : base(TableTag, rawBytes) - { - ItalicAngle = italicAngle; - UnderlinePosition = underlinePosition; - UnderlineThickness = underlineThickness; - IsFixedPitch = isFixedPitch; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - /// Parses the "post" table from its raw bytes. - public static TtfPostTable Parse(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // Version is a 16.16 Fixed value; we read it as a Fixed double but - // we don't branch on it — all versions share this prefix layout. - reader.Skip(4); // version (Fixed) - - double italicAngle = reader.ReadFixed(); // 16.16 fixed-point - short underlinePosition = reader.ReadInt16(); - short underlineThickness = reader.ReadInt16(); - uint isFixedPitchRaw = reader.ReadUInt32(); // 0=proportional, nonzero=fixed - - return new TtfPostTable( - rawBytes, - italicAngle, - underlinePosition, - underlineThickness, - isFixedPitchRaw != 0); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfSvgTable.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfSvgTable.cs deleted file mode 100644 index d5dd8a44..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfSvgTable.cs +++ /dev/null @@ -1,179 +0,0 @@ -using MiniSoftware.Drawing.Font.IO; -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Parsed OpenType "SVG " (Scalable Vector Graphics) table. - /// Exposes per-glyph SVG document strings. - /// Ref: OpenType spec §table-SVG. - /// - public sealed class TtfSvgTable : TtfTableBase - { - /// - /// The table tag for the SVG table. - /// - public const string TableTag = "SVG "; - - // ── Internal record ─────────────────────────────────────────────────── - - private struct SvgRecord - { - internal int StartGlyphId; - internal int EndGlyphId; - /// Absolute offset into of the SVG document data. - internal int DataOffset; - internal int DataLength; - } - - private readonly SvgRecord[] _records; - - private TtfSvgTable(byte[] rawBytes, SvgRecord[] records) - : base(TableTag, rawBytes) - { - _records = records; - } - - // ── Properties ──────────────────────────────────────────────────────── - - /// Number of SVG document records in the table. - public int DocumentCount => _records.Length; - - // ── Lookup ──────────────────────────────────────────────────────────── - - /// - /// Returns the SVG document string for , or - /// if no document covers that glyph. - /// - /// - /// Documents may cover a range of glyph IDs that share the same SVG. - /// GZip-compressed documents (magic bytes 0x1F 0x8B) are decompressed - /// automatically before being returned as a UTF-8 string. - /// - public string? GetSvgDocument(int glyphIndex) - { - foreach (var rec in _records) - { - if (glyphIndex < rec.StartGlyphId || glyphIndex > rec.EndGlyphId) - continue; - - if (rec.DataOffset < 0 || rec.DataLength <= 0) - return null; - if (rec.DataOffset + rec.DataLength > RawBytes.Length) - return null; - - byte[] data = new byte[rec.DataLength]; - Array.Copy(RawBytes, rec.DataOffset, data, 0, rec.DataLength); - - // GZip-compressed data starts with 0x1F 0x8B. - if (data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B) - { - data = Decompress(data); - if (data == null) return null; - } - - return SysEncoding.UTF8.GetString(data); - } - return null; - } - - // ── Factory ─────────────────────────────────────────────────────────── - - private static readonly TtfSvgTable _empty = - new TtfSvgTable(Array.Empty(), Array.Empty()); - - /// Parses the "SVG " table from its raw bytes. - public static TtfSvgTable Parse(byte[] rawBytes) - { - if (rawBytes == null || rawBytes.Length < 10) - return new TtfSvgTable(rawBytes ?? Array.Empty(), Array.Empty()); - - try - { - return ParseCore(rawBytes); - } - catch - { - return new TtfSvgTable(rawBytes, Array.Empty()); - } - } - - private static TtfSvgTable ParseCore(byte[] rawBytes) - { - using var reader = new FontBinaryReader(new MemoryStream(rawBytes)); - - // SVG table header (10 bytes): - // version(2) + offsetToSVGDocumentList(4) + reserved(4) - ushort version = reader.ReadUInt16(); - uint docListOffset = reader.ReadUInt32(); - uint reserved = reader.ReadUInt32(); - - if (docListOffset + 2 > (uint)rawBytes.Length) - return new TtfSvgTable(rawBytes, Array.Empty()); - - // SVGDocumentList starts at docListOffset from the table start. - reader.Seek(docListOffset); - ushort numEntries = reader.ReadUInt16(); - - if (numEntries == 0) - return new TtfSvgTable(rawBytes, Array.Empty()); - - // Each SVGDocumentRecord is 12 bytes: - // startGlyphID(2) + endGlyphID(2) + svgDocOffset(4) + svgDocLength(4) - // svgDocOffset is relative to the start of the SVGDocumentList. - long recordsBase = docListOffset + 2L; - long docListBase = docListOffset; - - var records = new List(numEntries); - for (int i = 0; i < numEntries; i++) - { - long recPos = recordsBase + i * 12L; - if (recPos + 12 > rawBytes.Length) break; - - reader.Seek(recPos); - ushort startGlyphId = reader.ReadUInt16(); - ushort endGlyphId = reader.ReadUInt16(); - uint svgDocOff = reader.ReadUInt32(); - uint svgDocLen = reader.ReadUInt32(); - - if (svgDocLen == 0) continue; - - // svgDocOff is relative to the start of SVGDocumentList. - long absDocOffset = docListBase + svgDocOff; - if (absDocOffset + svgDocLen > rawBytes.Length) continue; - - records.Add(new SvgRecord - { - StartGlyphId = startGlyphId, - EndGlyphId = endGlyphId, - DataOffset = (int)absDocOffset, - DataLength = (int)svgDocLen - }); - } - - return new TtfSvgTable(rawBytes, records.ToArray()); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static byte[]? Decompress(byte[] compressed) - { - try - { - using var input = new MemoryStream(compressed); - using var gz = new GZipStream(input, CompressionMode.Decompress); - using var output = new MemoryStream(); - gz.CopyTo(output); - return output.ToArray(); - } - catch - { - return null; - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfTableBase.cs b/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfTableBase.cs deleted file mode 100644 index 7498ff7b..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/Tables/TtfTableBase.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf.Tables -{ - /// - /// Abstract base for all parsed OpenType/TrueType table objects. - /// Holds the raw table bytes so individual parsers can be re-run on demand. - /// - public abstract class TtfTableBase - { - /// Four-character ASCII table tag (e.g. "head", "cmap"). - public string Tag { get; } - - /// - /// Raw bytes of this table as extracted from the font file. - /// The slice corresponds exactly to the byte range described by the - /// entry in the table directory. - /// - public byte[] RawBytes { get; } - - /// - /// Initializes a new with the specified tag and raw bytes. - /// - /// The four-character ASCII table tag. - /// The raw bytes of the table. - protected TtfTableBase(string tag, byte[] rawBytes) - { - Tag = tag ?? throw new ArgumentNullException(nameof(tag)); - RawBytes = rawBytes ?? throw new ArgumentNullException(nameof(rawBytes)); - } - - /// - /// Creates a new positioned at byte 0 of - /// . The caller owns the returned reader and must - /// dispose it (which also disposes the underlying ). - /// - protected FontBinaryReader CreateReader() => - new FontBinaryReader(new MemoryStream(RawBytes)); - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/TtfFont.cs b/src/MiniPdf/Drawing/Font/Ttf/TtfFont.cs deleted file mode 100644 index 23e6d39e..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/TtfFont.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Encoding; -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Font.Ttf -{ - /// - /// Represents a loaded TrueType or OpenType/TT font face. - /// Implements ; exposes the full parsed table set via - /// . - /// - public sealed class TtfFont : IFont - { - // ── Private state ───────────────────────────────────────────────────── - - private readonly FontMetrics _metrics; - private readonly IFontEncoding _encoding; - private readonly TtfGlyphAccessor _glyphAccessor; - - // ── Constructor ─────────────────────────────────────────────────────── - - internal TtfFont(TtfTables tables) - { - TtfTables = tables ?? throw new ArgumentNullException(nameof(tables)); - - // Build metrics from hhea + optional OS/2. - _metrics = BuildMetrics(tables); - - // Build encoding from best Unicode cmap subtable. - _encoding = BuildEncoding(tables); - - // Build glyph accessor. - _glyphAccessor = new TtfGlyphAccessor(tables); - } - - // ── TtfFont-specific property ───────────────────────────────────────── - - /// All parsed OpenType tables for this font. - public TtfTables TtfTables { get; } - - // ── IFont ───────────────────────────────────────────────────────────── - - /// - public string FontName => - TtfTables.Name.FullName - ?? TtfTables.Name.PostScriptName - ?? TtfTables.Name.FamilyName - ?? "(unknown)"; - - /// - public string FontFamily => - TtfTables.Name.FamilyName ?? "(unknown)"; - - /// - public int NumGlyphs => TtfTables.Maxp.NumGlyphs; - - /// - public FontFaceStyle Style => ResolveStyle(TtfTables.Head.MacStyle); - - /// - public IFontMetrics Metrics => _metrics; - - /// - public IFontEncoding Encoding => _encoding; - - /// - public IGlyphAccessor GlyphAccessor => _glyphAccessor; - - /// - public void Save(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - TtfFontWriter.Write(this, stream); - } - - /// - public void Save(string filePath) - { - if (filePath is null) throw new ArgumentNullException(nameof(filePath)); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, - FileShare.None, bufferSize: 4096); - Save(fs); - } - - /// - /// Returns a string representation of this TrueType font. - /// - public override string ToString() => - $"TtfFont(\"{FontName}\", {NumGlyphs} glyphs)"; - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static FontMetrics BuildMetrics(TtfTables t) - { - var m = new FontMetrics(gid => - { - if (gid is GlyphUInt32Id uid) - return t.Hmtx.GetAdvanceWidth((int)uid.Value); - return 0.0; - }); - - m.Ascender = t.Hhea.Ascender; - m.Descender = t.Hhea.Descender; - m.LineGap = t.Hhea.LineGap; - m.UnitsPerEM = t.Head.UnitsPerEm; - - // OS/2 typographic values are preferred when available. - if (t.Os2Table != null) - { - m.TypoAscender = t.Os2Table.TypoAscender; - m.TypoDescender = t.Os2Table.TypoDescender; - m.StrikeoutPosition = t.Os2Table.StrikeoutPosition; - m.StrikeoutSize = t.Os2Table.StrikeoutSize; - } - else - { - m.TypoAscender = t.Hhea.Ascender; - m.TypoDescender = t.Hhea.Descender; - } - - // post table underline metrics. - if (t.Post != null) - { - m.UnderlinePosition = t.Post.UnderlinePosition; - m.UnderlineThickness = t.Post.UnderlineThickness; - } - - return m; - } - - private static IFontEncoding BuildEncoding(TtfTables t) - { - if (t.CMapTable != null) - { - var best = t.CMapTable.FindUnicodeTable(); - if (best != null) - return new TtfUnicodeEncoding(best); - } - return NullEncoding.Instance; - } - - private static FontFaceStyle ResolveStyle(ushort macStyle) - { - bool bold = (macStyle & 0x01) != 0; - bool italic = (macStyle & 0x02) != 0; - if (bold && italic) return FontFaceStyle.BoldItalic; - if (bold) return FontFaceStyle.Bold; - if (italic) return FontFaceStyle.Italic; - return FontFaceStyle.Regular; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/TtfFontReader.cs b/src/MiniPdf/Drawing/Font/Ttf/TtfFontReader.cs deleted file mode 100644 index 0752ed6e..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/TtfFontReader.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.IO; -using MiniSoftware.Drawing.Font.Ttf.Tables; - -namespace MiniSoftware.Drawing.Font.Ttf -{ - /// - /// Reads a TrueType or OpenType/TT font from a stream and returns a fully - /// parsed . - /// - /// - /// The stream is read sequentially from its current position; it must be - /// seekable because individual table bytes are read by absolute offset. - /// The stream is not disposed by this reader. - /// - public static class TtfFontReader - { - /// - /// Parses the sfnt data from and returns a - /// . - /// - /// stream is null. - /// - /// The stream does not start with a recognised sfnt magic value, or a - /// required table is missing. - /// - public static TtfFont Read(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - - using var reader = new FontBinaryReader(stream, leaveOpen: true); - - // ── Parse offset table + table directory ────────────────────────── - var (header, records) = OpenTypeTableDirectory.Parse(reader); - - // ── Read all raw table bytes keyed by tag ───────────────────────── - var rawTables = OpenTypeTableDirectory.ReadAllTableBytes(reader, records); - - // ── Required tables ─────────────────────────────────────────────── - TtfHeadTable head = ParseRequired(rawTables, "head", - b => TtfHeadTable.Parse(b)); - - TtfHheaTable hhea = ParseRequired(rawTables, "hhea", - b => TtfHheaTable.Parse(b)); - - TtfMaxpTable maxp = ParseRequired(rawTables, "maxp", - b => TtfMaxpTable.Parse(b)); - - TtfNameTable name = ParseRequired(rawTables, "name", - b => TtfNameTable.Parse(b)); - - TtfHmtxTable hmtx = ParseRequired(rawTables, "hmtx", - b => TtfHmtxTable.Parse(b, hhea.NumberOfHMetrics, maxp.NumGlyphs)); - - // ── Optional tables ─────────────────────────────────────────────── - TtfOs2Table? os2 = ParseOptional(rawTables, "OS/2", - b => TtfOs2Table.Parse(b)); - - TtfPostTable? post = ParseOptional(rawTables, "post", - b => TtfPostTable.Parse(b)); - - TtfCMapTable? cmap = ParseOptional(rawTables, "cmap", - b => TtfCMapTable.Parse(b)); - - // "loca" and "glyf" are only present in TrueType-outline fonts. - TtfLocaTable? loca = null; - if (rawTables.ContainsKey("loca")) - { - loca = TtfLocaTable.Parse( - rawTables["loca"], - head.IndexToLocFormat, - (ushort)maxp.NumGlyphs); - } - - TtfGlyfTable? glyf = null; - if (rawTables.ContainsKey("glyf") && loca != null) - { - glyf = TtfGlyfTable.Create(rawTables["glyf"], loca); - } - - // ── Batch 13 optional tables ────────────────────────────────────── - TtfKernTable? kern = ParseOptional(rawTables, "kern", - b => TtfKernTable.Parse(b)); - - TtfGdefTable? gdef = ParseOptional(rawTables, "GDEF", - b => TtfGdefTable.Parse(b)); - - TtfGsubTable? gsub = ParseOptional(rawTables, "GSUB", - b => TtfGsubTable.Parse(b)); - - TtfGposTable? gpos = ParseOptional(rawTables, "GPOS", - b => TtfGposTable.Parse(b)); - // ── Batch 14 optional tables ────────────────────────────────────────────────── - TtfFvarTable? fvar = ParseOptional(rawTables, "fvar", - b => TtfFvarTable.Parse(b)); - - TtfGvarTable? gvar = ParseOptional(rawTables, "gvar", - b => TtfGvarTable.Parse(b)); - - TtfAvarTable? avar = ParseOptional(rawTables, "avar", - b => TtfAvarTable.Parse(b)); - - // ── Batch 15 optional tables ────────────────────────────────────── - // CBLC and CBDT must be parsed together; CBLC provides the glyph offsets. - TtfCbdtTable? cbdt = null; - if (rawTables.TryGetValue("CBLC", out byte[]? cblcBytes) && - rawTables.TryGetValue("CBDT", out byte[]? cbdtBytes)) - { - try - { - var cblc = TtfCblcTable.Parse(cblcBytes!); - cbdt = TtfCbdtTable.Parse(cbdtBytes!, cblcBytes!, cblc); - } - catch { /* malformed table — leave cbdt null */ } - } - - TtfSvgTable? svg = ParseOptional(rawTables, "SVG ", - b => TtfSvgTable.Parse(b)); - - // ── Assemble and return ─────────────────────────────────────────── - var tables = new TtfTables(head, hhea, maxp, name, hmtx, - os2, post, loca, glyf, cmap, - kern, gdef, gsub, gpos, - fvar, gvar, avar, - cbdt, svg); - return new TtfFont(tables); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static T ParseRequired( - IReadOnlyDictionary rawTables, - string tag, - Func parser) - { - if (!rawTables.TryGetValue(tag, out byte[]? raw)) - throw new InvalidOperationException( - $"Required OpenType table '{tag}' is missing from the font."); - return parser(raw); - } - - private static T? ParseOptional( - IReadOnlyDictionary rawTables, - string tag, - Func parser) - where T : class - { - if (!rawTables.TryGetValue(tag, out byte[]? raw)) return null; - try { return parser(raw); } - catch { return null; } // Corrupt optional table — skip gracefully. - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/TtfFontWriter.cs b/src/MiniPdf/Drawing/Font/Ttf/TtfFontWriter.cs deleted file mode 100644 index c745f8fd..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/TtfFontWriter.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.IO; - -namespace MiniSoftware.Drawing.Font.Ttf -{ - /// - /// Serialises a back to a binary sfnt stream. - /// Uses the raw table bytes already stored in each parsed table, so no - /// per-table re-serialisation is required. - /// - public static class TtfFontWriter - { - // ───────────────────────────────────────────────────────────────────── - // Public entry point - // ───────────────────────────────────────────────────────────────────── - - /// - /// Serialises and writes the resulting sfnt bytes to - /// . - /// - /// Either argument is null. - public static void Write(TtfFont font, Stream stream) - { - if (font == null) throw new ArgumentNullException(nameof(font)); - if (stream == null) throw new ArgumentNullException(nameof(stream)); - - byte[] data = WriteToBytes(font); - stream.Write(data, 0, data.Length); - } - - /// - /// Serialises and returns the resulting sfnt bytes. - /// - public static byte[] WriteToBytes(TtfFont font) - { - if (font == null) throw new ArgumentNullException(nameof(font)); - - // ── 1. Collect (tag, rawBytes) pairs in canonical sfnt order ───── - var tables = CollectTables(font.TtfTables); - - // ── 2. Determine sfnt version ──────────────────────────────────── - // TrueType-outline fonts have a glyf table; CFF-flavoured OTF don't. - // For an OTF/CFF font opened via TtfFont (edge-case), default to OTTO. - uint sfVersion = (font.TtfTables.GlyfTable != null) - ? OpenTypeOffsetTable.SfVersionTrueType - : OpenTypeOffsetTable.SfVersionCff; - - return BuildSfnt(sfVersion, tables); - } - - // ───────────────────────────────────────────────────────────────────── - // Internal helpers (also called by CffFontWriter) - // ───────────────────────────────────────────────────────────────────── - - /// - /// Builds a complete sfnt binary from the supplied (tag, bytes) pairs. - /// Patches head.checkSumAdjustment per spec. - /// - internal static byte[] BuildSfnt(uint sfVersion, - IReadOnlyList<(string Tag, byte[] Data)> tables) - { - int n = tables.Count; - - // Derived sfnt offset-table fields (binary-search acceleration). - int log2n = Log2Floor(n); - ushort searchRange = (ushort)((1 << log2n) * 16); - ushort entrySelector = (ushort)log2n; - ushort rangeShift = (ushort)(n * 16 - searchRange); - - // Compute the byte offsets of each table in the output. - // Layout: 12-byte offset table + n*16 table records + table data (4-aligned). - int dataStart = 12 + n * 16; - var offsets = new int[n]; - var paddedLengths = new int[n]; - - int currentOffset = dataStart; - for (int i = 0; i < n; i++) - { - offsets[i] = currentOffset; - int raw = tables[i].Data.Length; - paddedLengths[i] = (raw + 3) & ~3; // round up to multiple of 4 - currentOffset += paddedLengths[i]; - } - - int totalSize = currentOffset; - byte[] buf = new byte[totalSize]; - - // ── Write offset table (12 bytes) ───────────────────────────────── - WriteUInt32BE(buf, 0, sfVersion); - WriteUInt16BE(buf, 4, (ushort)n); - WriteUInt16BE(buf, 6, searchRange); - WriteUInt16BE(buf, 8, entrySelector); - WriteUInt16BE(buf, 10, rangeShift); - - // ── Write table records (16 bytes each) ────────────────────────── - // Tags must be sorted in ascending ASCII order per spec. - // Our CollectTables already returns them sorted, but we still compute - // checksums from the padded data at this step. - int recBase = 12; - for (int i = 0; i < n; i++) - { - var (tag, data) = tables[i]; - uint checksum = OpenTypeTableDirectory.ComputeChecksum(data); - - // Copy padded table data first so head patching can use final bytes. - Array.Copy(data, 0, buf, offsets[i], data.Length); - // Padding bytes are already zero (new byte[] is zero-initialised). - - WriteTagBytes(buf, recBase + i * 16, tag); - WriteUInt32BE(buf, recBase + i * 16 + 4, checksum); - WriteUInt32BE(buf, recBase + i * 16 + 8, (uint)offsets[i]); - WriteUInt32BE(buf, recBase + i * 16 + 12, (uint)data.Length); - } - - // ── Patch head.checkSumAdjustment ───────────────────────────────── - // Per spec: - // 1. Zero out bytes 8-11 of the head table. - // 2. Sum all uint32 words in the entire file (big-endian, padded). - // 3. checkSumAdjustment = 0xB1B0AFBA - totalSum. - int headIdx = FindTableIndex(tables, "head"); - if (headIdx >= 0) - { - // Zero the checkSumAdjustment field in the buffer. - int csa = offsets[headIdx] + 8; - if (csa + 4 <= buf.Length) - { - buf[csa] = 0; - buf[csa + 1] = 0; - buf[csa + 2] = 0; - buf[csa + 3] = 0; - } - - // Recompute head checksum with zeroed CSA and update table record. - int headDataLen = tables[headIdx].Data.Length; - byte[] headSlice = new byte[paddedLengths[headIdx]]; - Array.Copy(buf, offsets[headIdx], headSlice, 0, headSlice.Length); - uint newHeadChecksum = OpenTypeTableDirectory.ComputeChecksum(headSlice); - WriteUInt32BE(buf, recBase + headIdx * 16 + 4, newHeadChecksum); - - // Compute sum of the whole file. - uint fileSum = SumFile(buf); - - // Write checkSumAdjustment. - uint adj = unchecked(0xB1B0AFBAu - fileSum); - WriteUInt32BE(buf, csa, adj); - } - - return buf; - } - - // ───────────────────────────────────────────────────────────────────── - // Table collection - // ───────────────────────────────────────────────────────────────────── - - /// - /// Enumerates all non-null tables present in and returns - /// them sorted by tag (ascending ASCII, as required by the sfnt spec). - /// - internal static List<(string Tag, byte[] Data)> CollectTables(TtfTables t) - { - var result = new List<(string Tag, byte[] Data)>(24); - - Add(result, "head", t.Head.RawBytes); - Add(result, "hhea", t.Hhea.RawBytes); - Add(result, "maxp", t.Maxp.RawBytes); - Add(result, "name", t.Name.RawBytes); - Add(result, "hmtx", t.Hmtx.RawBytes); - - if (t.Os2Table != null) Add(result, "OS/2", t.Os2Table.RawBytes); - if (t.Post != null) Add(result, "post", t.Post.RawBytes); - if (t.Loca != null) Add(result, "loca", t.Loca.RawBytes); - if (t.GlyfTable != null) Add(result, "glyf", t.GlyfTable.RawBytes); - if (t.CMapTable != null) Add(result, "cmap", t.CMapTable.RawBytes); - - // Batch 13 — advanced layout - if (t.KernTable != null) Add(result, "kern", t.KernTable.RawBytes); - if (t.GdefTable != null) Add(result, "GDEF", t.GdefTable.RawBytes); - if (t.GsubTable != null) Add(result, "GSUB", t.GsubTable.RawBytes); - if (t.GposTable != null) Add(result, "GPOS", t.GposTable.RawBytes); - - // Batch 14 — variable fonts - if (t.FvarTable != null) Add(result, "fvar", t.FvarTable.RawBytes); - if (t.GvarTable != null) Add(result, "gvar", t.GvarTable.RawBytes); - if (t.AvarTable != null) Add(result, "avar", t.AvarTable.RawBytes); - - // Batch 15 — colour bitmaps (CBLC must precede CBDT) - if (t.CbdtTable != null) - { - Add(result, "CBLC", t.CbdtTable.CblcRawBytes); - Add(result, "CBDT", t.CbdtTable.RawBytes); - } - if (t.SvgTable != null) Add(result, "SVG ", t.SvgTable.RawBytes); - - // Sort ascending by tag (ASCII order) — sfnt spec requirement. - result.Sort((a, b) => string.Compare(a.Tag, b.Tag, StringComparison.Ordinal)); - - return result; - } - - // ───────────────────────────────────────────────────────────────────── - // Low-level binary helpers - // ───────────────────────────────────────────────────────────────────── - - private static void Add(List<(string Tag, byte[] Data)> list, string tag, byte[] data) - { - if (data != null && data.Length >= 0) - list.Add((tag, data)); - } - - private static int FindTableIndex(IReadOnlyList<(string Tag, byte[] Data)> tables, - string tag) - { - for (int i = 0; i < tables.Count; i++) - if (tables[i].Tag == tag) return i; - return -1; - } - - private static uint SumFile(byte[] buf) - { - uint sum = 0; - int wordCount = (buf.Length + 3) / 4; - for (int i = 0; i < wordCount; i++) - { - int pos = i * 4; - uint w = 0; - for (int b = 0; b < 4; b++) - w = (w << 8) | (uint)(pos + b < buf.Length ? buf[pos + b] : 0); - sum = unchecked(sum + w); - } - return sum; - } - - internal static void WriteUInt32BE(byte[] buf, int offset, uint value) - { - buf[offset ] = (byte)(value >> 24); - buf[offset + 1] = (byte)(value >> 16); - buf[offset + 2] = (byte)(value >> 8); - buf[offset + 3] = (byte) value; - } - - internal static void WriteUInt16BE(byte[] buf, int offset, ushort value) - { - buf[offset ] = (byte)(value >> 8); - buf[offset + 1] = (byte) value; - } - - private static void WriteTagBytes(byte[] buf, int offset, string tag) - { - // Tags are exactly 4 ASCII characters; pad with spaces if shorter. - for (int i = 0; i < 4; i++) - buf[offset + i] = (byte)(i < tag.Length ? tag[i] : ' '); - } - - private static int Log2Floor(int n) - { - if (n <= 0) return 0; - int r = 0; - while (n > 1) { n >>= 1; r++; } - return r; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/TtfGlyphAccessor.cs b/src/MiniPdf/Drawing/Font/Ttf/TtfGlyphAccessor.cs deleted file mode 100644 index e905ae22..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/TtfGlyphAccessor.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Ttf.Glyphs; - -namespace MiniSoftware.Drawing.Font.Ttf -{ - /// - /// Implements for TrueType/OTF fonts. - /// Retrieves glyph metrics from "hmtx" and outline bounds from "glyf". - /// - public sealed class TtfGlyphAccessor : IGlyphAccessor - { - private readonly TtfTables _tables; - - internal TtfGlyphAccessor(TtfTables tables) - { - _tables = tables ?? throw new ArgumentNullException(nameof(tables)); - } - - /// - public Glyph? GetGlyphById(GlyphId glyphId) - { - if (glyphId is null) return null; - - if (glyphId is GlyphUInt32Id uid) - return GetGlyphByIndex(uid.Value); - - return null; - } - - /// - public Glyph? GetGlyphByIndex(uint index) - { - int i = (int)index; - - if (i < 0 || i >= _tables.Maxp.NumGlyphs) - return null; - - // Advance width from hmtx (design units). - double advanceWidth = _tables.Hmtx.GetAdvanceWidth(i); - - // Bounding box from glyf (if present), otherwise empty. - GlyphBoundingBox bbox = GlyphBoundingBox.Empty; - if (_tables.GlyfTable != null) - { - GlyphOutlineData? outline = _tables.GlyfTable.GetGlyphOutline(i); - if (outline != null) - bbox = outline.BBox; - } - - return new Glyph(new GlyphUInt32Id(index), bbox, advanceWidth); - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Ttf/TtfTables.cs b/src/MiniPdf/Drawing/Font/Ttf/TtfTables.cs deleted file mode 100644 index b38a3464..00000000 --- a/src/MiniPdf/Drawing/Font/Ttf/TtfTables.cs +++ /dev/null @@ -1,122 +0,0 @@ -using MiniSoftware.Drawing.Font.Ttf.Tables; - -namespace MiniSoftware.Drawing.Font.Ttf -{ - /// - /// Property bag that holds every parsed OpenType table for a TrueType/OTF font. - /// Required tables are non-nullable; optional tables (absent from some fonts) - /// are nullable. - /// - public sealed class TtfTables - { - // ── Required tables ─────────────────────────────────────────────────── - - /// "head" — font header: unitsPerEm, bounds, indexToLocFormat. - public TtfHeadTable Head { get; } - - /// "hhea" — horizontal header: ascender, descender, lineGap, numberOfHMetrics. - public TtfHheaTable Hhea { get; } - - /// "maxp" — maximum profile: numGlyphs. - public TtfMaxpTable Maxp { get; } - - /// "name" — naming table: family name, full name, PostScript name, etc. - public TtfNameTable Name { get; } - - /// "hmtx" — horizontal metrics: advance widths and left side-bearings. - public TtfHmtxTable Hmtx { get; } - - // ── Optional tables ─────────────────────────────────────────────────── - - /// "OS/2" — Windows metrics and license flags. Absent in some old Mac fonts. - public TtfOs2Table? Os2Table { get; } - - /// "post" — PostScript compatibility info: italic angle, isFixedPitch. - public TtfPostTable? Post { get; } - - /// - /// "loca" — glyph offset index. Present only in TrueType-outline fonts; - /// null for CFF-flavored OTF. - /// - public TtfLocaTable? Loca { get; } - - /// - /// "glyf" — TrueType glyph outline data. Null for CFF-flavored OTF. - /// - public TtfGlyfTable? GlyfTable { get; } - - /// "cmap" — character-to-glyph-index map. Null for symbol/private-use fonts. - public TtfCMapTable? CMapTable { get; } - - /// "kern" — horizontal kerning pairs (format 0). Null when absent or Apple AAT only. - public TtfKernTable? KernTable { get; } - - /// "GDEF" — glyph classification (Base, Ligature, Mark, Component). Null when absent. - public TtfGdefTable? GdefTable { get; } - - /// "GSUB" — substitution feature tags (e.g. "liga", "calt"). Null when absent. - public TtfGsubTable? GsubTable { get; } - - /// "GPOS" — positioning feature tags (e.g. "kern", "mark"). Null when absent. - public TtfGposTable? GposTable { get; } - - /// "fvar" — variation axes and named instances. Null in non-variable fonts. - public TtfFvarTable? FvarTable { get; } - - /// "gvar" — per-glyph tuple variation data. Null in non-variable fonts. - public TtfGvarTable? GvarTable { get; } - - /// "avar" — axis variation segment maps. Null in non-variable fonts. - public TtfAvarTable? AvarTable { get; } - - /// "CBDT"/"CBLC" — colour bitmap glyph images. Null in non-colour fonts. - public TtfCbdtTable? CbdtTable { get; } - - /// "SVG " — SVG glyph outlines. Null in non-SVG fonts. - public TtfSvgTable? SvgTable { get; } - - // ── Constructor ─────────────────────────────────────────────────────── - - internal TtfTables( - TtfHeadTable head, - TtfHheaTable hhea, - TtfMaxpTable maxp, - TtfNameTable name, - TtfHmtxTable hmtx, - TtfOs2Table? os2Table, - TtfPostTable? post, - TtfLocaTable? loca, - TtfGlyfTable? glyfTable, - TtfCMapTable? cmapTable, - TtfKernTable? kernTable = null, - TtfGdefTable? gdefTable = null, - TtfGsubTable? gsubTable = null, - TtfGposTable? gposTable = null, - TtfFvarTable? fvarTable = null, - TtfGvarTable? gvarTable = null, - TtfAvarTable? avarTable = null, - TtfCbdtTable? cbdtTable = null, - TtfSvgTable? svgTable = null) - { - Head = head; - Hhea = hhea; - Maxp = maxp; - Name = name; - Hmtx = hmtx; - Os2Table = os2Table; - Post = post; - Loca = loca; - GlyfTable = glyfTable; - CMapTable = cmapTable; - KernTable = kernTable; - GdefTable = gdefTable; - GsubTable = gsubTable; - GposTable = gposTable; - FvarTable = fvarTable; - GvarTable = gvarTable; - AvarTable = avarTable; - CbdtTable = cbdtTable; - SvgTable = svgTable; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Type1/Type1CharStringInterpreter.cs b/src/MiniPdf/Drawing/Font/Type1/Type1CharStringInterpreter.cs deleted file mode 100644 index 1e1ebe67..00000000 --- a/src/MiniPdf/Drawing/Font/Type1/Type1CharStringInterpreter.cs +++ /dev/null @@ -1,398 +0,0 @@ -using System.Collections.Generic; -using MiniSoftware.Drawing.Font.Rendering; - -namespace MiniSoftware.Drawing.Font.Type1 -{ - /// - /// Executes a decrypted Type 1 charstring, emitting drawing commands to an - /// . Returns the advance width of the glyph. - /// - /// - /// Operators implemented: hsbw, sbw, vmoveto, hmoveto, rmoveto, - /// rlineto, hlineto, vlineto, rrcurveto, vhcurveto, hvcurveto, closepath, endchar, - /// hstem, vstem, hstem3, vstem3 (ignored for rendering), seac, - /// callsubr, return, div, dotsection, callothersubr, pop, setcurrentpoint. - /// - public sealed class Type1CharStringInterpreter - { - // ── Entry point ─────────────────────────────────────────────────────── - - /// - /// Executes and delivers outline commands - /// to . - /// - /// Decrypted Type 1 charstring bytes. - /// Receives outline drawing commands. - /// The font's /Subrs array (decrypted), or null. - /// All font charstrings keyed by glyph name - /// (needed to implement seac). May be null if seac is not expected. - /// The glyph advance width in font units. - public double Interpret( - byte[] charstring, - IGlyphOutlinePainter painter, - byte[][]? subrs, - Dictionary? charStrings) - { - if (charstring is null || charstring.Length == 0) return 0.0; - - var state = new InterpState(painter, subrs, charStrings); - Execute(charstring, state, 0); - return state.AdvanceWidth; - } - - // ── Core execution ──────────────────────────────────────────────────── - - private static void Execute(byte[] data, InterpState s, int depth) - { - if (depth > 10) return; // guard against runaway recursion - - int pos = 0, len = data.Length; - - while (pos < len) - { - byte b = data[pos++]; - - // ── Number encoding ─────────────────────────────────────────── - if (b >= 32 && b <= 246) - { - s.Push(b - 139); - continue; - } - if (b >= 247 && b <= 250) - { - if (pos >= len) return; - s.Push((b - 247) * 256.0 + data[pos++] + 108); - continue; - } - if (b >= 251 && b <= 254) - { - if (pos >= len) return; - s.Push(-((b - 251) * 256.0 + data[pos++] + 108)); - continue; - } - if (b == 255) // 4-byte signed integer - { - if (pos + 3 >= len) return; - int v = (data[pos] << 24) | (data[pos + 1] << 16) - | (data[pos + 2] << 8) | data[pos + 3]; - pos += 4; - s.Push(v); - continue; - } - - // ── Two-byte escape (12) ────────────────────────────────────── - if (b == 12) - { - if (pos >= len) return; - byte b2 = data[pos++]; - ExecuteEscape(b2, s, depth); - continue; - } - - // ── One-byte operators ──────────────────────────────────────── - switch (b) - { - case 1: // hstem – horizontal stem hint, ignore for rendering - case 3: // vstem – vertical stem hint, ignore for rendering - s.ClearStack(); - break; - - case 4: // vmoveto dy - { - double dy = s.PopOrZero(); - s.MoveBy(0, dy); - break; - } - - case 5: // rlineto dx dy - { - double dy = s.PopOrZero(); - double dx = s.PopOrZero(); - s.LineBy(dx, dy); - break; - } - - case 6: // hlineto dx - { - double dx = s.PopOrZero(); - s.LineBy(dx, 0); - break; - } - - case 7: // vlineto dy - { - double dy = s.PopOrZero(); - s.LineBy(0, dy); - break; - } - - case 8: // rrcurveto dx1 dy1 dx2 dy2 dx3 dy3 - { - double dy3 = s.PopOrZero(), dx3 = s.PopOrZero(); - double dy2 = s.PopOrZero(), dx2 = s.PopOrZero(); - double dy1 = s.PopOrZero(), dx1 = s.PopOrZero(); - s.CurveBy(dx1, dy1, dx2, dy2, dx3, dy3); - break; - } - - case 9: // closepath - s.ClosePath(); - break; - - case 10: // callsubr index - { - int idx = (int)s.PopOrZero(); - if (s.Subrs != null && idx >= 0 && idx < s.Subrs.Length - && s.Subrs[idx] != null) - { - Execute(s.Subrs[idx]!, s, depth + 1); - } - break; - } - - case 11: // return (from subr) - return; - - case 13: // hsbw sbx wx - { - double wx = s.PopOrZero(); - double sbx = s.PopOrZero(); - s.SetOriginAndWidth(sbx, 0.0, wx); - break; - } - - case 14: // endchar - s.ClosePath(); - return; - - case 21: // rmoveto dx dy (later Type 1 revision) - { - double dy = s.PopOrZero(); - double dx = s.PopOrZero(); - s.MoveBy(dx, dy); - break; - } - - case 22: // hmoveto dx - { - double dx = s.PopOrZero(); - s.MoveBy(dx, 0); - break; - } - - case 30: // vhcurveto dy1 dx2 dy2 dx3 - { - double dx3 = s.PopOrZero(), dy2 = s.PopOrZero(); - double dx2 = s.PopOrZero(), dy1 = s.PopOrZero(); - s.CurveBy(0, dy1, dx2, dy2, dx3, 0); - break; - } - - case 31: // hvcurveto dx1 dx2 dy2 dy3 - { - double dy3 = s.PopOrZero(), dy2 = s.PopOrZero(); - double dx2 = s.PopOrZero(), dx1 = s.PopOrZero(); - s.CurveBy(dx1, 0, dx2, dy2, 0, dy3); - break; - } - - // Anything else: skip (unknown/undefined operators) - default: - s.ClearStack(); - break; - } - } - } - - // ── Escape operator dispatch ────────────────────────────────────────── - - private static void ExecuteEscape(byte op, InterpState s, int depth) - { - switch (op) - { - case 0: // dotsection – rendering hint, ignore - break; - - case 1: // vstem3 – 3 vertical stems, ignore - case 2: // hstem3 – 3 horizontal stems, ignore - s.ClearStack(); - break; - - case 6: // seac asb adx ady bchar achar - { - // Standard Encoding Accented Character - // Operand order on stack (bottom→top): asb adx ady bchar achar - int achar = (int)s.PopOrZero(); - int bchar = (int)s.PopOrZero(); - double ady = s.PopOrZero(); - double adx = s.PopOrZero(); - // asb = sidebearing of accent (ignored here) - s.PopOrZero(); - - if (s.CharStrings != null) - { - string? baseName = GetStdEncName(bchar); - string? accentName = GetStdEncName(achar); - - if (baseName != null && s.CharStrings.TryGetValue(baseName, out byte[]? baseCs)) - Execute(baseCs, s, depth + 1); - - if (accentName != null && s.CharStrings.TryGetValue(accentName, out byte[]? accCs)) - { - // Render accent displaced by (adx, ady) from glyph origin - double savedX = s.CX, savedY = s.CY; - s.CX = adx; - s.CY = ady; - Execute(accCs, s, depth + 1); - s.CX = savedX; - s.CY = savedY; - } - } - break; - } - - case 7: // sbw sbx sby wx wy - { - double wy = s.PopOrZero(), wx = s.PopOrZero(); - double sby = s.PopOrZero(), sbx = s.PopOrZero(); - s.SetOriginAndWidth(sbx, sby, wx); - break; - } - - case 12: // div num den → num/den - { - double den = s.PopOrZero(); - double num = s.PopOrZero(); - s.Push(den != 0.0 ? num / den : 0.0); - break; - } - - case 16: // callothersubr proc_num count args... - { - // OtherSubrs are PostScript procedures; we cannot execute them, - // but we must consume the arguments. - int procNum = (int)s.PopOrZero(); - int count = (int)s.PopOrZero(); - // Push the right number of dummy results for subsequent "pop" ops - s.OtherSubrResultCount = count; - for (int i = 0; i < count; i++) s.Pop(); // consume args - break; - } - - case 17: // pop – retrieve result from OtherSubr - // Push 0 as a placeholder for any OtherSubr result - if (s.OtherSubrResultCount > 0) - { - s.OtherSubrResultCount--; - s.Push(0); - } - break; - - case 33: // setcurrentpoint x y - { - double y = s.PopOrZero(), x = s.PopOrZero(); - s.CX = x; - s.CY = y; - break; - } - - default: - s.ClearStack(); - break; - } - } - - // ── Standard encoding name lookup ───────────────────────────────────── - - private static string? GetStdEncName(int charCode) - { - if (charCode < 0 || charCode >= 256) return null; - string[] std = Type1Parser.GetStandardEncoding(); - string name = std[charCode]; - return (name == ".notdef") ? null : name; - } - - // ── Interpreter state ───────────────────────────────────────────────── - - private sealed class InterpState - { - private readonly IGlyphOutlinePainter _painter; - private readonly Stack _stack = new Stack(); - private bool _pathOpen; - - internal byte[][]? Subrs; - internal Dictionary? CharStrings; - - internal double CX; - internal double CY; - internal double AdvanceWidth; - internal int OtherSubrResultCount; - - internal InterpState( - IGlyphOutlinePainter painter, - byte[][]? subrs, - Dictionary? charStrings) - { - _painter = painter; - Subrs = subrs; - CharStrings = charStrings; - } - - // ── Stack helpers ───────────────────────────────────────────────── - - internal void Push(double v) => _stack.Push(v); - - internal double Pop() => _stack.Count > 0 ? _stack.Pop() : 0.0; - internal double PopOrZero() => _stack.Count > 0 ? _stack.Pop() : 0.0; - - internal void ClearStack() => _stack.Clear(); - - // ── Movement / drawing ──────────────────────────────────────────── - - internal void SetOriginAndWidth(double sbx, double sby, double wx) - { - CX = sbx; - CY = sby; - AdvanceWidth = wx; - } - - internal void MoveBy(double dx, double dy) - { - if (_pathOpen) { _painter.ClosePath(); _pathOpen = false; } - CX += dx; - CY += dy; - _painter.MoveTo(new MoveTo(CX, CY)); - _pathOpen = true; - } - - internal void LineBy(double dx, double dy) - { - CX += dx; - CY += dy; - _painter.LineTo(new LineTo(CX, CY)); - } - - internal void CurveBy( - double dx1, double dy1, - double dx2, double dy2, - double dx3, double dy3) - { - double x1 = CX + dx1, y1 = CY + dy1; - double x2 = x1 + dx2, y2 = y1 + dy2; - double x3 = x2 + dx3, y3 = y2 + dy3; - _painter.CurveTo(new CurveTo(x1, y1, x2, y2, x3, y3)); - CX = x3; - CY = y3; - } - - internal void ClosePath() - { - if (_pathOpen) - { - _painter.ClosePath(); - _pathOpen = false; - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Type1/Type1Data.cs b/src/MiniPdf/Drawing/Font/Type1/Type1Data.cs deleted file mode 100644 index ec5e6d63..00000000 --- a/src/MiniPdf/Drawing/Font/Type1/Type1Data.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Font.Type1 -{ - /// - /// Internal representation of a parsed Type 1 font file. - /// Populated by . - /// - internal sealed class Type1Data - { - /// PostScript font name from /FontName. - public string FontName = string.Empty; - - /// Font bounding box [xMin, yMin, xMax, yMax]. - public double[] FontBBox = new double[4]; - - /// - /// Number of random bytes prepended to each encrypted charstring. - /// Typically 4; 0 means no encryption seed bytes. - /// - public int LenIV = 4; - - /// Decrypted charstrings keyed by glyph name. - public Dictionary CharStrings = new Dictionary(); - - /// - /// Glyph names in the order they were encountered during parsing. - /// Index in this array is the glyph index used by . - /// - public string[] GlyphOrder = System.Array.Empty(); - - /// - /// Decrypted subroutine charstrings from /Subrs. - /// Null when the font has no subroutines. - /// - public byte[][]? Subrs; - - /// - /// Font encoding: maps byte value (0-255) to a glyph name. - /// Defaults to .notdef for unmapped slots. - /// - public string[] Encoding = new string[256]; - - public Type1Data() - { - for (int i = 0; i < 256; i++) Encoding[i] = ".notdef"; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Type1/Type1Font.cs b/src/MiniPdf/Drawing/Font/Type1/Type1Font.cs deleted file mode 100644 index 526f89bf..00000000 --- a/src/MiniPdf/Drawing/Font/Type1/Type1Font.cs +++ /dev/null @@ -1,382 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Encoding; -using MiniSoftware.Drawing.Font.Glyphs; -using MiniSoftware.Drawing.Font.Rendering; - -namespace MiniSoftware.Drawing.Font.Type1 -{ - /// - /// Represents a loaded Type 1 font face (PFB or PFA). - /// Charstrings are decoded via . - /// - public sealed class Type1Font : IFont - { - // ── Private state ───────────────────────────────────────────────────── - - internal readonly Type1Data Data; - private readonly FontMetrics _metrics; - private readonly IFontEncoding _encoding; - private readonly Type1GlyphAccessor _glyphAccessor; - - // ── Internal name→index map ─────────────────────────────────────────── - - // Maps glyph name to its index in GlyphOrder (used for encoding lookup) - internal readonly IReadOnlyDictionary NameToIndex; - - // ── Constructor ─────────────────────────────────────────────────────── - - internal Type1Font(Type1Data data) - { - Data = data ?? throw new ArgumentNullException(nameof(data)); - - // Build name→index map once - var nameToIdx = new Dictionary( - data.GlyphOrder.Length, StringComparer.Ordinal); - for (int i = 0; i < data.GlyphOrder.Length; i++) - nameToIdx[data.GlyphOrder[i]] = i; - NameToIndex = nameToIdx; - - _metrics = BuildMetrics(data); - _encoding = new Type1FontEncoding(data, nameToIdx); - _glyphAccessor = new Type1GlyphAccessor(data, this); - } - - // ── IFont ───────────────────────────────────────────────────────────── - - /// - public string FontName => Data.FontName.Length > 0 ? Data.FontName : "(Type1)"; - - /// - public string FontFamily => StripStyleSuffix(FontName); - - /// - public int NumGlyphs => Data.CharStrings.Count; - - /// - public FontFaceStyle Style => FontFaceStyle.Regular; // Type 1 has no macStyle bits - - /// - public IFontMetrics Metrics => _metrics; - - /// - public IFontEncoding Encoding => _encoding; - - /// - public IGlyphAccessor GlyphAccessor => _glyphAccessor; - - /// - /// Type 1 serialisation is outside the scope of this library. - public void Save(Stream stream) - { - if (stream is null) throw new ArgumentNullException(nameof(stream)); - throw new NotSupportedException("Type1Font serialisation is not supported."); - } - - /// - public void Save(string filePath) - { - if (filePath is null) throw new ArgumentNullException(nameof(filePath)); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, - FileShare.None, bufferSize: 4096); - Save(fs); - } - - /// - /// Returns a string representation of this Type 1 font. - /// - public override string ToString() => - $"Type1Font(\"{FontName}\", {NumGlyphs} glyphs)"; - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static FontMetrics BuildMetrics(Type1Data data) - { - // Type 1 fonts use a 1000-unit em square by default. - // /FontBBox = [xMin yMin xMax yMax] - double yMax = data.FontBBox.Length > 3 ? data.FontBBox[3] : 800; - double yMin = data.FontBBox.Length > 1 ? data.FontBBox[1] : -200; - - double upm = (yMax > 0 && yMin < yMax) ? yMax - yMin : 1000.0; - if (upm <= 0) upm = 1000.0; - - var m = new FontMetrics(gid => - { - if (!(gid is GlyphUInt32Id uid)) return 0.0; - int idx = (int)uid.Value; - if (idx < 0 || idx >= data.GlyphOrder.Length) return 0.0; - string name = data.GlyphOrder[idx]; - if (!data.CharStrings.TryGetValue(name, out byte[]? cs)) return 0.0; - var interp = new Type1CharStringInterpreter(); - return interp.Interpret(cs, NopPainter.Instance, data.Subrs, data.CharStrings); - }) - { - Ascender = yMax, - Descender = yMin, - LineGap = 0, - UnitsPerEM = upm, - TypoAscender = yMax, - TypoDescender = yMin, - }; - return m; - } - - private static string StripStyleSuffix(string name) - { - foreach (string suffix in new[] { "-Bold", "-Italic", "-BoldItalic", "-Regular" }) - { - if (name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) - return name.Substring(0, name.Length - suffix.Length); - } - return name; - } - - // ── No-op painter (for width measurement only) ───────────────────────── - - private sealed class NopPainter : IGlyphOutlinePainter - { - internal static readonly NopPainter Instance = new NopPainter(); - public void MoveTo(MoveTo cmd) { } - public void LineTo(LineTo cmd) { } - public void CurveTo(CurveTo cmd) { } - public void ClosePath() { } - } - } - - // ── Type1GlyphAccessor ──────────────────────────────────────────────────── - - internal sealed class Type1GlyphAccessor : IGlyphAccessor - { - private readonly Type1Data _data; - private readonly Type1Font _font; - - internal Type1GlyphAccessor(Type1Data data, Type1Font font) - { - _data = data; - _font = font; - } - - public Glyph? GetGlyphById(GlyphId gid) - { - if (!(gid is GlyphUInt32Id uid)) return null; - int idx = (int)uid.Value; - if (idx < 0 || idx >= _data.GlyphOrder.Length) return null; - - string name = _data.GlyphOrder[idx]; - if (!_data.CharStrings.TryGetValue(name, out byte[]? cs)) return null; - - var recording = new BBoxPainter(); - var interp = new Type1CharStringInterpreter(); - double width = interp.Interpret(cs, recording, _data.Subrs, _data.CharStrings); - - return new Glyph(gid, recording.GetBBox(), width); - } - - public Glyph? GetGlyphByIndex(uint index) - => GetGlyphById(new GlyphUInt32Id(index)); - - // ── BBox recording painter ──────────────────────────────────────────── - - private sealed class BBoxPainter : IGlyphOutlinePainter - { - private double _xMin = double.MaxValue, _yMin = double.MaxValue; - private double _xMax = double.MinValue, _yMax = double.MinValue; - private bool _has; - - private void Track(double x, double y) - { - if (x < _xMin) _xMin = x; - if (x > _xMax) _xMax = x; - if (y < _yMin) _yMin = y; - if (y > _yMax) _yMax = y; - _has = true; - } - - public void MoveTo(MoveTo c) => Track(c.X, c.Y); - public void LineTo(LineTo c) => Track(c.X, c.Y); - public void CurveTo(CurveTo c) - { - Track(c.X1, c.Y1); - Track(c.X2, c.Y2); - Track(c.X3, c.Y3); - } - public void ClosePath() { } - - public GlyphBoundingBox GetBBox() - => _has - ? new GlyphBoundingBox(_xMin, _yMin, _xMax, _yMax) - : new GlyphBoundingBox(0, 0, 0, 0); - } - } - - // ── Type1FontEncoding ───────────────────────────────────────────────────── - - internal sealed class Type1FontEncoding : IFontEncoding - { - // Unicode codepoint → glyph name (compact Adobe Glyph List subset) - private static readonly Dictionary AglCodepointToName = - BuildAgl(); - - private readonly string[] _encoding; // slot 0-255 → glyph name - private readonly IReadOnlyDictionary _nameToIndex; - - internal Type1FontEncoding( - Type1Data data, - IReadOnlyDictionary nameToIndex) - { - _encoding = data.Encoding; - _nameToIndex = nameToIndex; - } - - public GlyphId? DecodeToGid(uint codePoint) - { - // 1. Try Adobe Glyph List: codepoint → glyph name → index - if (AglCodepointToName.TryGetValue(codePoint, out string? aglName) - && _nameToIndex.TryGetValue(aglName, out int aglIdx)) - return new GlyphUInt32Id((uint)aglIdx); - - // 2. Try the font's own encoding array for single-byte codepoints - if (codePoint < 256) - { - string slotName = _encoding[codePoint]; - if (slotName != ".notdef" && _nameToIndex.TryGetValue(slotName, out int slotIdx)) - return new GlyphUInt32Id((uint)slotIdx); - } - - return GlyphUInt32Id.NotDefId; - } - - public GlyphId? DecodeToGid(char ch) => DecodeToGid((uint)ch); - - public bool TryGetGlyph(uint codePoint, out uint glyphId) - { - var gid = DecodeToGid(codePoint); - if (gid is Glyphs.GlyphUInt32Id u32 && u32.Value != 0) - { - glyphId = u32.Value; - return true; - } - glyphId = 0; - return false; - } - - public bool HasGlyph(uint codePoint) => TryGetGlyph(codePoint, out _); - - // ── Adobe Glyph List (compact subset: all ASCII + full Latin-1/2) ───── - - private static Dictionary BuildAgl() - { - var d = new Dictionary(); - - // ASCII printable - d[0x20] = "space"; d[0x21] = "exclam"; d[0x22] = "quotedbl"; - d[0x23] = "numbersign"; d[0x24] = "dollar"; d[0x25] = "percent"; - d[0x26] = "ampersand"; d[0x27] = "quotesingle"; d[0x28] = "parenleft"; - d[0x29] = "parenright"; d[0x2A] = "asterisk"; d[0x2B] = "plus"; - d[0x2C] = "comma"; d[0x2D] = "hyphen"; d[0x2E] = "period"; - d[0x2F] = "slash"; - d[0x30] = "zero"; d[0x31] = "one"; d[0x32] = "two"; - d[0x33] = "three"; d[0x34] = "four"; d[0x35] = "five"; - d[0x36] = "six"; d[0x37] = "seven"; d[0x38] = "eight"; - d[0x39] = "nine"; - d[0x3A] = "colon"; d[0x3B] = "semicolon"; d[0x3C] = "less"; - d[0x3D] = "equal"; d[0x3E] = "greater"; d[0x3F] = "question"; - d[0x40] = "at"; - - // A–Z - for (uint i = 0; i < 26; i++) - d[0x41 + i] = ((char)('A' + i)).ToString(); - - d[0x5B] = "bracketleft"; d[0x5C] = "backslash"; d[0x5D] = "bracketright"; - d[0x5E] = "asciicircum"; d[0x5F] = "underscore"; d[0x60] = "grave"; - - // a–z - for (uint i = 0; i < 26; i++) - d[0x61 + i] = ((char)('a' + i)).ToString(); - - d[0x7B] = "braceleft"; d[0x7C] = "bar"; d[0x7D] = "braceright"; - d[0x7E] = "asciitilde"; - - // Latin-1 supplement (U+00A0–U+00FF) - d[0x00A0] = "nbspace"; d[0x00A1] = "exclamdown"; - d[0x00A2] = "cent"; d[0x00A3] = "sterling"; - d[0x00A4] = "currency"; d[0x00A5] = "yen"; - d[0x00A6] = "brokenbar"; d[0x00A7] = "section"; - d[0x00A8] = "dieresis"; d[0x00A9] = "copyright"; - d[0x00AA] = "ordfeminine"; d[0x00AB] = "guillemotleft"; - d[0x00AC] = "logicalnot"; d[0x00AD] = "softhyphen"; - d[0x00AE] = "registered"; d[0x00AF] = "macron"; - d[0x00B0] = "degree"; d[0x00B1] = "plusminus"; - d[0x00B2] = "twosuperior"; d[0x00B3] = "threesuperior"; - d[0x00B4] = "acute"; d[0x00B5] = "mu"; - d[0x00B6] = "paragraph"; d[0x00B7] = "periodcentered"; - d[0x00B8] = "cedilla"; d[0x00B9] = "onesuperior"; - d[0x00BA] = "ordmasculine"; d[0x00BB] = "guillemotright"; - d[0x00BC] = "onequarter"; d[0x00BD] = "onehalf"; - d[0x00BE] = "threequarters"; d[0x00BF] = "questiondown"; - d[0x00C0] = "Agrave"; d[0x00C1] = "Aacute"; - d[0x00C2] = "Acircumflex"; d[0x00C3] = "Atilde"; - d[0x00C4] = "Adieresis"; d[0x00C5] = "Aring"; - d[0x00C6] = "AE"; d[0x00C7] = "Ccedilla"; - d[0x00C8] = "Egrave"; d[0x00C9] = "Eacute"; - d[0x00CA] = "Ecircumflex"; d[0x00CB] = "Edieresis"; - d[0x00CC] = "Igrave"; d[0x00CD] = "Iacute"; - d[0x00CE] = "Icircumflex"; d[0x00CF] = "Idieresis"; - d[0x00D0] = "Eth"; d[0x00D1] = "Ntilde"; - d[0x00D2] = "Ograve"; d[0x00D3] = "Oacute"; - d[0x00D4] = "Ocircumflex"; d[0x00D5] = "Otilde"; - d[0x00D6] = "Odieresis"; d[0x00D7] = "multiply"; - d[0x00D8] = "Oslash"; d[0x00D9] = "Ugrave"; - d[0x00DA] = "Uacute"; d[0x00DB] = "Ucircumflex"; - d[0x00DC] = "Udieresis"; d[0x00DD] = "Yacute"; - d[0x00DE] = "Thorn"; d[0x00DF] = "germandbls"; - d[0x00E0] = "agrave"; d[0x00E1] = "aacute"; - d[0x00E2] = "acircumflex"; d[0x00E3] = "atilde"; - d[0x00E4] = "adieresis"; d[0x00E5] = "aring"; - d[0x00E6] = "ae"; d[0x00E7] = "ccedilla"; - d[0x00E8] = "egrave"; d[0x00E9] = "eacute"; - d[0x00EA] = "ecircumflex"; d[0x00EB] = "edieresis"; - d[0x00EC] = "igrave"; d[0x00ED] = "iacute"; - d[0x00EE] = "icircumflex"; d[0x00EF] = "idieresis"; - d[0x00F0] = "eth"; d[0x00F1] = "ntilde"; - d[0x00F2] = "ograve"; d[0x00F3] = "oacute"; - d[0x00F4] = "ocircumflex"; d[0x00F5] = "otilde"; - d[0x00F6] = "odieresis"; d[0x00F7] = "divide"; - d[0x00F8] = "oslash"; d[0x00F9] = "ugrave"; - d[0x00FA] = "uacute"; d[0x00FB] = "ucircumflex"; - d[0x00FC] = "udieresis"; d[0x00FD] = "yacute"; - d[0x00FE] = "thorn"; d[0x00FF] = "ydieresis"; - - // Selected Latin Extended-A / special typographic chars - d[0x0131] = "dotlessi"; d[0x0141] = "Lslash"; d[0x0142] = "lslash"; - d[0x0152] = "OE"; d[0x0153] = "oe"; d[0x0160] = "Scaron"; - d[0x0161] = "scaron"; d[0x0178] = "Ydieresis"; d[0x017D] = "Zcaron"; - d[0x017E] = "zcaron"; d[0x0192] = "florin"; - - // Punctuation / typographic - d[0x2013] = "endash"; d[0x2014] = "emdash"; - d[0x2018] = "quoteleft"; d[0x2019] = "quoteright"; - d[0x201A] = "quotesinglbase"; - d[0x201C] = "quotedblleft"; d[0x201D] = "quotedblright"; - d[0x201E] = "quotedblbase"; - d[0x2020] = "dagger"; d[0x2021] = "daggerdbl"; - d[0x2022] = "bullet"; d[0x2026] = "ellipsis"; - d[0x2030] = "perthousand"; - d[0x2039] = "guilsinglleft"; d[0x203A] = "guilsinglright"; - d[0x2044] = "fraction"; - d[0x20AC] = "Euro"; d[0x2122] = "trademark"; - d[0x2202] = "partialdiff"; - d[0x2206] = "Delta"; d[0x220F] = "product"; - d[0x2211] = "summation"; d[0x2212] = "minus"; - d[0x221A] = "radical"; d[0x221E] = "infinity"; - d[0x222B] = "integral"; d[0x2248] = "approxequal"; - d[0x2260] = "notequal"; d[0x2264] = "lessequal"; - d[0x2265] = "greaterequal"; d[0x25CA] = "lozenge"; - d[0xFB01] = "fi"; d[0xFB02] = "fl"; - - return d; - } - } -} diff --git a/src/MiniPdf/Drawing/Font/Type1/Type1Parser.cs b/src/MiniPdf/Drawing/Font/Type1/Type1Parser.cs deleted file mode 100644 index 2fee4bd4..00000000 --- a/src/MiniPdf/Drawing/Font/Type1/Type1Parser.cs +++ /dev/null @@ -1,878 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using SysEncoding = System.Text.Encoding; - -namespace MiniSoftware.Drawing.Font.Type1 -{ - /// - /// Reads PFB (binary) or PFA (ASCII-hex) Type 1 font files and returns - /// a containing all metadata, charstrings, and subrs. - /// - public static class Type1Parser - { - // ── Cipher constants ────────────────────────────────────────────────── - - private const ushort EexecKey = 55665; - private const ushort CharstringKey = 4330; - private const uint CipherC1 = 52845; - private const uint CipherC2 = 22719; - - // ── Public entry point ──────────────────────────────────────────────── - - /// - /// Parses a PFB or PFA byte array into a instance. - /// - internal static Type1Data Parse(byte[] data) - { - if (data is null) throw new ArgumentNullException(nameof(data)); - - return (data.Length >= 2 && data[0] == 0x80) - ? ParsePfb(data) - : ParsePfa(EncodingLatin1.GetString(data)); - } - - // ── Latin-1 encoding helper ─────────────────────────────────────────── - - private static readonly SysEncoding EncodingLatin1 = SysEncoding.GetEncoding(28591); - - // ── PFB reader ──────────────────────────────────────────────────────── - - private static Type1Data ParsePfb(byte[] data) - { - var result = new Type1Data(); - var asciiAccum = new System.Text.StringBuilder(); - var eexecAccum = new System.Collections.Generic.List(); - bool seenEexec = false; - int pos = 0; - - while (pos < data.Length) - { - // ── PFB segment? ────────────────────────────────────────────── - // Handle EOF marker (only 2 bytes) before the 6-byte check. - if (pos + 2 <= data.Length && data[pos] == 0x80 && data[pos + 1] == 0x03) - break; // PFB EOF marker - - if (pos + 6 <= data.Length && data[pos] == 0x80) - { - byte type = data[pos + 1]; - - int segLen = data[pos + 2] - | (data[pos + 3] << 8) - | (data[pos + 4] << 16) - | (data[pos + 5] << 24); - pos += 6; - if (pos + segLen > data.Length) segLen = data.Length - pos; - - if (type == 0x01) - { - // ASCII segment: accumulate, but check for "eexec" token. - string asciiSeg = EncodingLatin1.GetString(data, pos, segLen); - if (!seenEexec) - { - int eexecInSeg = asciiSeg.IndexOf("eexec", StringComparison.Ordinal); - if (eexecInSeg >= 0) - { - // Accumulate ASCII up to (not including) "eexec". - asciiAccum.Append(asciiSeg.Substring(0, eexecInSeg)); - seenEexec = true; - // Any bytes after "eexec\n" within this ASCII segment - // (uncommon in PFB) would be in-line eexec data. - int afterEexec = eexecInSeg + 5; - if (afterEexec < asciiSeg.Length - && (asciiSeg[afterEexec] == '\n' || asciiSeg[afterEexec] == '\r' - || asciiSeg[afterEexec] == ' ')) - afterEexec++; - if (afterEexec < asciiSeg.Length) - { - byte[] trailing = EncodingLatin1.GetBytes( - asciiSeg.Substring(afterEexec)); - eexecAccum.Add(trailing); - } - } - else - { - asciiAccum.Append(asciiSeg); - } - } - // (If seenEexec and type=1: additional cleartext segments after - // the eexec block — rare but possible; ignore for now.) - } - else if (type == 0x02 && seenEexec) - { - var chunk = new byte[segLen]; - Array.Copy(data, pos, chunk, 0, segLen); - eexecAccum.Add(chunk); - } - pos += segLen; - continue; - } - - // ── Raw (non-segmented) bytes ───────────────────────────────── - if (!seenEexec) - { - // Scan for "eexec" keyword; everything before is ASCII. - byte[] needle = EncodingLatin1.GetBytes("eexec"); - int eexecByte = IndexOfBytes(data, needle, pos); - - if (eexecByte >= 0) - { - asciiAccum.Append(EncodingLatin1.GetString(data, pos, eexecByte - pos)); - seenEexec = true; - - // Advance past "eexec" + optional single whitespace - pos = eexecByte + 5; - if (pos < data.Length - && (data[pos] == '\n' || data[pos] == '\r' - || data[pos] == ' ' || data[pos] == '\t')) - pos++; - - // If PFB binary segment follows, let the loop handle it. - if (pos + 2 <= data.Length - && data[pos] == 0x80 && data[pos + 1] == 0x02) - continue; - - // Raw binary eexec data (no further PFB wrapping) - if (pos < data.Length) - { - var chunk = new byte[data.Length - pos]; - Array.Copy(data, pos, chunk, 0, chunk.Length); - eexecAccum.Add(chunk); - } - break; - } - else - { - // No "eexec" in remaining bytes — all ASCII - asciiAccum.Append(EncodingLatin1.GetString(data, pos, data.Length - pos)); - break; - } - } - else - { - // We've already seen eexec but hit raw non-segmented bytes. - // Treat them as raw binary eexec continuation. - var chunk = new byte[data.Length - pos]; - Array.Copy(data, pos, chunk, 0, chunk.Length); - eexecAccum.Add(chunk); - break; - } - } - - if (asciiAccum.Length > 0) ParseAsciiSection(asciiAccum.ToString(), result); - - if (eexecAccum.Count > 0) - { - // Concatenate all binary chunks into one eexec byte array - int total = 0; - foreach (var c in eexecAccum) total += c.Length; - var eexecBytes = new byte[total]; - int off = 0; - foreach (var c in eexecAccum) { Array.Copy(c, 0, eexecBytes, off, c.Length); off += c.Length; } - ApplyEexecSection(eexecBytes, result); - } - - return result; - } - - // Byte-level search helper - private static int IndexOfBytes(byte[] haystack, byte[] needle, int startPos) - { - int limit = haystack.Length - needle.Length; - for (int i = startPos; i <= limit; i++) - { - bool match = true; - for (int j = 0; j < needle.Length; j++) - if (haystack[i + j] != needle[j]) { match = false; break; } - if (match) return i; - } - return -1; - } - - // ── PFA reader ──────────────────────────────────────────────────────── - - private static Type1Data ParsePfa(string text) - { - var result = new Type1Data(); - - int eexecIdx = text.IndexOf("eexec", StringComparison.Ordinal); - if (eexecIdx < 0) - { - ParseAsciiSection(text, result); - return result; - } - - ParseAsciiSection(text.Substring(0, eexecIdx), result); - - // Skip "eexec" + one whitespace character - int hexStart = eexecIdx + 5; - if (hexStart < text.Length && - (text[hexStart] == '\n' || text[hexStart] == '\r' || text[hexStart] == ' ')) - hexStart++; - - byte[] eexecBytes = DecodeHexString(text.Substring(hexStart)); - ApplyEexecSection(eexecBytes, result); - - return result; - } - - // ── eexec section wrapper ───────────────────────────────────────────── - - private static void ApplyEexecSection(byte[] eexecBytes, Type1Data data) - { - byte[] decrypted = EexecDecrypt(eexecBytes); - ParseEexecSectionBytes(decrypted, data); - } - - // ── ASCII section parser ────────────────────────────────────────────── - - private static void ParseAsciiSection(string text, Type1Data data) - { - var tokens = Tokenize(text); - - for (int i = 0; i < tokens.Count; i++) - { - string tok = tokens[i]; - - // /FontName /Courier def - if (tok == "/FontName" && i + 1 < tokens.Count) - { - string next = tokens[i + 1]; - if (next.StartsWith("/", StringComparison.Ordinal)) - data.FontName = next.Substring(1); - i++; - continue; - } - - // /FontBBox {x0 y0 x1 y1} def - if (tok == "/FontBBox" && i + 1 < tokens.Count) - { - data.FontBBox = ParseNumericBlock(tokens[i + 1]); - i++; - continue; - } - - // /Encoding StandardEncoding|ISOLatin1Encoding| - if (tok == "/Encoding" && i + 1 < tokens.Count) - { - if (tokens[i + 1] == "StandardEncoding") - { - data.Encoding = GetStandardEncoding(); - i++; - } - else if (tokens[i + 1] == "ISOLatin1Encoding") - { - data.Encoding = GetIsoLatin1Encoding(); - i++; - } - // Custom encodings are handled below via "dup N /name put" pattern - continue; - } - } - - // Parse custom encoding: dup / put - for (int i = 0; i + 3 < tokens.Count; i++) - { - if (tokens[i] == "dup" - && int.TryParse(tokens[i + 1], NumberStyles.Integer, - CultureInfo.InvariantCulture, out int slot) - && slot >= 0 && slot < 256 - && tokens[i + 2].StartsWith("/", StringComparison.Ordinal) - && tokens[i + 3] == "put") - { - data.Encoding[slot] = tokens[i + 2].Substring(1); - i += 3; - } - } - } - - // ── eexec section parser (byte-level, handles both binary RD and hex PFA) ── - - internal static void ParseEexecSectionBytes(byte[] decrypted, Type1Data data) - { - int pos = 0; - var order = new List(); - - while (pos < decrypted.Length) - { - string tok = ReadByteToken(decrypted, ref pos); - if (tok.Length == 0) break; - - // /lenIV N def - if (tok == "/lenIV") - { - string num = ReadByteToken(decrypted, ref pos); - if (int.TryParse(num, NumberStyles.Integer, - CultureInfo.InvariantCulture, out int lv)) - data.LenIV = lv; - continue; - } - - // /Subrs N array dup 0 M RD … NP … def - if (tok == "/Subrs") - { - string countTok = ReadByteToken(decrypted, ref pos); - if (!int.TryParse(countTok, NumberStyles.Integer, - CultureInfo.InvariantCulture, out int count)) - continue; - var subrs = new byte[count][]; - ReadByteToken(decrypted, ref pos); // consume "array" - - while (pos < decrypted.Length) - { - int savedPos = pos; - string t = ReadByteToken(decrypted, ref pos); - if (t.Length == 0 || t == "def" || t == "readonly" - || t == "end" || t == "noaccess") break; - // A name literal (starts with '/') means we've left the Subrs - // section — rewind so the main loop can pick it up. - if (t.StartsWith("/", StringComparison.Ordinal)) { pos = savedPos; break; } - if (t != "dup") continue; - - string idxTok = ReadByteToken(decrypted, ref pos); - if (!int.TryParse(idxTok, NumberStyles.Integer, - CultureInfo.InvariantCulture, out int idx) - || idx < 0 || idx >= count) - continue; - - byte[] raw = ReadCharsBytes(decrypted, ref pos); - if (raw.Length > 0) - subrs[idx] = DecryptCharstring(raw, data.LenIV); - } - data.Subrs = subrs; - continue; - } - - // /CharStrings N dict begin … end - if (tok == "/CharStrings") - { - // Skip preamble tokens (N, "dict", "begin", etc.) until first /name - while (pos < decrypted.Length) - { - string t = ReadByteToken(decrypted, ref pos); - if (t.Length == 0 || t == "end" || t == "readonly" - || t == "currentdict") goto doneCharStrings; - if (!t.StartsWith("/", StringComparison.Ordinal)) continue; - - // Process first glyph - string nm = t.Substring(1); - byte[] raw = ReadCharsBytes(decrypted, ref pos); - if (!data.CharStrings.ContainsKey(nm)) - { data.CharStrings[nm] = DecryptCharstring(raw, data.LenIV); order.Add(nm); } - break; - } - - // Process remaining glyphs - while (pos < decrypted.Length) - { - string t = ReadByteToken(decrypted, ref pos); - if (t.Length == 0 || t == "end" || t == "readonly" - || t == "currentdict") break; - if (!t.StartsWith("/", StringComparison.Ordinal)) continue; - - string name = t.Substring(1); - byte[] raw = ReadCharsBytes(decrypted, ref pos); - if (!data.CharStrings.ContainsKey(name)) - { data.CharStrings[name] = DecryptCharstring(raw, data.LenIV); order.Add(name); } - } - doneCharStrings: - data.GlyphOrder = order.ToArray(); - break; // found CharStrings — done with main loop - } - } - - if (data.GlyphOrder.Length == 0 && data.CharStrings.Count > 0) - { - data.GlyphOrder = new string[data.CharStrings.Count]; - int j = 0; - foreach (string k in data.CharStrings.Keys) data.GlyphOrder[j++] = k; - } - } - - // Read one charstring's raw (inner-encrypted) bytes. - // Handles: hex → - // binary → N RD (RD variants: "RD", "-|") - // ND terminators: "ND", "--", "|-", "NP", "|" - internal static byte[] ReadCharsBytes(byte[] data, ref int pos) - { - string tok1 = ReadByteToken(data, ref pos); - - // Hex format (PFA-style after eexec-decrypt): - if (tok1.StartsWith("<", StringComparison.Ordinal) - && tok1.EndsWith(">", StringComparison.Ordinal)) - return ParseHexToken(tok1); - - // Binary format: N RD - // RD operators: "RD" or "-|" (dash-pipe) - if (int.TryParse(tok1, NumberStyles.Integer, - CultureInfo.InvariantCulture, out int blen) && blen > 0) - { - string rdTok = ReadByteToken(data, ref pos); // "RD", "-|" - if ((rdTok == "RD" || rdTok == "-|")) - { - // After the RD operator there is exactly one mandatory separator byte - // (space or newline) before the binary charstring bytes. Skip it. - if (pos < data.Length - && (data[pos] == ' ' || data[pos] == '\t' - || data[pos] == '\r' || data[pos] == '\n')) - pos++; - - if (pos + blen > data.Length) return Array.Empty(); - - var raw = new byte[blen]; - Array.Copy(data, pos, raw, 0, blen); - pos += blen; - // Skip optional whitespace before the ND terminator - while (pos < data.Length - && (data[pos] == ' ' || data[pos] == '\t' - || data[pos] == '\r' || data[pos] == '\n')) - pos++; - // Detect ND at raw-byte level so that pipe-based NDs - // immediately followed by the next token (e.g. "|dup", "||dup", - // "|-/name") are consumed without folding the next token. - if (pos < data.Length && data[pos] == '|') - { - pos++; // consume leading '|' - if (pos < data.Length - && (data[pos] == '|' || data[pos] == '-')) - pos++; // consume second char of "||" or "|-" - } - else if (pos + 1 < data.Length - && data[pos] == '-' && data[pos + 1] == '-') - { - pos += 2; // consume "--" - } - else - { - int ndPos = pos; - string nd = ReadByteToken(data, ref ndPos); - if (nd == "ND" || nd == "NP" || nd == "noaccess") - pos = ndPos; - } - return raw; - } - } - - return Array.Empty(); - } - - // Byte-level PostScript token reader (skips whitespace and comments). - internal static string ReadByteToken(byte[] data, ref int pos) - { - // Skip whitespace and comments - while (pos < data.Length) - { - byte b = data[pos]; - if (b == ' ' || b == '\t' || b == '\r' || b == '\n' || b == '\f' || b == 0) - { pos++; continue; } - if (b == '%') - { while (pos < data.Length && data[pos] != '\n' && data[pos] != '\r') pos++; continue; } - break; - } - if (pos >= data.Length) return string.Empty; - - byte c = data[pos]; - - // Proc body { } - if (c == '{') - { - int depth = 1, start = pos++; - while (pos < data.Length && depth > 0) - { - if (data[pos] == '{') depth++; - else if (data[pos] == '}') depth--; - pos++; - } - return EncodingLatin1.GetString(data, start, pos - start); - } - - // Array [ ] - if (c == '[') - { - int depth = 1, start = pos++; - while (pos < data.Length && depth > 0) - { - if (data[pos] == '[') depth++; - else if (data[pos] == ']') depth--; - pos++; - } - return EncodingLatin1.GetString(data, start, pos - start); - } - - // Dict << >> - if (c == '<' && pos + 1 < data.Length && data[pos + 1] == '<') - { pos += 2; return "<<"; } - if (c == '>' && pos + 1 < data.Length && data[pos + 1] == '>') - { pos += 2; return ">>"; } - - // Hex string <…> - if (c == '<') - { - int start = ++pos; - while (pos < data.Length && data[pos] != '>') pos++; - string hex = EncodingLatin1.GetString(data, start, pos - start); - if (pos < data.Length) pos++; - return "<" + hex + ">"; - } - - // PS string (…) - if (c == '(') - { - int depth = 1, start = pos++; - while (pos < data.Length && depth > 0) - { - if (data[pos] == '\\') { pos += 2; continue; } - if (data[pos] == '(') depth++; - else if (data[pos] == ')') depth--; - pos++; - } - return EncodingLatin1.GetString(data, start, pos - start); - } - - // Single-char delimiters not part of above - if (c == ')' || c == ']' || c == '}' || c == '>') - { pos++; return EncodingLatin1.GetString(data, pos - 1, 1); } - - // Name (starts with /) or keyword/number - { - int start = pos; - if (c == '/') pos++; // include leading '/' - while (pos < data.Length && !IsByteTokDelim(data[pos])) pos++; - return pos > start - ? EncodingLatin1.GetString(data, start, pos - start) - : string.Empty; - } - } - - internal static bool IsByteTokDelim(byte b) - => b == ' ' || b == '\t' || b == '\r' || b == '\n' || b == '\f' || b == 0 - || b == '(' || b == ')' || b == '<' || b == '>' - || b == '[' || b == ']' || b == '{' || b == '}' - || b == '/' || b == '%'; - - // ── eexec decryption ────────────────────────────────────────────────── - - internal static byte[] EexecDecrypt(byte[] data) - { - if (data.Length <= 4) return Array.Empty(); - - ushort r = EexecKey; - - // Prime the cipher with the first 4 bytes (discarded plaintext) - for (int i = 0; i < 4; i++) - r = Step(r, data[i]); - - var result = new byte[data.Length - 4]; - for (int i = 0; i < result.Length; i++) - { - byte c = data[i + 4]; - result[i] = (byte)(c ^ (r >> 8)); - r = Step(r, c); - } - return result; - } - - // ── Charstring decryption ───────────────────────────────────────────── - - internal static byte[] DecryptCharstring(byte[] data, int lenIV) - { - if (lenIV <= 0) return data; - if (data.Length <= lenIV) return Array.Empty(); - - ushort r = CharstringKey; - - for (int i = 0; i < lenIV; i++) - r = Step(r, data[i]); - - var result = new byte[data.Length - lenIV]; - for (int i = 0; i < result.Length; i++) - { - byte c = data[i + lenIV]; - result[i] = (byte)(c ^ (r >> 8)); - r = Step(r, c); - } - return result; - } - - // ── Cipher step ─────────────────────────────────────────────────────── - - private static ushort Step(ushort r, byte c) - => (ushort)((c + r) * CipherC1 + CipherC2); - - // ── PFA hex decoder ─────────────────────────────────────────────────── - - private static byte[] DecodeHexString(string hex) - { - // Strip whitespace and count valid hex chars - var clean = new System.Text.StringBuilder(hex.Length); - foreach (char c in hex) - { - if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) - clean.Append(c); - } - - string s = clean.ToString(); - int count = s.Length / 2; - var bytes = new byte[count]; - for (int i = 0; i < count; i++) - bytes[i] = Convert.ToByte(s.Substring(i * 2, 2), 16); - return bytes; - } - - // ── Tokenizer ───────────────────────────────────────────────────────── - - internal static List Tokenize(string text) - { - var tokens = new List(); - int i = 0, n = text.Length; - - while (i < n) - { - char c = text[i]; - - // Whitespace - if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\0') - { i++; continue; } - - // Comment - if (c == '%') - { while (i < n && text[i] != '\n') i++; continue; } - - // Dictionary << >> - if (c == '<' && i + 1 < n && text[i + 1] == '<') - { tokens.Add("<<"); i += 2; continue; } - if (c == '>' && i + 1 < n && text[i + 1] == '>') - { tokens.Add(">>"); i += 2; continue; } - - // Hex string - if (c == '<') - { - int start = ++i; - while (i < n && text[i] != '>') i++; - tokens.Add("<" + text.Substring(start, i - start) + ">"); - if (i < n) i++; - continue; - } - - // Procedure { } - if (c == '{') - { - int depth = 1, start = i++; - while (i < n && depth > 0) - { - if (text[i] == '{') depth++; - else if (text[i] == '}') depth--; - i++; - } - tokens.Add(text.Substring(start, i - start)); - continue; - } - - // Array [ ] - if (c == '[') - { - int depth = 1, start = i++; - while (i < n && depth > 0) - { - if (text[i] == '[') depth++; - else if (text[i] == ']') depth--; - i++; - } - tokens.Add(text.Substring(start, i - start)); - continue; - } - - // PS string ( ) - if (c == '(') - { - int depth = 1, start = i++; - while (i < n && depth > 0) - { - if (text[i] == '\\') { i += 2; continue; } - if (text[i] == '(') depth++; - else if (text[i] == ')') depth--; - i++; - } - tokens.Add(text.Substring(start, i - start)); - continue; - } - - // Delimiter chars not already handled - if (c == ')' || c == ']' || c == '}' || c == '>') - { tokens.Add(c.ToString()); i++; continue; } - - // Name/keyword/number: read until a delimiter - { - int start = i; - if (c == '/') i++; // consume '/' as part of the literal name - while (i < n && !IsTokDelim(text[i])) i++; - if (i > start) tokens.Add(text.Substring(start, i - start)); - else i++; - } - } - - return tokens; - } - - private static bool IsTokDelim(char c) - => c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\0' - || c == '(' || c == ')' || c == '<' || c == '>' - || c == '[' || c == ']' || c == '{' || c == '}' - || c == '/' || c == '%'; - - private static bool IsSkipKeyword(string t) - => t == "executeonly" || t == "put" || t == "def" - || t == "noaccess" || t == "readonly" || t == "bind" - || t == "ND" || t == "|-" || t == "--" - || t == "NP" || t == "RD"; - - // ── Numeric block parser ────────────────────────────────────────────── - - private static double[] ParseNumericBlock(string token) - { - string inner = token.Trim('{', '}', '[', ']'); - string[] parts = inner.Split(new[] { ' ', '\t', '\r', '\n' }, - StringSplitOptions.RemoveEmptyEntries); - var nums = new double[parts.Length]; - for (int i = 0; i < parts.Length; i++) - double.TryParse(parts[i], NumberStyles.Float, - CultureInfo.InvariantCulture, out nums[i]); - return nums; - } - - // ── Hex token decoder ───────────────────────────────────────────────── - - private static byte[] ParseHexToken(string token) - { - // Strip surrounding < > - int start = token.StartsWith("<", StringComparison.Ordinal) ? 1 : 0; - int end = token.EndsWith(">", StringComparison.Ordinal) ? token.Length - 1 : token.Length; - - var sb = new System.Text.StringBuilder(end - start); - for (int i = start; i < end; i++) - { - char c = token[i]; - if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) - sb.Append(c); - } - - string hex = sb.ToString(); - if (hex.Length % 2 != 0) hex += "0"; - - var bytes = new byte[hex.Length / 2]; - for (int i = 0; i < bytes.Length; i++) - bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); - return bytes; - } - - // ── Standard Encoding ───────────────────────────────────────────────── - - /// - /// Returns the 256-entry PostScript Standard Encoding array. - /// Each element is a glyph name; unmapped slots contain ".notdef". - /// - public static string[] GetStandardEncoding() - { - var enc = new string[256]; - for (int i = 0; i < 256; i++) enc[i] = ".notdef"; - - enc[32] = "space"; enc[33] = "exclam"; enc[34] = "quotedbl"; - enc[35] = "numbersign"; enc[36] = "dollar"; enc[37] = "percent"; - enc[38] = "ampersand"; enc[39] = "quoteright"; enc[40] = "parenleft"; - enc[41] = "parenright"; enc[42] = "asterisk"; enc[43] = "plus"; - enc[44] = "comma"; enc[45] = "hyphen"; enc[46] = "period"; - enc[47] = "slash"; - enc[48] = "zero"; enc[49] = "one"; enc[50] = "two"; enc[51] = "three"; - enc[52] = "four"; enc[53] = "five"; enc[54] = "six"; enc[55] = "seven"; - enc[56] = "eight"; enc[57] = "nine"; - enc[58] = "colon"; enc[59] = "semicolon"; enc[60] = "less"; - enc[61] = "equal"; enc[62] = "greater"; enc[63] = "question"; - enc[64] = "at"; - - // A–Z: standard glyph names match the character itself - for (int i = 0; i < 26; i++) enc[65 + i] = ((char)('A' + i)).ToString(); - - enc[91] = "bracketleft"; enc[92] = "backslash"; enc[93] = "bracketright"; - enc[94] = "asciicircum"; enc[95] = "underscore"; enc[96] = "quoteleft"; - - // a–z - for (int i = 0; i < 26; i++) enc[97 + i] = ((char)('a' + i)).ToString(); - - enc[123] = "braceleft"; enc[124] = "bar"; enc[125] = "braceright"; - enc[126] = "asciitilde"; - - enc[161] = "exclamdown"; enc[162] = "cent"; enc[163] = "sterling"; - enc[164] = "fraction"; enc[165] = "yen"; enc[166] = "florin"; - enc[167] = "section"; enc[168] = "currency"; enc[169] = "quotesingle"; - enc[170] = "quotedblleft"; enc[171] = "guillemotleft"; - enc[172] = "guilsinglleft"; enc[173] = "guilsinglright"; - enc[174] = "fi"; enc[175] = "fl"; - enc[177] = "endash"; enc[178] = "dagger"; enc[179] = "daggerdbl"; - enc[180] = "periodcentered"; enc[182] = "paragraph"; enc[183] = "bullet"; - enc[184] = "quotesinglbase"; enc[185] = "quotedblbase"; - enc[186] = "quotedblright"; enc[187] = "guillemotright"; - enc[188] = "ellipsis"; enc[189] = "perthousand"; - enc[191] = "questiondown"; - enc[193] = "grave"; enc[194] = "acute"; enc[195] = "circumflex"; - enc[196] = "tilde"; enc[197] = "macron"; enc[198] = "breve"; - enc[199] = "dotaccent"; enc[200] = "dieresis"; enc[202] = "ring"; - enc[203] = "cedilla"; enc[205] = "hungarumlaut"; enc[206] = "ogonek"; - enc[207] = "caron"; enc[208] = "emdash"; - enc[225] = "AE"; enc[227] = "ordfeminine"; - enc[232] = "Lslash"; enc[233] = "Oslash"; enc[234] = "OE"; - enc[235] = "ordmasculine"; enc[241] = "ae"; enc[243] = "dotlessi"; - enc[246] = "lslash"; enc[247] = "oslash"; enc[248] = "oe"; - enc[249] = "germandbls"; - return enc; - } - - // ── ISO Latin-1 Encoding ────────────────────────────────────────────── - - private static string[] GetIsoLatin1Encoding() - { - var enc = new string[256]; - for (int i = 0; i < 256; i++) enc[i] = ".notdef"; - - // Copy ASCII range from Standard Encoding - string[] std = GetStandardEncoding(); - for (int i = 32; i < 128; i++) enc[i] = std[i]; - - // Latin-1 supplement (0xA0–0xFF) - enc[160] = "space"; enc[161] = "exclamdown"; enc[162] = "cent"; - enc[163] = "sterling"; enc[164] = "currency"; enc[165] = "yen"; - enc[166] = "brokenbar"; enc[167] = "section"; enc[168] = "dieresis"; - enc[169] = "copyright"; enc[170] = "ordfeminine"; enc[171] = "guillemotleft"; - enc[172] = "logicalnot"; enc[173] = "softhyphen"; enc[174] = "registered"; - enc[175] = "macron"; enc[176] = "degree"; enc[177] = "plusminus"; - enc[178] = "twosuperior"; enc[179] = "threesuperior"; enc[180] = "acute"; - enc[181] = "mu"; enc[182] = "paragraph"; enc[183] = "periodcentered"; - enc[184] = "cedilla"; enc[185] = "onesuperior"; enc[186] = "ordmasculine"; - enc[187] = "guillemotright"; enc[188] = "onequarter"; enc[189] = "onehalf"; - enc[190] = "threequarters"; enc[191] = "questiondown"; - enc[192] = "Agrave"; enc[193] = "Aacute"; enc[194] = "Acircumflex"; - enc[195] = "Atilde"; enc[196] = "Adieresis"; enc[197] = "Aring"; - enc[198] = "AE"; enc[199] = "Ccedilla"; enc[200] = "Egrave"; - enc[201] = "Eacute"; enc[202] = "Ecircumflex"; enc[203] = "Edieresis"; - enc[204] = "Igrave"; enc[205] = "Iacute"; enc[206] = "Icircumflex"; - enc[207] = "Idieresis"; enc[208] = "Eth"; enc[209] = "Ntilde"; - enc[210] = "Ograve"; enc[211] = "Oacute"; enc[212] = "Ocircumflex"; - enc[213] = "Otilde"; enc[214] = "Odieresis"; enc[215] = "multiply"; - enc[216] = "Oslash"; enc[217] = "Ugrave"; enc[218] = "Uacute"; - enc[219] = "Ucircumflex"; enc[220] = "Udieresis"; enc[221] = "Yacute"; - enc[222] = "Thorn"; enc[223] = "germandbls"; - enc[224] = "agrave"; enc[225] = "aacute"; enc[226] = "acircumflex"; - enc[227] = "atilde"; enc[228] = "adieresis"; enc[229] = "aring"; - enc[230] = "ae"; enc[231] = "ccedilla"; enc[232] = "egrave"; - enc[233] = "eacute"; enc[234] = "ecircumflex"; enc[235] = "edieresis"; - enc[236] = "igrave"; enc[237] = "iacute"; enc[238] = "icircumflex"; - enc[239] = "idieresis"; enc[240] = "eth"; enc[241] = "ntilde"; - enc[242] = "ograve"; enc[243] = "oacute"; enc[244] = "ocircumflex"; - enc[245] = "otilde"; enc[246] = "odieresis"; enc[247] = "divide"; - enc[248] = "oslash"; enc[249] = "ugrave"; enc[250] = "uacute"; - enc[251] = "ucircumflex"; enc[252] = "udieresis"; enc[253] = "yacute"; - enc[254] = "thorn"; enc[255] = "ydieresis"; - return enc; - } - } -} diff --git a/src/MiniPdf/Drawing/Geometry/Point.cs b/src/MiniPdf/Drawing/Geometry/Point.cs deleted file mode 100644 index 8bc33861..00000000 --- a/src/MiniPdf/Drawing/Geometry/Point.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// Represents an ordered pair of integer x- and y-coordinates. - /// - /// A represents a location in a two-dimensional coordinate system. - /// X and Y are public fields for performance reasons, matching the System.Drawing API. - /// - public struct Point : IEquatable - { - /// - /// Gets or sets the x-coordinate. - /// - public int X; - - /// - /// Gets or sets the y-coordinate. - /// - public int Y; - - /// - /// Initializes a new with the specified coordinates. - /// - /// The x-coordinate. - /// The y-coordinate. - public Point(int x, int y) { X = x; Y = y; } - - /// - /// Initializes a new from a . - /// - /// The size to convert to a point. - public Point(Size sz) { X = sz.Width; Y = sz.Height; } - - /// - /// Gets an empty (0, 0). - /// - public static readonly Point Empty = default; - - /// - /// Gets a value indicating whether this point is empty (0, 0). - /// - public bool IsEmpty => X == 0 && Y == 0; - - /// - /// Translates the point by the specified offsets. - /// - /// The horizontal offset. - /// The vertical offset. - public void Offset(int dx, int dy) { X += dx; Y += dy; } - - /// - /// Translates the point by the offsets of another point. - /// - /// The point containing the offsets. - public void Offset(Point p) { X += p.X; Y += p.Y; } - - /// - /// Adds the specified point and size. - /// - /// The point to add to. - /// The size to add. - /// The resulting point. - public static Point Add(Point pt, Size sz) => new Point(pt.X + sz.Width, pt.Y + sz.Height); - - /// - /// Subtracts the specified size from the point. - /// - /// The point to subtract from. - /// The size to subtract. - /// The resulting point. - public static Point Subtract(Point pt, Size sz) => new Point(pt.X - sz.Width, pt.Y - sz.Height); - - /// - /// Adds a point and a size. - /// - public static Point operator +(Point pt, Size sz) => Add(pt, sz); - - /// - /// Subtracts a size from a point. - /// - public static Point operator -(Point pt, Size sz) => Subtract(pt, sz); - - /// - /// Implicitly converts a to a . - /// - public static implicit operator PointF(Point p) => new PointF(p.X, p.Y); - - /// - /// Explicitly converts a to a . - /// - public static explicit operator Size(Point p) => new Size(p.X, p.Y); - - /// - /// Compares two points for equality. - /// - public static bool operator ==(Point left, Point right) => left.X == right.X && left.Y == right.Y; - - /// - /// Compares two points for inequality. - /// - public static bool operator !=(Point left, Point right) => !(left == right); - - /// - /// Indicates whether this point is equal to another point. - /// - /// The point to compare. - /// true if the points are equal; otherwise, false. - public bool Equals(Point other) => this == other; - - /// - /// Indicates whether this point is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is Point p && this == p; - - /// - /// Returns a hash code for this point. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked { return X * 397 ^ Y; } - } - - /// - /// Returns a string representation of this point. - /// - /// A string in the format "{X=value, Y=value}". - public override string ToString() => $"{{X={X}, Y={Y}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Geometry/PointF.cs b/src/MiniPdf/Drawing/Geometry/PointF.cs deleted file mode 100644 index 773a16c7..00000000 --- a/src/MiniPdf/Drawing/Geometry/PointF.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// Represents an ordered pair of floating-point x- and y-coordinates. - /// - /// A represents a location in a two-dimensional coordinate system. - /// X and Y are public fields for performance reasons, matching the System.Drawing API. - /// - public struct PointF : IEquatable - { - /// - /// Gets or sets the x-coordinate. - /// - public float X; - - /// - /// Gets or sets the y-coordinate. - /// - public float Y; - - /// - /// Initializes a new with the specified coordinates. - /// - /// The x-coordinate. - /// The y-coordinate. - public PointF(float x, float y) { X = x; Y = y; } - - /// - /// Gets an empty (0, 0). - /// - public static readonly PointF Empty = default; - - /// - /// Gets a value indicating whether this point is empty (0, 0). - /// - public bool IsEmpty => X == 0f && Y == 0f; - - /// - /// Translates the point by the specified offsets. - /// - /// The horizontal offset. - /// The vertical offset. - public void Offset(float dx, float dy) { X += dx; Y += dy; } - - /// - /// Translates the point by the offsets of another point. - /// - /// The point containing the offsets. - public void Offset(PointF p) { X += p.X; Y += p.Y; } - - /// - /// Adds the specified point and size. - /// - /// The point to add to. - /// The size to add. - /// The resulting point. - public static PointF Add(PointF pt, SizeF sz) => new PointF(pt.X + sz.Width, pt.Y + sz.Height); - - /// - /// Subtracts the specified size from the point. - /// - /// The point to subtract from. - /// The size to subtract. - /// The resulting point. - public static PointF Subtract(PointF pt, SizeF sz) => new PointF(pt.X - sz.Width, pt.Y - sz.Height); - - /// - /// Adds a point and a size. - /// - public static PointF operator +(PointF pt, SizeF sz) => Add(pt, sz); - - /// - /// Subtracts a size from a point. - /// - public static PointF operator -(PointF pt, SizeF sz) => Subtract(pt, sz); - - /// - /// Compares two points for equality. - /// - public static bool operator ==(PointF left, PointF right) => left.X == right.X && left.Y == right.Y; - - /// - /// Compares two points for inequality. - /// - public static bool operator !=(PointF left, PointF right) => !(left == right); - - /// - /// Indicates whether this point is equal to another point. - /// - /// The point to compare. - /// true if the points are equal; otherwise, false. - public bool Equals(PointF other) => this == other; - - /// - /// Indicates whether this point is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is PointF p && this == p; - - /// - /// Returns a hash code for this point. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked { return X.GetHashCode() * 397 ^ Y.GetHashCode(); } - } - - /// - /// Returns a string representation of this point. - /// - /// A string in the format "{X=value, Y=value}". - public override string ToString() => $"{{X={X}, Y={Y}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Geometry/PointTransform.cs b/src/MiniPdf/Drawing/Geometry/PointTransform.cs deleted file mode 100644 index 58f09152..00000000 --- a/src/MiniPdf/Drawing/Geometry/PointTransform.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Geometry -{ - /// - /// Internal helpers for applying a to point(s). - /// Used by GraphicsPath, Region, and the rasterizer. - /// - internal static class PointTransform - { - internal static PointF Transform(Matrix matrix, PointF point) - { - var pts = new[] { point }; - matrix.TransformPoints(pts); - return pts[0]; - } - - internal static PointF[] TransformAll(Matrix matrix, PointF[] points) - { - if (points == null || points.Length == 0) return System.Array.Empty(); - var copy = (PointF[])points.Clone(); - matrix.TransformPoints(copy); - return copy; - } - - internal static void TransformInPlace(Matrix matrix, PointF[] points) - { - if (points != null && points.Length > 0) - matrix.TransformPoints(points); - } - } -} diff --git a/src/MiniPdf/Drawing/Geometry/Rectangle.cs b/src/MiniPdf/Drawing/Geometry/Rectangle.cs deleted file mode 100644 index 1ba1b986..00000000 --- a/src/MiniPdf/Drawing/Geometry/Rectangle.cs +++ /dev/null @@ -1,304 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// - /// Represents the location and size of a rectangular region, using integer coordinates. - /// - /// - /// A defines a region with X, Y, Width, and Height. - /// X and Y represent the top-left corner; Width and Height represent the dimensions. - /// - public struct Rectangle : IEquatable - { - /// - /// Gets or sets the x-coordinate of the top-left corner. - /// - public int X; - - /// - /// Gets or sets the y-coordinate of the top-left corner. - /// - public int Y; - - /// - /// Gets or sets the width. - /// - public int Width; - - /// - /// Gets or sets the height. - /// - public int Height; - - /// - /// Initializes a new with the specified location and size. - /// - /// The x-coordinate of the top-left corner. - /// The y-coordinate of the top-left corner. - /// The width. - /// The height. - public Rectangle(int x, int y, int width, int height) - { - X = x; Y = y; Width = width; Height = height; - } - - /// - /// Initializes a new from a point and a size. - /// - /// The top-left corner. - /// The dimensions. - public Rectangle(Point location, Size size) - { - X = location.X; Y = location.Y; Width = size.Width; Height = size.Height; - } - - /// - /// Gets an empty (0, 0, 0, 0). - /// - public static readonly Rectangle Empty = default; - - // ── Derived edges ──────────────────────────────────────────────────────── - - /// - /// Gets the x-coordinate of the left edge. - /// - public int Left => X; - - /// - /// Gets the y-coordinate of the top edge. - /// - public int Top => Y; - - /// - /// Gets the x-coordinate of the right edge. - /// - public int Right => X + Width; - - /// - /// Gets the y-coordinate of the bottom edge. - /// - public int Bottom => Y + Height; - - /// - /// Gets a value indicating whether this rectangle is empty (Width or Height less than or equal to 0). - /// - public bool IsEmpty => Width <= 0 || Height <= 0; - - /// - /// Gets or sets the top-left corner of this rectangle. - /// - public Point Location - { - get => new Point(X, Y); - set { X = value.X; Y = value.Y; } - } - - /// - /// Gets or sets the dimensions of this rectangle. - /// - public Size Size - { - get => new Size(Width, Height); - set { Width = value.Width; Height = value.Height; } - } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Creates a rectangle from left, top, right, and bottom coordinates. - /// - /// The x-coordinate of the left edge. - /// The y-coordinate of the top edge. - /// The x-coordinate of the right edge. - /// The y-coordinate of the bottom edge. - /// A new . - public static Rectangle FromLTRB(int left, int top, int right, int bottom) - => new Rectangle(left, top, right - left, bottom - top); - - // ── Containment / intersection ──────────────────────────────────────────── - - /// - /// Determines whether the specified point is contained within this rectangle. - /// - /// The x-coordinate of the point. - /// The y-coordinate of the point. - /// true if the point is within the rectangle; otherwise, false. - public bool Contains(int x, int y) - => x >= X && x < X + Width && y >= Y && y < Y + Height; - - /// - /// Determines whether the specified point is contained within this rectangle. - /// - /// The point to check. - /// true if the point is within the rectangle; otherwise, false. - public bool Contains(Point pt) - => Contains(pt.X, pt.Y); - - /// - /// Determines whether the specified rectangle is fully contained within this rectangle. - /// - /// The rectangle to check. - /// true if the rectangle is fully contained; otherwise, false. - public bool Contains(Rectangle rect) - => rect.X >= X && rect.Y >= Y && rect.Right <= Right && rect.Bottom <= Bottom; - - /// - /// Determines whether this rectangle intersects with another rectangle. - /// - /// The rectangle to check. - /// true if the rectangles intersect; otherwise, false. - public bool IntersectsWith(Rectangle rect) - => rect.X < Right && X < rect.Right && rect.Y < Bottom && Y < rect.Bottom; - - // ── Set operations (instance — mutate this) ─────────────────────────────── - - /// - /// Intersects this rectangle with another, modifying this rectangle to the result. - /// - /// The rectangle to intersect with. - public void Intersect(Rectangle rect) - { - Rectangle result = Intersect(this, rect); - X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; - } - - /// - /// Inflates this rectangle by the specified width and height. - /// - /// The horizontal inflation amount. - /// The vertical inflation amount. - public void Inflate(int width, int height) - { - X -= width; - Y -= height; - Width += 2 * width; - Height += 2 * height; - } - - /// - /// Inflates this rectangle by the specified size. - /// - /// The size to inflate by. - public void Inflate(Size size) => Inflate(size.Width, size.Height); - - /// - /// Offsets this rectangle by the specified horizontal and vertical amounts. - /// - /// The horizontal offset. - /// The vertical offset. - public void Offset(int dx, int dy) { X += dx; Y += dy; } - - /// - /// Offsets this rectangle by the specified point. - /// - /// The point containing the offsets. - public void Offset(Point pos) { X += pos.X; Y += pos.Y; } - - // ── Set operations (static — return new Rectangle) ──────────────────────── - - /// - /// Returns the intersection of two rectangles. - /// - /// The first rectangle. - /// The second rectangle. - /// The intersection rectangle, or if they don't intersect. - public static Rectangle Intersect(Rectangle a, Rectangle b) - { - int x = Math.Max(a.X, b.X); - int y = Math.Max(a.Y, b.Y); - int right = Math.Min(a.Right, b.Right); - int bottom = Math.Min(a.Bottom, b.Bottom); - return right > x && bottom > y - ? new Rectangle(x, y, right - x, bottom - y) - : Empty; - } - - /// - /// Returns the union of two rectangles. - /// - /// The first rectangle. - /// The second rectangle. - /// The smallest rectangle containing both input rectangles. - public static Rectangle Union(Rectangle a, Rectangle b) - { - int x = Math.Min(a.X, b.X); - int y = Math.Min(a.Y, b.Y); - int right = Math.Max(a.Right, b.Right); - int bottom = Math.Max(a.Bottom, b.Bottom); - return new Rectangle(x, y, right - x, bottom - y); - } - - /// - /// Returns an inflated copy of the specified rectangle. - /// - /// The rectangle to inflate. - /// The horizontal inflation amount. - /// The vertical inflation amount. - /// The inflated rectangle. - public static Rectangle Inflate(Rectangle rect, int x, int y) - { - Rectangle r = rect; - r.Inflate(x, y); - return r; - } - - // ── Conversion ──────────────────────────────────────────────────────────── - - /// - /// Converts this to a . - /// - /// A new with the same dimensions. - public RectangleF ToRectangleF() => new RectangleF(X, Y, Width, Height); - - // ── Equality ───────────────────────────────────────────────────────────── - - /// - /// Indicates whether this rectangle is equal to another rectangle. - /// - /// The rectangle to compare. - /// true if the rectangles are equal; otherwise, false. - public bool Equals(Rectangle other) - => X == other.X && Y == other.Y && Width == other.Width && Height == other.Height; - - /// - /// Indicates whether this rectangle is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is Rectangle r && Equals(r); - - /// - /// Returns a hash code for this rectangle. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked - { - int h = X; - h = h * 397 ^ Y; - h = h * 397 ^ Width; - h = h * 397 ^ Height; - return h; - } - } - - /// - /// Compares two rectangles for equality. - /// - public static bool operator ==(Rectangle left, Rectangle right) => left.Equals(right); - - /// - /// Compares two rectangles for inequality. - /// - public static bool operator !=(Rectangle left, Rectangle right) => !left.Equals(right); - - /// - /// Returns a string representation of this rectangle. - /// - /// A string in the format "{X=value, Y=value, Width=value, Height=value}". - public override string ToString() - => $"{{X={X}, Y={Y}, Width={Width}, Height={Height}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Geometry/RectangleF.cs b/src/MiniPdf/Drawing/Geometry/RectangleF.cs deleted file mode 100644 index b3cb0315..00000000 --- a/src/MiniPdf/Drawing/Geometry/RectangleF.cs +++ /dev/null @@ -1,339 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// - /// Represents the location and size of a rectangular region, using float coordinates. - /// - /// - /// A defines a region with X, Y, Width, and Height. - /// X and Y represent the top-left corner; Width and Height represent the dimensions. - /// - public struct RectangleF : IEquatable - { - /// - /// Gets or sets the x-coordinate of the top-left corner. - /// - public float X; - - /// - /// Gets or sets the y-coordinate of the top-left corner. - /// - public float Y; - - /// - /// Gets or sets the width. - /// - public float Width; - - /// - /// Gets or sets the height. - /// - public float Height; - - /// - /// Initializes a new with the specified location and size. - /// - /// The x-coordinate of the top-left corner. - /// The y-coordinate of the top-left corner. - /// The width. - /// The height. - public RectangleF(float x, float y, float width, float height) - { - X = x; Y = y; Width = width; Height = height; - } - - /// - /// Initializes a new from a point and a size. - /// - /// The top-left corner. - /// The dimensions. - public RectangleF(PointF location, SizeF size) - { - X = location.X; Y = location.Y; Width = size.Width; Height = size.Height; - } - - /// - /// Gets an empty (0, 0, 0, 0). - /// - public static readonly RectangleF Empty = default; - - // ── Derived edges ───────────────────────────────────────────────────────── - - /// - /// Gets the x-coordinate of the left edge. - /// - public float Left => X; - - /// - /// Gets the y-coordinate of the top edge. - /// - public float Top => Y; - - /// - /// Gets the x-coordinate of the right edge. - /// - public float Right => X + Width; - - /// - /// Gets the y-coordinate of the bottom edge. - /// - public float Bottom => Y + Height; - - /// - /// Gets a value indicating whether this rectangle is empty (Width or Height less than or equal to 0). - /// - public bool IsEmpty => Width <= 0f || Height <= 0f; - - /// - /// Gets or sets the top-left corner of this rectangle. - /// - public PointF Location - { - get => new PointF(X, Y); - set { X = value.X; Y = value.Y; } - } - - /// - /// Gets or sets the dimensions of this rectangle. - /// - public SizeF Size - { - get => new SizeF(Width, Height); - set { Width = value.Width; Height = value.Height; } - } - - // ── Factory ────────────────────────────────────────────────────────────── - - /// - /// Creates a rectangle from left, top, right, and bottom coordinates. - /// - /// The x-coordinate of the left edge. - /// The y-coordinate of the top edge. - /// The x-coordinate of the right edge. - /// The y-coordinate of the bottom edge. - /// A new . - public static RectangleF FromLTRB(float left, float top, float right, float bottom) - => new RectangleF(left, top, right - left, bottom - top); - - // ── Containment / intersection ──────────────────────────────────────────── - - /// - /// Determines whether the specified point is contained within this rectangle. - /// - /// The x-coordinate of the point. - /// The y-coordinate of the point. - /// true if the point is within the rectangle; otherwise, false. - public bool Contains(float x, float y) - => x >= X && x < X + Width && y >= Y && y < Y + Height; - - /// - /// Determines whether the specified point is contained within this rectangle. - /// - /// The point to check. - /// true if the point is within the rectangle; otherwise, false. - public bool Contains(PointF pt) - => Contains(pt.X, pt.Y); - - /// - /// Determines whether the specified rectangle is fully contained within this rectangle. - /// - /// The rectangle to check. - /// true if the rectangle is fully contained; otherwise, false. - public bool Contains(RectangleF rect) - => rect.X >= X && rect.Y >= Y && rect.Right <= Right && rect.Bottom <= Bottom; - - /// - /// Determines whether this rectangle intersects with another rectangle. - /// - /// The rectangle to check. - /// true if the rectangles intersect; otherwise, false. - public bool IntersectsWith(RectangleF rect) - => rect.X < Right && X < rect.Right && rect.Y < Bottom && Y < rect.Bottom; - - // ── Set operations (instance — mutate this) ─────────────────────────────── - - /// - /// Intersects this rectangle with another, modifying this rectangle to the result. - /// - /// The rectangle to intersect with. - public void Intersect(RectangleF rect) - { - RectangleF result = Intersect(this, rect); - X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; - } - - /// - /// Inflates this rectangle by the specified width and height. - /// - /// The horizontal inflation amount. - /// The vertical inflation amount. - public void Inflate(float width, float height) - { - X -= width; - Y -= height; - Width += 2f * width; - Height += 2f * height; - } - - /// - /// Inflates this rectangle by the specified size. - /// - /// The size to inflate by. - public void Inflate(SizeF size) => Inflate(size.Width, size.Height); - - /// - /// Offsets this rectangle by the specified horizontal and vertical amounts. - /// - /// The horizontal offset. - /// The vertical offset. - public void Offset(float dx, float dy) { X += dx; Y += dy; } - - /// - /// Offsets this rectangle by the specified point. - /// - /// The point containing the offsets. - public void Offset(PointF pos) { X += pos.X; Y += pos.Y; } - - // ── Set operations (static — return new RectangleF) ────────────────────── - - /// - /// Returns the intersection of two rectangles. - /// - /// The first rectangle. - /// The second rectangle. - /// The intersection rectangle, or if they don't intersect. - public static RectangleF Intersect(RectangleF a, RectangleF b) - { - float x = Math.Max(a.X, b.X); - float y = Math.Max(a.Y, b.Y); - float right = Math.Min(a.Right, b.Right); - float bottom = Math.Min(a.Bottom, b.Bottom); - return right > x && bottom > y - ? new RectangleF(x, y, right - x, bottom - y) - : Empty; - } - - /// - /// Returns the union of two rectangles. - /// - /// The first rectangle. - /// The second rectangle. - /// The smallest rectangle containing both input rectangles. - public static RectangleF Union(RectangleF a, RectangleF b) - { - float x = Math.Min(a.X, b.X); - float y = Math.Min(a.Y, b.Y); - float right = Math.Max(a.Right, b.Right); - float bottom = Math.Max(a.Bottom, b.Bottom); - return new RectangleF(x, y, right - x, bottom - y); - } - - /// - /// Returns an inflated copy of the specified rectangle. - /// - /// The rectangle to inflate. - /// The horizontal inflation amount. - /// The vertical inflation amount. - /// The inflated rectangle. - public static RectangleF Inflate(RectangleF rect, float x, float y) - { - RectangleF r = rect; - r.Inflate(x, y); - return r; - } - - // ── Conversion ──────────────────────────────────────────────────────────── - - /// - /// Truncates each component toward zero and converts to a . - /// - /// A new with truncated dimensions. - public Rectangle ToRectangle() - => new Rectangle((int)X, (int)Y, (int)Width, (int)Height); - - /// - /// Rounds each component to the nearest integer and converts to a . - /// - /// The rectangle to round. - /// A new with rounded dimensions. - public static Rectangle Round(RectangleF r) - => new Rectangle( - (int)Math.Round(r.X), (int)Math.Round(r.Y), - (int)Math.Round(r.Width), (int)Math.Round(r.Height)); - - /// - /// Truncates each component toward negative infinity and converts to a . - /// - /// The rectangle to truncate. - /// A new with truncated dimensions. - public static Rectangle Truncate(RectangleF r) - => new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height); - - /// - /// Applies ceiling to each component and converts to a . - /// - /// The rectangle to apply ceiling to. - /// A new with ceiled dimensions. - public static Rectangle Ceiling(RectangleF r) - => new Rectangle( - (int)Math.Ceiling(r.X), (int)Math.Ceiling(r.Y), - (int)Math.Ceiling(r.Width), (int)Math.Ceiling(r.Height)); - - /// - /// Implicitly converts a to a . - /// - public static implicit operator RectangleF(Rectangle r) - => new RectangleF(r.X, r.Y, r.Width, r.Height); - - // ── Equality ───────────────────────────────────────────────────────────── - - /// - /// Indicates whether this rectangle is equal to another rectangle. - /// - /// The rectangle to compare. - /// true if the rectangles are equal; otherwise, false. - public bool Equals(RectangleF other) - => X == other.X && Y == other.Y && Width == other.Width && Height == other.Height; - - /// - /// Indicates whether this rectangle is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is RectangleF r && Equals(r); - - /// - /// Returns a hash code for this rectangle. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked - { - int h = X.GetHashCode(); - h = h * 397 ^ Y.GetHashCode(); - h = h * 397 ^ Width.GetHashCode(); - h = h * 397 ^ Height.GetHashCode(); - return h; - } - } - - /// - /// Compares two rectangles for equality. - /// - public static bool operator ==(RectangleF left, RectangleF right) => left.Equals(right); - - /// - /// Compares two rectangles for inequality. - /// - public static bool operator !=(RectangleF left, RectangleF right) => !left.Equals(right); - - /// - /// Returns a string representation of this rectangle. - /// - /// A string in the format "{X=value, Y=value, Width=value, Height=value}". - public override string ToString() - => $"{{X={X}, Y={Y}, Width={Width}, Height={Height}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Geometry/Size.cs b/src/MiniPdf/Drawing/Geometry/Size.cs deleted file mode 100644 index 30158ef9..00000000 --- a/src/MiniPdf/Drawing/Geometry/Size.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// Represents the size of a rectangular region with an ordered pair of integers. - /// - /// A represents the width and height of a rectangle. - /// Width and Height are public fields for performance reasons, matching the System.Drawing API. - /// - public struct Size : IEquatable - { - /// - /// Gets or sets the width. - /// - public int Width; - - /// - /// Gets or sets the height. - /// - public int Height; - - /// - /// Initializes a new with the specified width and height. - /// - /// The width. - /// The height. - public Size(int width, int height) { Width = width; Height = height; } - - /// - /// Initializes a new from a . - /// - /// The point to convert to a size. - public Size(Point pt) { Width = pt.X; Height = pt.Y; } - - /// - /// Gets an empty (0, 0). - /// - public static readonly Size Empty = default; - - /// - /// Gets a value indicating whether this size is empty (0, 0). - /// - public bool IsEmpty => Width == 0 && Height == 0; - - /// - /// Converts this to a . - /// - /// A new with the same dimensions. - public SizeF ToSizeF() => new SizeF(Width, Height); - - /// - /// Adds two sizes. - /// - /// The first size. - /// The second size. - /// The resulting size. - public static Size Add(Size sz1, Size sz2) => new Size(sz1.Width + sz2.Width, sz1.Height + sz2.Height); - - /// - /// Subtracts the second size from the first. - /// - /// The size to subtract from. - /// The size to subtract. - /// The resulting size. - public static Size Subtract(Size sz1, Size sz2) => new Size(sz1.Width - sz2.Width, sz1.Height - sz2.Height); - - /// - /// Adds two sizes. - /// - public static Size operator +(Size sz1, Size sz2) => Add(sz1, sz2); - - /// - /// Subtracts two sizes. - /// - public static Size operator -(Size sz1, Size sz2) => Subtract(sz1, sz2); - - /// - /// Explicitly converts a to a . - /// - public static explicit operator Point(Size sz) => new Point(sz.Width, sz.Height); - - /// - /// Implicitly converts a to a . - /// - public static implicit operator SizeF(Size sz) => new SizeF(sz.Width, sz.Height); - - /// - /// Compares two sizes for equality. - /// - public static bool operator ==(Size left, Size right) => left.Width == right.Width && left.Height == right.Height; - - /// - /// Compares two sizes for inequality. - /// - public static bool operator !=(Size left, Size right) => !(left == right); - - /// - /// Indicates whether this size is equal to another size. - /// - /// The size to compare. - /// true if the sizes are equal; otherwise, false. - public bool Equals(Size other) => this == other; - - /// - /// Indicates whether this size is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is Size s && this == s; - - /// - /// Returns a hash code for this size. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked { return Width * 397 ^ Height; } - } - - /// - /// Returns a string representation of this size. - /// - /// A string in the format "{Width=value, Height=value}". - public override string ToString() => $"{{Width={Width}, Height={Height}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Geometry/SizeF.cs b/src/MiniPdf/Drawing/Geometry/SizeF.cs deleted file mode 100644 index c6ed16b4..00000000 --- a/src/MiniPdf/Drawing/Geometry/SizeF.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Geometry -{ - /// Represents the size of a rectangular region with an ordered pair of floats. - /// - /// A represents the width and height of a rectangle. - /// Width and Height are public fields for performance reasons, matching the System.Drawing API. - /// - public struct SizeF : IEquatable - { - /// - /// Gets or sets the width. - /// - public float Width; - - /// - /// Gets or sets the height. - /// - public float Height; - - /// - /// Initializes a new with the specified width and height. - /// - /// The width. - /// The height. - public SizeF(float width, float height) { Width = width; Height = height; } - - /// - /// Initializes a new from a . - /// - /// The point to convert to a size. - public SizeF(PointF pt) { Width = pt.X; Height = pt.Y; } - - /// - /// Initializes a new as a copy of another size. - /// - /// The size to copy. - public SizeF(SizeF sz) { Width = sz.Width; Height = sz.Height; } - - /// - /// Gets an empty (0, 0). - /// - public static readonly SizeF Empty = default; - - /// - /// Gets a value indicating whether this size is empty (0, 0). - /// - public bool IsEmpty => Width == 0f && Height == 0f; - - /// - /// Truncates each dimension to the nearest integer toward zero. - /// - /// A new with truncated dimensions. - public Size ToSize() => new Size((int)Width, (int)Height); - - /// - /// Converts this to a . - /// - /// A new with the same dimensions. - public PointF ToPointF() => new PointF(Width, Height); - - /// - /// Adds two sizes. - /// - /// The first size. - /// The second size. - /// The resulting size. - public static SizeF Add(SizeF sz1, SizeF sz2) => new SizeF(sz1.Width + sz2.Width, sz1.Height + sz2.Height); - - /// - /// Subtracts the second size from the first. - /// - /// The size to subtract from. - /// The size to subtract. - /// The resulting size. - public static SizeF Subtract(SizeF sz1, SizeF sz2) => new SizeF(sz1.Width - sz2.Width, sz1.Height - sz2.Height); - - /// - /// Adds two sizes. - /// - public static SizeF operator +(SizeF sz1, SizeF sz2) => Add(sz1, sz2); - - /// - /// Subtracts two sizes. - /// - public static SizeF operator -(SizeF sz1, SizeF sz2) => Subtract(sz1, sz2); - - /// - /// Compares two sizes for equality. - /// - public static bool operator ==(SizeF left, SizeF right) => left.Width == right.Width && left.Height == right.Height; - - /// - /// Compares two sizes for inequality. - /// - public static bool operator !=(SizeF left, SizeF right) => !(left == right); - - /// - /// Indicates whether this size is equal to another size. - /// - /// The size to compare. - /// true if the sizes are equal; otherwise, false. - public bool Equals(SizeF other) => this == other; - - /// - /// Indicates whether this size is equal to another object. - /// - /// The object to compare. - /// true if the objects are equal; otherwise, false. - public override bool Equals(object? obj) => obj is SizeF s && this == s; - - /// - /// Returns a hash code for this size. - /// - /// The hash code. - public override int GetHashCode() - { - unchecked { return Width.GetHashCode() * 397 ^ Height.GetHashCode(); } - } - - /// - /// Returns a string representation of this size. - /// - /// A string in the format "{Width=value, Height=value}". - public override string ToString() => $"{{Width={Width}, Height={Height}}}"; - } -} diff --git a/src/MiniPdf/Drawing/Graphics/Graphics.cs b/src/MiniPdf/Drawing/Graphics/Graphics.cs deleted file mode 100644 index 0e00b57a..00000000 --- a/src/MiniPdf/Drawing/Graphics/Graphics.cs +++ /dev/null @@ -1,2104 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Rendering; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; -using MiniSoftware.Drawing.Text.Bidi; - -namespace MiniSoftware.Drawing -{ - /// - /// Encapsulates a GDI+ drawing surface and provides methods for rendering shapes, text, and images. - /// - /// - /// A object is associated with a specific device context and is used to - /// perform drawing operations. It is typically obtained from a via . - /// - public class Graphics : IDrawingContext - { - private readonly Bitmap? _target; - private Matrix _transform; - private Region _clip; - private Point _renderingOrigin; - private bool _disposed; - - // ── Rendering-hint backing fields ── - private SmoothingMode _smoothingMode; - private InterpolationMode _interpolationMode; - private CompositingMode _compositingMode; - private CompositingQuality _compositingQuality; - private PixelOffsetMode _pixelOffsetMode; - private TextRenderingHint _textRenderingHint; - private GraphicsUnit _pageUnit; - private float _pageScale; - - private readonly List _stateStack = new List(); - private readonly List _containerStack = new List(); - - /// - /// Gets a value indicating whether this graphics surface is a recording - /// (non-raster) surface. When true, is null and - /// raster core methods are never called. - /// - protected virtual bool IsRecording => false; - - /// - /// Initializes a new instance associated with the specified bitmap. - /// - /// The target bitmap for drawing operations. - protected Graphics(Bitmap target) - { - _target = target ?? throw new ArgumentNullException(nameof(target)); - _transform = new Matrix(); - _clip = new Region(new RectangleF(0f, 0f, target.Width, target.Height)); - - _pageUnit = GraphicsUnit.Pixel; - _pageScale = 1f; - _smoothingMode = SmoothingMode.None; - _interpolationMode = InterpolationMode.NearestNeighbor; - _compositingMode = CompositingMode.SourceOver; - _compositingQuality = CompositingQuality.Default; - _pixelOffsetMode = PixelOffsetMode.Default; - _textRenderingHint = TextRenderingHint.SystemDefault; - } - - /// - /// Sentinel constructor for recording surfaces that have no bitmap target. - /// Initializes transform and clip to safe defaults without allocating a bitmap. - /// - internal Graphics() - { - _target = null; - _transform = new Matrix(); - _clip = new Region(); - _clip.MakeInfinite(); - - _pageUnit = GraphicsUnit.Pixel; - _pageScale = 1f; - _smoothingMode = SmoothingMode.None; - _interpolationMode = InterpolationMode.NearestNeighbor; - _compositingMode = CompositingMode.SourceOver; - _compositingQuality = CompositingQuality.Default; - _pixelOffsetMode = PixelOffsetMode.Default; - _textRenderingHint = TextRenderingHint.SystemDefault; - } - - /// - /// Creates a object from the specified image. - /// - /// The image to create the graphics context from. - /// A new instance. - /// Thrown when is null. - /// Thrown when the image is not a . - public static Graphics FromImage(Image image) - { - if (image == null) throw new ArgumentNullException(nameof(image)); - if (!(image is Bitmap bmp)) - throw new NotSupportedException("Only Bitmap-backed images are currently supported."); - return new Graphics(bmp); - } - - /// - /// Creates a object from a device context handle. - /// - /// The device context handle. - /// A new instance. - /// Always thrown as HDC-backed Graphics is not supported. - public static Graphics FromHdc(IntPtr hdc) - => throw new PlatformNotSupportedException("HDC-backed Graphics is not supported."); - - /// - /// Creates a object from a window handle. - /// - /// The window handle. - /// A new instance. - /// Always thrown as HWND-backed Graphics is not supported. - public static Graphics FromHwnd(IntPtr hwnd) - => throw new PlatformNotSupportedException("HWND-backed Graphics is not supported."); - - /// - /// Gets or sets the world transformation matrix for this . - /// - public Matrix Transform - { - get { ThrowIfDisposed(); return _transform.Clone(); } - set - { - ThrowIfDisposed(); - if (value == null) throw new ArgumentNullException(nameof(value)); - _transform = value.Clone(); - OnTransformChanged(); - } - } - - /// - /// Gets or sets the unit of measure for page coordinates. - /// - public GraphicsUnit PageUnit - { - get => _pageUnit; - set { _pageUnit = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the scaling factor for page coordinates. - /// - public float PageScale - { - get => _pageScale; - set { _pageScale = value; OnHintChanged(value); } - } - - public Text.FontFallbackChain? FontFallback { get; set; } - - /// - /// Gets or sets the smoothing mode for rendering lines and curves. - /// - public SmoothingMode SmoothingMode - { - get => _smoothingMode; - set { _smoothingMode = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the interpolation mode for scaling and rotating images. - /// - public InterpolationMode InterpolationMode - { - get => _interpolationMode; - set { _interpolationMode = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the compositing mode for rendering. - /// - public CompositingMode CompositingMode - { - get => _compositingMode; - set { _compositingMode = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the compositing quality for rendering. - /// - public CompositingQuality CompositingQuality - { - get => _compositingQuality; - set { _compositingQuality = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the pixel offset mode for rendering. - /// - public PixelOffsetMode PixelOffsetMode - { - get => _pixelOffsetMode; - set { _pixelOffsetMode = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the text rendering hint for text quality. - /// - public TextRenderingHint TextRenderingHint - { - get => _textRenderingHint; - set { _textRenderingHint = value; OnHintChanged(value); } - } - - /// - /// Gets or sets the clipping region for this . - /// - public Region Clip - { - get { ThrowIfDisposed(); return _clip.Clone(); } - set - { - ThrowIfDisposed(); - if (value == null) throw new ArgumentNullException(nameof(value)); - ReplaceClip(value.Clone()); - OnClipChanged(); - } - } - - /// - /// Gets the bounding rectangle of the clipping region. - /// - public RectangleF ClipBounds - { - get { ThrowIfDisposed(); return _clip.GetBounds(this); } - } - - /// - /// Gets a value indicating whether the clipping region is empty. - /// - public bool IsClipEmpty - { - get { ThrowIfDisposed(); return _clip.IsEmpty(this); } - } - - /// - /// Gets the visible clipping bounds. - /// - public RectangleF VisibleClipBounds - { - get - { - ThrowIfDisposed(); - var b = ClipBounds; - var s = new RectangleF(0f, 0f, Width, Height); - return RectangleF.Intersect(b, s); - } - } - - /// - /// Gets the width of the drawing surface in pixels. - /// - public virtual int Width => _target!.Width; - - /// - /// Gets the height of the drawing surface in pixels. - /// - public virtual int Height => _target!.Height; - - /// - /// Gets the horizontal resolution of the graphics context in pixels per inch. - /// - public virtual float DpiX => _target!.HorizontalResolution; - - /// - /// Gets the vertical resolution of the graphics context in pixels per inch. - /// - public virtual float DpiY => _target!.VerticalResolution; - - /// - /// Gets or sets the rendering origin point for the graphics context. - /// - public Point RenderingOrigin - { - get { ThrowIfDisposed(); return _renderingOrigin; } - set { ThrowIfDisposed(); _renderingOrigin = value; OnHintChanged(value); } - } - - /// - /// Resets the world transformation matrix to the identity matrix. - /// - public void ResetTransform() - { - ThrowIfDisposed(); - _transform.Reset(); - OnTransformChanged(); - } - - /// - /// Multiplies the world transformation matrix by the specified matrix. - /// - /// The matrix to multiply. - /// The order of multiplication (prepend or append). - public void MultiplyTransform(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) - { - ThrowIfDisposed(); - if (matrix == null) throw new ArgumentNullException(nameof(matrix)); - _transform.Multiply(matrix, order); - OnTransformChanged(); - } - - /// - /// Rotates the world transformation matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - { - ThrowIfDisposed(); - _transform.Rotate(angle, order); - OnTransformChanged(); - } - - /// - /// Scales the world transformation matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - { - ThrowIfDisposed(); - _transform.Scale(sx, sy, order); - OnTransformChanged(); - } - - /// - /// Translates the world transformation matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - { - ThrowIfDisposed(); - _transform.Translate(dx, dy, order); - OnTransformChanged(); - } - - /// - /// Draws a line connecting two points with the specified pen. - /// - /// The pen to draw with. - /// The x-coordinate of the first point. - /// The y-coordinate of the first point. - /// The x-coordinate of the second point. - /// The y-coordinate of the second point. - public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - using var path = new GraphicsPath(); - path.AddLine(ToPointF(x1, y1), ToPointF(x2, y2)); - DrawPath(pen, path); - } - - /// - /// Draws a line connecting two points with the specified pen. - /// - /// The pen to draw with. - /// The first point. - /// The second point. - public void DrawLine(Pen pen, PointF pt1, PointF pt2) - => DrawLine(pen, pt1.X, pt1.Y, pt2.X, pt2.Y); - - /// - /// Draws a line connecting two points with the specified pen. - /// - /// The pen to draw with. - /// The x-coordinate of the first point. - /// The y-coordinate of the first point. - /// The x-coordinate of the second point. - /// The y-coordinate of the second point. - public void DrawLine(Pen pen, int x1, int y1, int x2, int y2) - => DrawLine(pen, (float)x1, (float)y1, (float)x2, (float)y2); - - /// - /// Draws a series of line segments connecting an array of points. - /// - /// The pen to draw with. - /// The array of points to connect. - public void DrawLines(Pen pen, PointF[] points) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (points == null) throw new ArgumentNullException(nameof(points)); - if (points.Length < 2) return; - - using var path = new GraphicsPath(); - path.AddLines(ToPointFs(points)); - DrawPath(pen, path); - } - - /// - /// Draws a rectangle with the specified pen. - /// - /// The pen to draw with. - /// The rectangle to draw. - public void DrawRectangle(Pen pen, Rectangle rect) - => DrawRectangle(pen, new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - /// - /// Draws a rectangle with the specified pen. - /// - /// The pen to draw with. - /// The x-coordinate of the rectangle. - /// The y-coordinate of the rectangle. - /// The width of the rectangle. - /// The height of the rectangle. - public void DrawRectangle(Pen pen, float x, float y, float width, float height) - => DrawRectangle(pen, new RectangleF(x, y, width, height)); - - /// - /// Draws a rectangle with the specified pen. - /// - /// The pen to draw with. - /// The rectangle to draw. - public void DrawRectangle(Pen pen, RectangleF rect) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - using var path = new GraphicsPath(); - path.AddRectangle(ToRectangleF(rect)); - DrawPath(pen, path); - } - - /// - /// Draws a series of rectangles with the specified pen. - /// - /// The pen to draw with. - /// The array of rectangles to draw. - public void DrawRectangles(Pen pen, RectangleF[] rects) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (rects == null) throw new ArgumentNullException(nameof(rects)); - - using var path = new GraphicsPath(); - for (int i = 0; i < rects.Length; i++) - path.AddRectangle(ToRectangleF(rects[i])); - DrawPath(pen, path); - } - - /// - /// Draws an ellipse defined by a bounding rectangle with the specified pen. - /// - /// The pen to draw with. - /// The bounding rectangle of the ellipse. - public void DrawEllipse(Pen pen, Rectangle rect) - => DrawEllipse(pen, new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - /// - /// Draws an ellipse defined by a bounding rectangle with the specified pen. - /// - /// The pen to draw with. - /// The bounding rectangle of the ellipse. - public void DrawEllipse(Pen pen, RectangleF rect) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - using var path = new GraphicsPath(); - path.AddEllipse(ToRectangleF(rect)); - DrawPath(pen, path); - } - - /// - /// Draws an arc defined by a bounding rectangle, start angle, and sweep angle with the specified pen. - /// - /// The pen to draw with. - /// The bounding rectangle of the arc. - /// The start angle of the arc in degrees. - /// The sweep angle of the arc in degrees. - public void DrawArc(Pen pen, RectangleF rect, float startAngle, float sweepAngle) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - var r = ToRectangleF(rect); - using var path = new GraphicsPath(); - path.AddArc(r, startAngle, sweepAngle); - DrawPath(pen, path); - } - - /// - /// Draws a Bézier spline defined by four points with the specified pen. - /// - /// The pen to draw with. - /// The starting point. - /// The first control point. - /// The second control point. - /// The ending point. - public void DrawBezier(Pen pen, PointF pt1, PointF pt2, PointF pt3, PointF pt4) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - using var path = new GraphicsPath(); - path.AddBezier(ToPointF(pt1), ToPointF(pt2), ToPointF(pt3), ToPointF(pt4)); - DrawPath(pen, path); - } - - /// - /// Draws a series of Bézier splines with the specified pen. - /// - /// The pen to draw with. - /// The array of points defining the splines. - public void DrawBeziers(Pen pen, PointF[] points) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(); - path.AddBeziers(ToPointFs(points)); - DrawPath(pen, path); - } - - /// - /// Draws a curve through a series of points with the specified pen. - /// - /// The pen to draw with. - /// The array of points to draw through. - /// The tension of the curve (default 0.5). - public void DrawCurve(Pen pen, PointF[] points, float tension = 0.5f) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(); - path.AddCurve(ToPointFs(points), tension); - DrawPath(pen, path); - } - - /// - /// Draws a closed curve through a series of points with the specified pen. - /// - /// The pen to draw with. - /// The array of points to draw through. - /// The tension of the curve (default 0.5). - /// The fill mode for the curve (default Alternate). - public void DrawClosedCurve(Pen pen, PointF[] points, float tension = 0.5f, FillMode fillMode = FillMode.Alternate) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(fillMode); - path.AddClosedCurve(ToPointFs(points), tension); - DrawPath(pen, path); - } - - /// - /// Draws a polygon defined by an array of points with the specified pen. - /// - /// The pen to draw with. - /// The array of points defining the polygon. - public void DrawPolygon(Pen pen, PointF[] points) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(); - path.AddPolygon(ToPointFs(points)); - DrawPath(pen, path); - } - - /// - /// Draws a path defined by a GraphicsPath object with the specified pen. - /// - /// The pen to draw with. - /// The GraphicsPath to draw. - public void DrawPath(Pen pen, GraphicsPath path) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - if (path == null) throw new ArgumentNullException(nameof(path)); - DrawPathCore(pen, path); - } - - /// - /// Core implementation that strokes a graphics path. Override in a - /// recording surface to capture the command instead of rasterizing. - /// - /// The pen to stroke with. - /// The path to stroke. - protected virtual void DrawPathCore(Pen pen, GraphicsPath path) - { - Rasterizer.DrawPath( - _target!, - path, - pen, - _transform, - GetClipRect(), - SmoothingMode, - CompositingMode, - InterpolationMode); - } - - /// - /// Draws a pie shape defined by an ellipse and two radial lines with the specified pen. - /// - /// The pen to draw with. - /// The bounding rectangle of the pie. - /// The start angle of the pie in degrees. - /// The sweep angle of the pie in degrees. - public void DrawPie(Pen pen, RectangleF rect, float startAngle, float sweepAngle) - { - ThrowIfDisposed(); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - var r = ToRectangleF(rect); - float cx = r.X + r.Width * 0.5f; - float cy = r.Y + r.Height * 0.5f; - float a0 = startAngle * ((float)Math.PI / 180f); - float a1 = (startAngle + sweepAngle) * ((float)Math.PI / 180f); - - var p0 = new PointF(cx + (float)Math.Cos(a0) * r.Width * 0.5f, - cy + (float)Math.Sin(a0) * r.Height * 0.5f); - var p1 = new PointF(cx + (float)Math.Cos(a1) * r.Width * 0.5f, - cy + (float)Math.Sin(a1) * r.Height * 0.5f); - - using var path = new GraphicsPath(); - path.StartFigure(); - path.AddLine(new PointF(cx, cy), p0); - path.AddArc(r, startAngle, sweepAngle); - path.AddLine(p1, new PointF(cx, cy)); - path.CloseFigure(); - - DrawPath(pen, path); - } - - /// - /// Fills the interior of a rectangle with the specified brush. - /// - /// The brush to fill with. - /// The rectangle to fill. - public void FillRectangle(Brush brush, Rectangle rect) - => FillRectangle(brush, new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - /// - /// Fills the interior of a rectangle with the specified brush. - /// - /// The brush to fill with. - /// The x-coordinate of the rectangle. - /// The y-coordinate of the rectangle. - /// The width of the rectangle. - /// The height of the rectangle. - public void FillRectangle(Brush brush, float x, float y, float width, float height) - => FillRectangle(brush, new RectangleF(x, y, width, height)); - - /// - /// Fills the interior of a rectangle with the specified brush. - /// - /// The brush to fill with. - /// The rectangle to fill. - public void FillRectangle(Brush brush, RectangleF rect) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - using var path = new GraphicsPath(); - path.AddRectangle(ToRectangleF(rect)); - FillPath(brush, path); - } - - /// - /// Fills the interiors of a series of rectangles with the specified brush. - /// - /// The brush to fill with. - /// The array of rectangles to fill. - public void FillRectangles(Brush brush, RectangleF[] rects) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (rects == null) throw new ArgumentNullException(nameof(rects)); - - using var path = new GraphicsPath(); - for (int i = 0; i < rects.Length; i++) - path.AddRectangle(ToRectangleF(rects[i])); - FillPath(brush, path); - } - - /// - /// Fills the interior of an ellipse defined by a bounding rectangle with the specified brush. - /// - /// The brush to fill with. - /// The bounding rectangle of the ellipse. - public void FillEllipse(Brush brush, Rectangle rect) - => FillEllipse(brush, new RectangleF(rect.X, rect.Y, rect.Width, rect.Height)); - - /// - /// Fills the interior of an ellipse defined by a bounding rectangle with the specified brush. - /// - /// The brush to fill with. - /// The bounding rectangle of the ellipse. - public void FillEllipse(Brush brush, RectangleF rect) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - using var path = new GraphicsPath(); - path.AddEllipse(ToRectangleF(rect)); - FillPath(brush, path); - } - - /// - /// Fills the interior of a polygon defined by an array of points with the specified brush. - /// - /// The brush to fill with. - /// The array of points defining the polygon. - /// The fill mode for the polygon (default Alternate). - public void FillPolygon(Brush brush, PointF[] points, FillMode fillMode = FillMode.Alternate) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(fillMode); - path.AddPolygon(ToPointFs(points)); - FillPath(brush, path); - } - - /// - /// Fills the interior of a pie shape defined by an ellipse and two radial lines with the specified brush. - /// - /// The brush to fill with. - /// The bounding rectangle of the pie. - /// The start angle of the pie in degrees. - /// The sweep angle of the pie in degrees. - public void FillPie(Brush brush, RectangleF rect, float startAngle, float sweepAngle) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - var r = ToRectangleF(rect); - float cx = r.X + r.Width * 0.5f; - float cy = r.Y + r.Height * 0.5f; - float a0 = startAngle * ((float)Math.PI / 180f); - float a1 = (startAngle + sweepAngle) * ((float)Math.PI / 180f); - - var p0 = new PointF(cx + (float)Math.Cos(a0) * r.Width * 0.5f, - cy + (float)Math.Sin(a0) * r.Height * 0.5f); - var p1 = new PointF(cx + (float)Math.Cos(a1) * r.Width * 0.5f, - cy + (float)Math.Sin(a1) * r.Height * 0.5f); - - using var path = new GraphicsPath(); - path.StartFigure(); - path.AddLine(new PointF(cx, cy), p0); - path.AddArc(r, startAngle, sweepAngle); - path.AddLine(p1, new PointF(cx, cy)); - path.CloseFigure(); - - FillPath(brush, path); - } - - /// - /// Fills the interior of a path defined by a GraphicsPath object with the specified brush. - /// - /// The brush to fill with. - /// The GraphicsPath to fill. - public void FillPath(Brush brush, GraphicsPath path) - => FillPath(brush, path, path.FillMode); - - /// - /// Fills the interior of a path defined by a GraphicsPath object with the specified brush and fill mode. - /// - /// The brush to fill with. - /// The GraphicsPath to fill. - /// The fill mode. - public void FillPath(Brush brush, GraphicsPath path, FillMode fillMode) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (path == null) throw new ArgumentNullException(nameof(path)); - FillPathCore(brush, path, fillMode); - } - - /// - /// Core implementation that fills a graphics path. Override in a - /// recording surface to capture the command instead of rasterizing. - /// - protected virtual void FillPathCore(Brush brush, GraphicsPath path, FillMode fillMode) - { - Rasterizer.FillPath( - _target!, - path, - brush, - _transform, - fillMode, - GetClipRect(), - SmoothingMode, - CompositingMode, - InterpolationMode); - } - - /// - /// Fills the interior of a closed curve with the specified brush. - /// - /// The brush to fill with. - /// The array of points defining the curve. - /// The fill mode for the curve (default Alternate). - /// The tension of the curve (default 0.5). - public void FillClosedCurve(Brush brush, PointF[] points, FillMode fillMode = FillMode.Alternate, float tension = 0.5f) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (points == null) throw new ArgumentNullException(nameof(points)); - - using var path = new GraphicsPath(fillMode); - path.AddClosedCurve(ToPointFs(points), tension); - FillPath(brush, path); - } - - /// - /// Fills the interior of a region with the specified brush. - /// - /// The brush to fill with. - /// The region to fill. - public void FillRegion(Brush brush, Region region) - { - ThrowIfDisposed(); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (region == null) throw new ArgumentNullException(nameof(region)); - - using var identity = new Matrix(); - var scans = region.GetRegionScans(identity); - for (int i = 0; i < scans.Length; i++) - FillRectangle(brush, scans[i]); - } - - /// - /// Sets the clipping region to the specified rectangle. - /// - /// The rectangle to clip to. - /// The combine mode for the clipping operation (default Replace). - public void SetClip(Rectangle rect, CombineMode combineMode = CombineMode.Replace) - => SetClip(new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), combineMode); - - /// - /// Sets the clipping region to the specified rectangle. - /// - /// The rectangle to clip to. - /// The combine mode for the clipping operation (default Replace). - public void SetClip(RectangleF rect, CombineMode combineMode = CombineMode.Replace) - { - ThrowIfDisposed(); - using var region = new Region(ToRectangleF(rect)); - ApplyClip(region, combineMode); - OnClipChanged(); - } - - /// - /// Sets the clipping region to the specified path. - /// - /// The path to clip to. - /// The combine mode for the clipping operation (default Replace). - public void SetClip(GraphicsPath path, CombineMode combineMode = CombineMode.Replace) - { - ThrowIfDisposed(); - if (path == null) throw new ArgumentNullException(nameof(path)); - using var region = new Region(path); - ApplyClip(region, combineMode); - OnClipChanged(); - } - - /// - /// Sets the clipping region to the specified region. - /// - /// The region to clip to. - /// The combine mode for the clipping operation (default Replace). - public void SetClip(Region region, CombineMode combineMode = CombineMode.Replace) - { - ThrowIfDisposed(); - if (region == null) throw new ArgumentNullException(nameof(region)); - ApplyClip(region, combineMode); - OnClipChanged(); - } - - /// - /// Intersects the clipping region with the specified rectangle. - /// - /// The rectangle to intersect with. - public void IntersectClip(Rectangle rect) => SetClip(rect, CombineMode.Intersect); - - /// - /// Intersects the clipping region with the specified rectangle. - /// - /// The rectangle to intersect with. - public void IntersectClip(RectangleF rect) => SetClip(rect, CombineMode.Intersect); - - /// - /// Intersects the clipping region with the specified region. - /// - /// The region to intersect with. - public void IntersectClip(Region region) => SetClip(region, CombineMode.Intersect); - - /// - /// Excludes the specified rectangle from the clipping region. - /// - /// The rectangle to exclude. - public void ExcludeClip(Rectangle rect) => SetClip(rect, CombineMode.Exclude); - - /// - /// Excludes the specified region from the clipping region. - /// - /// The region to exclude. - public void ExcludeClip(Region region) => SetClip(region, CombineMode.Exclude); - - /// - /// Resets the clipping region to the entire graphics surface. - /// -public void ResetClip() - { - ThrowIfDisposed(); - ReplaceClip(new Region(new RectangleF(0f, 0f, Width, Height))); - OnClipChanged(); - } - - /// - /// Translates the clipping region by the specified amount. - /// - /// The horizontal translation. - /// The vertical translation. - public void TranslateClip(float dx, float dy) - { - ThrowIfDisposed(); - _clip.Translate(ToPixels(dx, PageUnit), ToPixels(dy, PageUnit)); - OnClipChanged(); - } - - /// - /// Saves the current graphics state and returns a GraphicsState object. - /// - /// The saved graphics state. - public virtual GraphicsState Save() - { - ThrowIfDisposed(); - var state = CreateState(); - _stateStack.Add(state); - return state; - } - - /// - /// Restores the graphics state to the specified state. - /// - /// The graphics state to restore. - public virtual void Restore(GraphicsState graphicsState) - { - ThrowIfDisposed(); - if (graphicsState == null) throw new ArgumentNullException(nameof(graphicsState)); - ApplyState(graphicsState); - - int idx = _stateStack.LastIndexOf(graphicsState); - if (idx >= 0) - _stateStack.RemoveRange(idx, _stateStack.Count - idx); - } - - /// - /// Begins a graphics container and saves the current state. - /// - /// The graphics container. - public virtual GraphicsContainer BeginContainer() - { - ThrowIfDisposed(); - var state = Save(); - var container = new GraphicsContainer(state); - _containerStack.Add(container); - return container; - } - - /// - /// Begins a graphics container with the specified destination and source rectangles and unit. - /// - /// The destination rectangle. - /// The source rectangle. - /// The graphics unit for the rectangles. - /// The graphics container. - public virtual GraphicsContainer BeginContainer(RectangleF dstRect, RectangleF srcRect, GraphicsUnit unit) - { - ThrowIfDisposed(); - var container = BeginContainer(); - - float sx = srcRect.Width == 0f ? 1f : dstRect.Width / srcRect.Width; - float sy = srcRect.Height == 0f ? 1f : dstRect.Height / srcRect.Height; - - var m = new Matrix(); - m.Translate(dstRect.X, dstRect.Y, MatrixOrder.Append); - m.Scale(sx, sy, MatrixOrder.Append); - m.Translate(-srcRect.X, -srcRect.Y, MatrixOrder.Append); - MultiplyTransform(m, MatrixOrder.Append); - - PageUnit = unit; - return container; - } - - /// - /// Ends a graphics container and restores the previous state. - /// - /// The graphics container to end. - public virtual void EndContainer(GraphicsContainer container) - { - ThrowIfDisposed(); - if (container == null) throw new ArgumentNullException(nameof(container)); - Restore(container.State); - _containerStack.Remove(container); - } - - /// - /// Clears the graphics surface with the specified color. - /// - /// The color to clear with. - public void Clear(Color color) - { - ThrowIfDisposed(); - ClearCore(color); - } - - /// - /// Core implementation that clears the surface. Override in a recording - /// surface to capture the command instead of rasterizing. - /// - protected virtual void ClearCore(Color color) - { - int bpp = Bitmap.GetBytesPerPixel(_target!._format); - if (bpp < 3) - { - for (int y = 0; y < _target!._height; y++) - for (int x = 0; x < _target!._width; x++) - _target!.SetPixel(x, y, color); - return; - } - - for (int y = 0; y < _target!._height; y++) - { - int row = y * _target!._stride; - for (int x = 0; x < _target!._width; x++) - { - int o = row + x * bpp; - _target!._pixels[o] = color.B; - _target!._pixels[o + 1] = color.G; - _target!._pixels[o + 2] = color.R; - if (bpp >= 4) - _target!._pixels[o + 3] = color.A; - } - } - } - - /// - /// Flushes the graphics buffer to the output device. - /// - public void Flush() { ThrowIfDisposed(); } - - /// - /// Flushes the graphics buffer to the output device with the specified intention. - /// - /// The flush intention. - public void Flush(FlushIntention intention) { ThrowIfDisposed(); } - - /// - /// Copies a block of pixels from the screen to the graphics surface. - /// - /// The x-coordinate of the source location. - /// The y-coordinate of the source location. - /// The x-coordinate of the destination location. - /// The y-coordinate of the destination location. - /// The size of the block to copy. - /// Always thrown as screen capture is not supported. - public void CopyFromScreen(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize) - => throw new PlatformNotSupportedException("Screen capture is not supported in this implementation."); - - // ── DrawImage overloads ────────────────────────────────────────────────── - - /// - /// Draws the specified image at the specified point. - /// - /// The image to draw. - /// The point where the image will be drawn. - public void DrawImage(Image image, Point point) - => DrawImage(image, new Rectangle(point.X, point.Y, image?.Width ?? 0, image?.Height ?? 0)); - - /// - /// Draws the specified image at the specified point. - /// - /// The image to draw. - /// The point where the image will be drawn. - public void DrawImage(Image image, PointF point) - => DrawImage(image, new RectangleF(point.X, point.Y, image?.Width ?? 0, image?.Height ?? 0)); - - /// - /// Draws the specified image at the specified coordinates. - /// - /// The image to draw. - /// The x-coordinate of the location. - /// The y-coordinate of the location. - public void DrawImage(Image image, int x, int y) - => DrawImage(image, new Rectangle(x, y, image?.Width ?? 0, image?.Height ?? 0)); - - /// - /// Draws the specified image at the specified coordinates. - /// - /// The image to draw. - /// The x-coordinate of the location. - /// The y-coordinate of the location. - public void DrawImage(Image image, float x, float y) - => DrawImage(image, new RectangleF(x, y, image?.Width ?? 0, image?.Height ?? 0)); - - /// - /// Draws the specified image scaled to fit the specified rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - public void DrawImage(Image image, Rectangle destRect) - => DrawImage(image, (RectangleF)destRect, - new RectangleF(0, 0, image?.Width ?? 0, image?.Height ?? 0), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified image scaled to fit the specified rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - public void DrawImage(Image image, RectangleF destRect) - => DrawImage(image, destRect, - new RectangleF(0, 0, image?.Width ?? 0, image?.Height ?? 0), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified image transformed to fit the specified array of points. - /// - /// The image to draw. - /// An array of points that define a parallelogram. - public void DrawImage(Image image, Point[] destPoints) - { - if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); - var pts = new PointF[destPoints.Length]; - for (int i = 0; i < destPoints.Length; i++) - pts[i] = new PointF(destPoints[i].X, destPoints[i].Y); - DrawImage(image, pts); - } - - /// - /// Draws the specified image transformed to fit the specified array of points. - /// - /// The image to draw. - /// An array of points that define a parallelogram. - public void DrawImage(Image image, PointF[] destPoints) - => DrawImage(image, destPoints, - new RectangleF(0, 0, image?.Width ?? 0, image?.Height ?? 0), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height), srcUnit, image), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit) - => DrawImage(image, destRect, ToSrcPixelRect(srcRect, srcUnit, image), GraphicsUnit.Pixel, null); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle with the specified attributes. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height), srcUnit, image), - GraphicsUnit.Pixel, imageAttr); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle with the specified attributes. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) - { - ThrowIfDisposed(); - if (image == null) throw new ArgumentNullException(nameof(image)); - DrawImageCore(image, destRect, srcRect, srcUnit, imageAttr); - } - - /// - /// Core implementation that draws a scaled image. Override in a recording - /// surface to capture the command instead of rasterizing. - /// - protected virtual void DrawImageCore(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? imageAttr) - { - bool disposeSrc; - Bitmap src = GetBitmapSource(image, out disposeSrc); - try - { - var d = ToRectangleF(destRect); - var sr = ToSrcPixelRect(srcRect, srcUnit, image); - ImageRenderer.Render(_target!, src, d, sr, GetClipRect(), InterpolationMode, CompositingMode, imageAttr); - } - finally - { - if (disposeSrc) src.Dispose(); - } - } - - /// - /// Draws the specified portion of the image at the specified point. - /// - /// The image to draw. - /// The point where the image will be drawn. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, PointF destPoint, RectangleF srcRect, GraphicsUnit srcUnit) - => DrawImage(image, destPoint, srcRect, srcUnit, null); - - /// - /// Draws the specified portion of the image at the specified point with the specified attributes. - /// - /// The image to draw. - /// The point where the image will be drawn. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, PointF destPoint, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) - => DrawImage(image, new RectangleF(destPoint.X, destPoint.Y, srcRect.Width, srcRect.Height), - srcRect, srcUnit, imageAttr); - - /// - /// Draws the specified portion of the image transformed to fit the specified array of points. - /// - /// The image to draw. - /// An array of points that define a parallelogram. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit) - => DrawImage(image, destPoints, srcRect, srcUnit, null); - - /// - /// Draws the specified portion of the image transformed to fit the specified array of points with the specified attributes. - /// - /// The image to draw. - /// An array of points that define a parallelogram. - /// The portion of the image to draw. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr) - { - ThrowIfDisposed(); - if (image == null) throw new ArgumentNullException(nameof(image)); - if (destPoints == null) throw new ArgumentNullException(nameof(destPoints)); - DrawImageCore(image, destPoints, srcRect, srcUnit, imageAttr); - } - - /// - /// Core implementation that draws an affine-transformed image. Override in - /// a recording surface to capture the command instead of rasterizing. - /// - protected virtual void DrawImageCore(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? imageAttr) - { - bool disposeSrc; - Bitmap src = GetBitmapSource(image, out disposeSrc); - try - { - var pts = ToPointFs(destPoints); - var sr = ToSrcPixelRect(srcRect, srcUnit, image); - ImageRenderer.RenderAffine(_target!, src, pts, sr, GetClipRect(), InterpolationMode, CompositingMode, imageAttr); - } - finally - { - if (disposeSrc) src.Dispose(); - } - } - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The x-coordinate of the source rectangle. - /// The y-coordinate of the source rectangle. - /// The width of the source rectangle. - /// The height of the source rectangle. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, - GraphicsUnit srcUnit) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcX, srcY, srcWidth, srcHeight), srcUnit, image), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle with the specified attributes. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The x-coordinate of the source rectangle. - /// The y-coordinate of the source rectangle. - /// The width of the source rectangle. - /// The height of the source rectangle. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, - GraphicsUnit srcUnit, ImageAttributes? imageAttr) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcX, srcY, srcWidth, srcHeight), srcUnit, image), - GraphicsUnit.Pixel, imageAttr); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The x-coordinate of the source rectangle. - /// The y-coordinate of the source rectangle. - /// The width of the source rectangle. - /// The height of the source rectangle. - /// The unit of measure for the source rectangle. - public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, - GraphicsUnit srcUnit) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcX, srcY, srcWidth, srcHeight), srcUnit, image), - GraphicsUnit.Pixel, null); - - /// - /// Draws the specified portion of the image scaled to fit the specified destination rectangle with the specified attributes. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - /// The x-coordinate of the source rectangle. - /// The y-coordinate of the source rectangle. - /// The width of the source rectangle. - /// The height of the source rectangle. - /// The unit of measure for the source rectangle. - /// The image attributes to use for drawing. - public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, - GraphicsUnit srcUnit, ImageAttributes? imageAttr) - => DrawImage(image, (RectangleF)destRect, - ToSrcPixelRect(new RectangleF(srcX, srcY, srcWidth, srcHeight), srcUnit, image), - GraphicsUnit.Pixel, imageAttr); - - /// - /// Draws the specified image at the specified point without scaling. - /// - /// The image to draw. - /// The point where the image will be drawn. - public void DrawImageUnscaled(Image image, Point point) - { - ThrowIfDisposed(); - if (image == null) throw new ArgumentNullException(nameof(image)); - DrawImage(image, new Rectangle(point.X, point.Y, image.Width, image.Height)); - } - - /// - /// Draws the specified image at the specified point without scaling and clips if necessary. - /// - /// The image to draw. - /// The rectangle that specifies the location and size of the drawn image. - public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) - { - ThrowIfDisposed(); - if (image == null) throw new ArgumentNullException(nameof(image)); - var dst = new Rectangle(rect.X, rect.Y, - Math.Min(rect.Width, image.Width), - Math.Min(rect.Height, image.Height)); - DrawImage(image, dst); - } - - private static Bitmap GetBitmapSource(Image image, out bool disposeAfterUse) - { - if (image is Bitmap bitmap) - { - disposeAfterUse = false; - return bitmap; - } - - if (image is Imaging.Metafile metafile) - { - disposeAfterUse = true; - return metafile.RenderToBitmap(); - } - - throw new NotSupportedException("Only Bitmap and Metafile images are currently supported."); - } - - // ── DrawImage source-rect unit conversion ───────────────────────────── - - private static RectangleF ToSrcPixelRect(RectangleF srcRect, GraphicsUnit srcUnit, Image src) - { - if (srcUnit == GraphicsUnit.Pixel) return srcRect; - float dpiX = src.HorizontalResolution; - float dpiY = src.VerticalResolution; - return new RectangleF( - SrcUnitToPixel(srcRect.X, srcUnit, dpiX), - SrcUnitToPixel(srcRect.Y, srcUnit, dpiY), - SrcUnitToPixel(srcRect.Width, srcUnit, dpiX), - SrcUnitToPixel(srcRect.Height, srcUnit, dpiY)); - } - - private static float SrcUnitToPixel(float value, GraphicsUnit unit, float dpi) - { - switch (unit) - { - case GraphicsUnit.Pixel: return value; - case GraphicsUnit.Point: return value * dpi / 72f; - case GraphicsUnit.Inch: return value * dpi; - case GraphicsUnit.Document: return value * dpi / 300f; - case GraphicsUnit.Millimeter: return value * dpi / 25.4f; - default: return value; - } - } - - /// - /// Gets the nearest color to the specified color. - /// - /// The color to find the nearest match for. - /// The nearest color. - public Color GetNearestColor(Color color) - { - ThrowIfDisposed(); - return color; - } - - /// - /// Determines whether the specified point is visible within the clipping region. - /// - /// The point to check. - /// True if the point is visible; otherwise, false. - public bool IsVisible(PointF point) - { - ThrowIfDisposed(); - return _clip.IsVisible(point, this); - } - - /// - /// Determines whether the specified rectangle is visible within the clipping region. - /// - /// The rectangle to check. - /// True if the rectangle is visible; otherwise, false. - public bool IsVisible(RectangleF rect) - { - ThrowIfDisposed(); - return _clip.IsVisible(rect, this); - } - - // ── Virtual hooks for recording surfaces ────────────────────────────────── - - /// - /// Called after the world transform changes. Override in a recording - /// surface to capture the new transform state. - /// - protected virtual void OnTransformChanged() { } - - /// - /// Called after the clip region changes. Override in a recording - /// surface to capture the new clip state. - /// - protected virtual void OnClipChanged() { } - - /// - /// Called after a rendering hint, page unit, page scale, or rendering - /// origin changes. Override in a recording surface to capture the new value. - /// - /// The new hint value. - protected virtual void OnHintChanged(object hintValue) { } - - /// - /// Releases all resources used by the Graphics object. - /// - public void Dispose() - { - if (_disposed) return; - _disposed = true; - _clip.Dispose(); - _transform.Dispose(); - } - - private GraphicsState CreateState() - => new GraphicsState( - _transform.Clone(), - _clip.Clone(), - PageUnit, - PageScale, - SmoothingMode, - InterpolationMode, - CompositingMode, - CompositingQuality, - PixelOffsetMode, - TextRenderingHint, - _renderingOrigin); - - private void ApplyState(GraphicsState state) - { - ReplaceClip(state.Clip.Clone()); - _transform.Dispose(); - _transform = state.Transform.Clone(); - PageUnit = state.PageUnit; - PageScale = state.PageScale; - SmoothingMode = state.SmoothingMode; - InterpolationMode = state.InterpolationMode; - CompositingMode = state.CompositingMode; - CompositingQuality = state.CompositingQuality; - PixelOffsetMode = state.PixelOffsetMode; - TextRenderingHint = state.TextRenderingHint; - _renderingOrigin = state.RenderingOrigin; - } - - private void ApplyClip(Region region, CombineMode mode) - { - switch (mode) - { - case CombineMode.Replace: - ReplaceClip(region.Clone()); - break; - case CombineMode.Intersect: - _clip.Intersect(region); - break; - case CombineMode.Union: - _clip.Union(region); - break; - case CombineMode.Xor: - _clip.Xor(region); - break; - case CombineMode.Exclude: - _clip.Exclude(region); - break; - case CombineMode.Complement: - _clip.Complement(region); - break; - default: - throw new ArgumentOutOfRangeException(nameof(mode)); - } - } - - private void ReplaceClip(Region newClip) - { - _clip.Dispose(); - _clip = newClip; - } - - private Rectangle? GetClipRect() - { - var r = VisibleClipBounds; - if (r.IsEmpty) return Rectangle.Empty; - - int x = Clamp((int)Math.Floor(r.X), 0, Width); - int y = Clamp((int)Math.Floor(r.Y), 0, Height); - int right = Clamp((int)Math.Ceiling(r.Right), 0, Width); - int bottom = Clamp((int)Math.Ceiling(r.Bottom), 0, Height); - - if (right <= x || bottom <= y) - return Rectangle.Empty; - - return Rectangle.FromLTRB(x, y, right, bottom); - } - - private float ToPixels(float value, GraphicsUnit unit) - { - float px; - switch (unit) - { - case GraphicsUnit.Pixel: - px = value; - break; - case GraphicsUnit.Point: - px = value * DpiX / 72f; - break; - case GraphicsUnit.Inch: - px = value * DpiX; - break; - case GraphicsUnit.Document: - px = value * DpiX / 300f; - break; - case GraphicsUnit.Millimeter: - px = value * DpiX / 25.4f; - break; - default: - px = value; - break; - } - - return px * PageScale; - } - - private PointF ToPointF(float x, float y) - => new PointF(ToPixels(x, PageUnit), ToPixels(y, PageUnit)); - - private PointF ToPointF(PointF p) - => new PointF(ToPixels(p.X, PageUnit), ToPixels(p.Y, PageUnit)); - - private PointF[] ToPointFs(PointF[] points) - { - var arr = new PointF[points.Length]; - for (int i = 0; i < points.Length; i++) - arr[i] = ToPointF(points[i]); - return arr; - } - - private RectangleF ToRectangleF(RectangleF r) - => new RectangleF(ToPixels(r.X, PageUnit), ToPixels(r.Y, PageUnit), ToPixels(r.Width, PageUnit), ToPixels(r.Height, PageUnit)); - - private static int Clamp(int value, int min, int max) - { - if (value < min) return min; - if (value > max) return max; - return value; - } - - private void ThrowIfDisposed() - { - if (_disposed) - throw new ObjectDisposedException(nameof(Graphics)); - } - - // ── DrawString overloads ───────────────────────────────────────────── - - /// - /// Draws the specified text at the specified location with the specified brush and font. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The x-coordinate of the text location. - /// The y-coordinate of the text location. - public void DrawString(string s,Text.Font font, Brush brush, float x, float y) - => DrawStringCore(s, font, brush, - new RectangleF(x, y, 1e7f, 1e7f), - new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Draws the specified text at the specified point with the specified brush and font. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The point representing the text location. - public void DrawString(string s, Text.Font font, Brush brush, PointF point) - => DrawStringCore(s, font, brush, - new RectangleF(point.X, point.Y, 1e7f, 1e7f), - new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Draws the specified text in the specified layout rectangle with the specified brush and font. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The layout rectangle for the text. - public void DrawString(string s, Text.Font font, Brush brush, RectangleF layoutRect) - => DrawStringCore(s, font, brush, layoutRect, null); - - /// - /// Draws the specified text at the specified location with the specified brush, font, and format. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The x-coordinate of the text location. - /// The y-coordinate of the text location. - /// The string format, or null for default. - public void DrawString(string s, Text.Font font, Brush brush, float x, float y, StringFormat? format) - => DrawStringCore(s, font, brush, - new RectangleF(x, y, 1e7f, 1e7f), - format ?? new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Draws the specified text at the specified point with the specified brush, font, and format. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The point representing the text location. - /// The string format, or null for default. - public void DrawString(string s, Text.Font font, Brush brush, PointF point, StringFormat? format) - => DrawStringCore(s, font, brush, - new RectangleF(point.X, point.Y, 1e7f, 1e7f), - format ?? new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Draws the specified text in the specified layout rectangle with the specified brush, font, and format. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The layout rectangle for the text. - /// The string format, or null for default. - public void DrawString(string s, Text.Font font, Brush brush, RectangleF layoutRect, StringFormat? format) - => DrawStringCore(s, font, brush, layoutRect, format); - - protected virtual void DrawStringCore( - string s, - Text.Font font, - Brush brush, - RectangleF layoutRect, - StringFormat? format) - { - ThrowIfDisposed(); - if (string.IsNullOrEmpty(s)) return; - if (font == null) throw new ArgumentNullException(nameof(font)); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - var pixelRect = ToRectangleF(layoutRect); - var lines = TextLayoutEngine.Layout(s, font, pixelRect, format, DpiX, DpiY); - if (lines.Count == 0) return; - - var metrics = font.FontFamily.GetMetricsData(font.Style); - float emPixels = TextLayoutEngine.FontSizeToPixels(font.Size, font.Unit, DpiY); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) - : 1f; - - IFont? fontFace = font.FontFamily.GetFontFace(font.Style); - GlyphOutlineRenderer? renderer = fontFace != null - ? new GlyphOutlineRenderer(fontFace) - : null; - GlyphRasterizer? rasterizer = renderer != null ? new GlyphRasterizer() : null; - - // Decoration metrics (design units → pixels) - float ulY = (float)(metrics.UnderlinePosition * emScale); // typically negative (below baseline) - float ulH = Math.Max(1f, (float)(metrics.UnderlineThickness * emScale)); - float soY = (float)(metrics.StrikeoutPosition * emScale); // typically positive (above baseline) - float soH = Math.Max(1f, (float)(metrics.StrikeoutSize * emScale)); - - float firstTabOffset; - float[] tabStops = (format ?? StringFormat.GenericDefault).GetTabStops(out firstTabOffset); - - foreach (var line in lines) - { - foreach (var run in line.Runs) - { - if (renderer != null && rasterizer != null) - { - float curX = run.X; - foreach (char c in run.Text) - { - float adv = TextLayoutEngine.GetCharAdvance( - c, curX - run.X, - fontFace, emScale, emPixels * TextLayoutEngine.DefaultCharWidthFactor, - firstTabOffset, tabStops, emPixels); - - if (c != '\t') - { - var gid = fontFace!.Encoding.DecodeToGid(c); - if (gid != null) - { - using var glyphPath = rasterizer.RenderGlyph( - renderer, gid, emScale, curX, run.Baseline); - if (glyphPath.PointCount > 0) - FillPath(brush, glyphPath); - } - } - - curX += adv; - } - } - - // Underline - if (font.Underline && run.Width > 0f) - { - float ry = run.Baseline - ulY; - using var ulPath = new GraphicsPath(); - ulPath.AddRectangle(new RectangleF(run.X, ry, run.Width, ulH)); - FillPath(brush, ulPath); - } - - // Strikeout - if (font.Strikeout && run.Width > 0f) - { - float ry = run.Baseline - soY; - using var soPath = new GraphicsPath(); - soPath.AddRectangle(new RectangleF(run.X, ry, run.Width, soH)); - FillPath(brush, soPath); - } - } - } - } - - // ── DrawStringOnPath overloads ─────────────────────────────────────── - - /// - /// Draws the specified text along the given baseline path. - /// Each glyph is positioned on the path and rotated to follow the - /// path tangent. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The baseline path along which to lay out the text, in the current page units. - public void DrawStringOnPath(string s, Text.Font font, Brush brush, - Drawing2D.GraphicsPath baselinePath) - => DrawStringOnPath(s, font, brush, baselinePath, null, null); - - /// - /// Draws the specified text along the given baseline path. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The baseline path along which to lay out the text, in the current page units. - /// The string format (only is used), or null for default. - public void DrawStringOnPath(string s, Text.Font font, Brush brush, - Drawing2D.GraphicsPath baselinePath, StringFormat? format) - => DrawStringOnPath(s, font, brush, baselinePath, format, null); - - /// - /// Draws the specified text along the given baseline path. - /// - /// The text to draw. - /// The font to draw with. - /// The brush to draw the text with. - /// The baseline path along which to lay out the text, in the current page units. - /// The string format (only is used), or null for default. - /// Placement options (start offset, perpendicular offset, overflow), or null for defaults. Offsets are in the current page units. - public void DrawStringOnPath(string s, Text.Font font, Brush brush, - Drawing2D.GraphicsPath baselinePath, - StringFormat? format, TextOnPathOptions? options) - { - ThrowIfDisposed(); - if (font == null) throw new ArgumentNullException(nameof(font)); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - if (baselinePath == null) throw new ArgumentNullException(nameof(baselinePath)); - if (string.IsNullOrEmpty(s)) return; - - // Convert page-unit offsets to pixels (consistent with DrawString). - TextOnPathOptions? pixelOptions = options != null - ? new TextOnPathOptions - { - StartOffset = ToPixels(options.StartOffset, PageUnit), - PerpendicularOffset = ToPixels(options.PerpendicularOffset, PageUnit), - Alignment = options.Alignment, - Overflow = options.Overflow, - } - : null; - - GraphicsPath result = TextOnPathLayout.BuildPath( - s, font, baselinePath, format, pixelOptions, DpiX, DpiY); - - if (result.PointCount > 0) - FillPath(brush, result); - } - - // ── MeasureString overloads ────────────────────────────────────────── - - /// - /// Measures the specified text when drawn with the specified font. - /// - /// The text to measure. - /// The font to measure with. - /// The size of the text in pixels. - public SizeF MeasureString(string text, Text.Font font) - => MeasureStringCore(text, font, - new RectangleF(0f, 0f, float.MaxValue / 2f, float.MaxValue / 2f), - new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Measures the specified text when drawn with the specified font within the specified width. - /// - /// The text to measure. - /// The font to measure with. - /// The maximum width in pixels. - /// The size of the text in pixels. - public SizeF MeasureString(string text, Text.Font font, int width) - => MeasureStringCore(text, font, - new RectangleF(0f, 0f, width, float.MaxValue / 2f), - null); - - /// - /// Measures the specified text when drawn with the specified font within the specified layout area. - /// - /// The text to measure. - /// The font to measure with. - /// The layout area in the current page units. - /// The size of the text in pixels. - public SizeF MeasureString(string text, Text.Font font, SizeF layoutArea) - => MeasureStringCore(text, font, - new RectangleF(0f, 0f, - ToPixels(layoutArea.Width, PageUnit), - ToPixels(layoutArea.Height, PageUnit)), - null); - - /// - /// Measures the specified text when drawn with the specified font within the specified layout area and format. - /// - /// The text to measure. - /// The font to measure with. - /// The layout area in the current page units. - /// The string format, or null for default. - /// The size of the text in pixels. - public SizeF MeasureString(string text, Text.Font font, SizeF layoutArea, StringFormat? format) - => MeasureStringCore(text, font, - new RectangleF(0f, 0f, - ToPixels(layoutArea.Width, PageUnit), - ToPixels(layoutArea.Height, PageUnit)), - format); - - /// - /// Measures the specified text when drawn with the specified font at the specified origin and format. - /// - /// The text to measure. - /// The font to measure with. - /// The origin point in the current page units. - /// The string format, or null for default. - /// The size of the text in pixels. - public SizeF MeasureString(string text, Text.Font font, PointF origin, StringFormat? format) - => MeasureStringCore(text, font, - new RectangleF(origin.X, origin.Y, float.MaxValue / 2f, float.MaxValue / 2f), - format ?? new StringFormat(StringFormatFlags.NoWrap)); - - /// - /// Core implementation for measuring text. - /// - /// The text to measure. - /// The font to measure with. - /// The layout rectangle in pixels. - /// The string format, or null for default. - /// The size of the text in pixels. - private SizeF MeasureStringCore( - string text, - Text.Font font, - RectangleF pixelRect, - StringFormat? format) - { - if (string.IsNullOrEmpty(text)) return SizeF.Empty; - if (font == null) throw new ArgumentNullException(nameof(font)); - - var lines = TextLayoutEngine.Layout(text, font, pixelRect, format, DpiX, DpiY); - if (lines.Count == 0) return SizeF.Empty; - - float maxW = 0f; - foreach (var line in lines) - if (line.Width > maxW) maxW = line.Width; - - float totalH = lines.Count * lines[0].LineHeight; - return new SizeF(maxW, totalH); - } - - // ── Rich text methods ─────────────────────────────────────────────── - - public void DrawRichText(string text, RichTextOptions options, Brush defaultBrush, - RectangleF layoutRect) - => DrawRichText(text, options, defaultBrush, layoutRect, null); - - public void DrawRichText(string text, RichTextOptions options, Brush defaultBrush, - RectangleF layoutRect, StringFormat? format) - { - ThrowIfDisposed(); - if (string.IsNullOrEmpty(text)) return; - if (options == null) throw new ArgumentNullException(nameof(options)); - if (defaultBrush == null) throw new ArgumentNullException(nameof(defaultBrush)); - - var pixelRect = ToRectangleF(layoutRect); - var sf = format ?? StringFormat.GenericDefault; - - using var defaultFont = new Text.Font(options.FontFamily, options.EmSize, - options.FontStyle, options.Unit); - var chain = options.Fallback ?? FontFallback; - var runs = RunSegmenter.Segment(text, defaultFont, options, sf, chain); - var lines = TextLayoutEngine.Layout(runs, pixelRect, sf, DpiX, DpiY); - if (lines.Count == 0) return; - - RenderMultiRunLines(lines, defaultBrush, sf); - } - - public SizeF MeasureRichText(string text, RichTextOptions options, SizeF layoutArea) - => MeasureRichText(text, options, layoutArea, null); - - public SizeF MeasureRichText(string text, RichTextOptions options, SizeF layoutArea, - StringFormat? format) - { - if (string.IsNullOrEmpty(text)) return SizeF.Empty; - if (options == null) throw new ArgumentNullException(nameof(options)); - - var pixelRect = new RectangleF(0f, 0f, - ToPixels(layoutArea.Width, PageUnit), - ToPixels(layoutArea.Height, PageUnit)); - var sf = format ?? StringFormat.GenericDefault; - - using var defaultFont = new Text.Font(options.FontFamily, options.EmSize, - options.FontStyle, options.Unit); - var chain = options.Fallback ?? FontFallback; - var runs = RunSegmenter.Segment(text, defaultFont, options, sf, chain); - var lines = TextLayoutEngine.Layout(runs, pixelRect, sf, DpiX, DpiY); - if (lines.Count == 0) return SizeF.Empty; - - float maxW = 0f; - foreach (var line in lines) - if (line.Width > maxW) maxW = line.Width; - - float totalH = 0f; - foreach (var line in lines) - totalH += line.LineHeight; - - return new SizeF(maxW, totalH); - } - - private void RenderMultiRunLines(List lines, Brush defaultBrush, - StringFormat sf) - { - float firstTabOffset; - float[] tabStops = sf.GetTabStops(out firstTabOffset); - - var rendererCache = new Dictionary(); - - foreach (var line in lines) - { - foreach (var run in line.Runs) - { - var fontFace = run.Font.FontFamily.GetFontFace(run.Font.Style); - if (fontFace == null) continue; - - if (!rendererCache.TryGetValue(fontFace, out var cached)) - { - cached = (new GlyphOutlineRenderer(fontFace), new GlyphRasterizer()); - rendererCache[fontFace] = cached; - } - var (renderer, rasterizer) = cached; - - var metrics = run.Font.FontFamily.GetMetricsData(run.Font.Style); - float emPixels = TextLayoutEngine.FontSizeToPixels( - run.Font.Size, run.Font.Unit, DpiY); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) : 1f; - float fallbackW = emPixels * TextLayoutEngine.DefaultCharWidthFactor; - - var brush = run.Brush ?? defaultBrush; - float curX = run.X; - - foreach (char c in run.Text) - { - if (c == '\t' || c == '\r' || c == '\n') continue; - - char renderChar = c; - char mirrored = c; - if (run.IsRTL && BidiMirroring.TryGetMirror(c, out mirrored)) - renderChar = mirrored; - - var gid = fontFace.Encoding.DecodeToGid(renderChar); - if (gid != null) - { - using var glyphPath = rasterizer.RenderGlyph( - renderer, gid, emScale, curX, run.Baseline); - if (glyphPath.PointCount > 0) - FillPath(brush, glyphPath); - } - - curX += TextLayoutEngine.GetCharAdvance(c, curX - run.X, - fontFace, emScale, fallbackW, - firstTabOffset, tabStops, emPixels); - } - - if (run.Font.Underline && run.Width > 0f) - { - float ulY = run.Baseline - (float)(metrics.UnderlinePosition * emScale); - float ulH = Math.Max(1f, (float)(metrics.UnderlineThickness * emScale)); - using var ulPath = new GraphicsPath(); - ulPath.AddRectangle(new RectangleF(run.X, ulY, run.Width, ulH)); - FillPath(brush, ulPath); - } - - if (run.Font.Strikeout && run.Width > 0f) - { - float soY = run.Baseline - (float)(metrics.StrikeoutPosition * emScale); - float soH = Math.Max(1f, (float)(metrics.StrikeoutSize * emScale)); - using var soPath = new GraphicsPath(); - soPath.AddRectangle(new RectangleF(run.X, soY, run.Width, soH)); - FillPath(brush, soPath); - } - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Graphics/IDrawingContext.cs b/src/MiniPdf/Drawing/Graphics/IDrawingContext.cs deleted file mode 100644 index 2add2395..00000000 --- a/src/MiniPdf/Drawing/Graphics/IDrawingContext.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing -{ - /// - /// Primitive drawing-surface contract shared by raster, recording, - /// SVG, and EMF surfaces. Convenience overloads (DrawLine, DrawEllipse, …) - /// are NOT on this interface; they reduce to these primitives. - /// - internal interface IDrawingContext : IDisposable - { - // ── Dimensions / DPI ── - int Width { get; } - int Height { get; } - float DpiX { get; } - float DpiY { get; } - - // ── Rendering state (get/set) ── - Matrix Transform { get; set; } - Region Clip { get; set; } - SmoothingMode SmoothingMode { get; set; } - InterpolationMode InterpolationMode { get; set; } - CompositingMode CompositingMode { get; set; } - CompositingQuality CompositingQuality { get; set; } - PixelOffsetMode PixelOffsetMode { get; set; } - TextRenderingHint TextRenderingHint { get; set; } - GraphicsUnit PageUnit { get; set; } - float PageScale { get; set; } - Point RenderingOrigin { get; set; } - - // ── Transform mutators ── - void ResetTransform(); - void MultiplyTransform(Matrix m, MatrixOrder order = MatrixOrder.Prepend); - void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend); - void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend); - void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend); - - // ── Clip mutators ── - void SetClip(RectangleF rect, CombineMode mode = CombineMode.Replace); - void SetClip(GraphicsPath path, CombineMode mode = CombineMode.Replace); - void SetClip(Region region, CombineMode mode = CombineMode.Replace); - void IntersectClip(RectangleF rect); - void IntersectClip(Region region); - void ExcludeClip(Rectangle rect); - void ExcludeClip(Region region); - void ResetClip(); - void TranslateClip(float dx, float dy); - - // ── State stack ── - GraphicsState Save(); - void Restore(GraphicsState state); - GraphicsContainer BeginContainer(); - GraphicsContainer BeginContainer(RectangleF dst, RectangleF src, GraphicsUnit unit); - void EndContainer(GraphicsContainer container); - - // ── Primitives (everything else reduces to these) ── - void Clear(Color color); - void DrawPath(Pen pen, GraphicsPath path); - void FillPath(Brush brush, GraphicsPath path); - void FillPath(Brush brush, GraphicsPath path, FillMode fillMode); - void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr); - void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr); - void DrawString(string s, Text.Font font, Brush brush, - RectangleF layoutRect, StringFormat? format); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Graphics/RecordingGraphics.cs b/src/MiniPdf/Drawing/Graphics/RecordingGraphics.cs deleted file mode 100644 index c86c5dbb..00000000 --- a/src/MiniPdf/Drawing/Graphics/RecordingGraphics.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; -using MiniSoftware.Drawing.Vector.Commands; - -namespace MiniSoftware.Drawing -{ - /// - /// A surface that records drawing operations into a - /// instead of rasterizing. Same public API - /// as . Reuses all convenience overloads unchanged; - /// only primitives and state hooks are intercepted. - /// - public sealed class RecordingGraphics : Graphics - { - private readonly Vector.VectorScene _scene; - private readonly int _width; - private readonly int _height; - private readonly float _dpiX; - private readonly float _dpiY; - private bool _suppressRecording; - private readonly Dictionary _saveCommands - = new Dictionary(); - - /// - /// Initializes a new bound to the specified scene. - /// - /// The scene to record into. - /// The canvas width. - /// The canvas height. - internal RecordingGraphics(Vector.VectorScene scene, int width, int height) - : base() - { - _scene = scene; - _width = width; - _height = height; - _dpiX = scene.DpiX; - _dpiY = scene.DpiY; - } - - /// - protected override bool IsRecording => true; - - /// - public override int Width => _width; - - /// - public override int Height => _height; - - /// - public override float DpiX => _dpiX; - - /// - public override float DpiY => _dpiY; - - // ── Primitive overrides: record instead of rasterize ────────────────── - - /// - protected override void DrawPathCore(Pen pen, GraphicsPath path) - => _scene.Add(new DrawPathCommand(pen, path)); - - /// - protected override void FillPathCore(Brush brush, GraphicsPath path, FillMode fillMode) - => _scene.Add(new FillPathCommand(brush, path, fillMode)); - - /// - protected override void DrawImageCore(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - => _scene.Add(new DrawImageCommand(image, destRect, srcRect, srcUnit, attr)); - - /// - protected override void DrawImageCore(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - => _scene.Add(new DrawImageAffineCommand(image, destPoints, srcRect, srcUnit, attr)); - - /// - protected override void DrawStringCore(string s, Text.Font font, Brush brush, - RectangleF layoutRect, StringFormat? format) - => _scene.Add(new DrawStringCommand(s, font, brush, layoutRect, format)); - - /// - protected override void ClearCore(Color color) - => _scene.Add(new ClearCommand(color)); - - // ── State hooks: record state commands ───────────────────────────────── - - /// - protected override void OnTransformChanged() - { - if (_suppressRecording) return; - _scene.Add(new SetTransformCommand(Transform)); - } - - /// - protected override void OnClipChanged() - { - if (_suppressRecording) return; - _scene.Add(new SetClipCommand(Clip, CombineMode.Replace)); - } - - /// - protected override void OnHintChanged(object hintValue) - { - if (_suppressRecording) return; - _scene.Add(new SetHintCommand(hintValue)); - } - - // ── State stack: record Save/Restore commands ────────────────────────── - - /// - public override GraphicsState Save() - { - var state = base.Save(); - var cmd = new SaveStateCommand(); - _scene.Add(cmd); - _saveCommands[state] = cmd; - return state; - } - - /// - public override void Restore(GraphicsState graphicsState) - { - if (graphicsState == null) throw new ArgumentNullException(nameof(graphicsState)); - - if (_saveCommands.TryGetValue(graphicsState, out var saveCmd)) - _scene.Add(new RestoreStateCommand(saveCmd)); - - _suppressRecording = true; - try - { - base.Restore(graphicsState); - } - finally - { - _suppressRecording = false; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/AnimationFrame.cs b/src/MiniPdf/Drawing/Imaging/AnimationFrame.cs deleted file mode 100644 index 8d4fe0ef..00000000 --- a/src/MiniPdf/Drawing/Imaging/AnimationFrame.cs +++ /dev/null @@ -1,21 +0,0 @@ -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - internal sealed class AnimationFrame - { - public Rectangle Bounds { get; } - public int DelayMilliseconds { get; set; } - public FrameDisposeMethod DisposeMethod { get; set; } - public FrameBlendMethod BlendMethod { get; set; } - public byte[] Pixels { get; } - - public int Stride => Bounds.Width * 4; - - public AnimationFrame(Rectangle bounds, byte[] pixels) - { - Bounds = bounds; - Pixels = pixels; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/Bitmap.cs b/src/MiniPdf/Drawing/Imaging/Bitmap.cs deleted file mode 100644 index 183f29eb..00000000 --- a/src/MiniPdf/Drawing/Imaging/Bitmap.cs +++ /dev/null @@ -1,721 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Raster image stored as a managed byte array (top-down, BGRA / BGR layout). - /// BMP file I/O is supported natively; other formats throw NotSupportedException. - /// - public sealed class Bitmap : Image - { - internal byte[] _pixels; // length = _height * _stride - internal int _width, _height, _stride; - internal PixelFormat _format; - internal ImageFormat _rawFormat = ImageFormat.MemoryBmp; - - // LockBits support - private GCHandle _lockHandle; - private bool _locked; - - // Multi-frame (animation) support — APNG, animated GIF. - private List? _frames; - private FrameAnimator? _animator; - private byte[]? _defaultPixels; - private int _activeFrame = -1; - private int _loopCount; - - // ── Constructors ──────────────────────────────────────────────────────── - - /// - /// Initializes a new with the specified width and height. - /// - /// The width of the bitmap. - /// The height of the bitmap. - public Bitmap(int width, int height) - : this(width, height, PixelFormat.Format32bppArgb) { } - - /// - /// Initializes a new with the specified width, height, and pixel format. - /// - /// The width of the bitmap. - /// The height of the bitmap. - /// The pixel format of the bitmap. - public Bitmap(int width, int height, PixelFormat format) - { - if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width)); - if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height)); - _width = width; - _height = height; - _format = format; - _stride = CalcStride(width, format); - _pixels = new byte[_height * _stride]; - } - - /// - /// Initializes a new from an external pixel buffer. - /// - /// The width of the bitmap. - /// The height of the bitmap. - /// The stride (bytes per row) of the pixel buffer. - /// The pixel format of the bitmap. - /// A pointer to the pixel buffer. - public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0) - { - if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width)); - if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height)); - _width = width; - _height = height; - _stride = stride; - _format = format; - _pixels = new byte[Math.Abs(stride) * height]; - Marshal.Copy(scan0, _pixels, 0, _pixels.Length); - } - - /// - /// Initializes a new from the specified file. - /// - /// The file to load from. - public Bitmap(string filename) - { - using (var fs = File.OpenRead(filename)) - { - var loaded = Codecs.CodecRegistry.Decode(fs); - CopyLoaded(loaded); - } - } - - /// - /// Initializes a new from the specified stream. - /// - /// The stream to load from. - public Bitmap(Stream stream) - { - var loaded = Codecs.CodecRegistry.Decode(stream); - CopyLoaded(loaded); - } - - /// - /// Initializes a new as a copy of an existing image. - /// - /// The image to copy from. - public Bitmap(Image original) - { - if (original == null) throw new ArgumentNullException(nameof(original)); - _width = original.Width; - _height = original.Height; - _format = PixelFormat.Format32bppArgb; - _stride = CalcStride(_width, _format); - _pixels = new byte[_height * _stride]; - _dpiX = original.HorizontalResolution; - _dpiY = original.VerticalResolution; - - if (original is Bitmap src) - { - CopyFrom(src); - } - else if (original is Metafile metafile) - { - using var rendered = metafile.RenderToBitmap(_width, _height); - CopyFrom(rendered); - } - } - - // Private constructor used by Clone/Load helpers - private Bitmap() { _pixels = Array.Empty(); } - - // ── Properties ────────────────────────────────────────────────────────── - - /// - /// Gets the width of this bitmap in pixels. - /// - public override int Width => _width; - - /// - /// Gets the height of this bitmap in pixels. - /// - public override int Height => _height; - - /// - /// Gets the pixel format of this bitmap. - /// - public override PixelFormat PixelFormat => _format; - - /// - /// Gets the format of this bitmap. - /// - public override ImageFormat RawFormat => _rawFormat; - - /// - /// Gets the flags for this bitmap. - /// - public override int Flags - => (int)(ImageFlags.ColorSpaceRgb | ImageFlags.HasRealDpi | ImageFlags.HasRealPixelSize); - - // ── Multi-frame (animation) ────────────────────────────────────────────── - - internal void SetAnimationFrames(List frames, int loopCount) - { - _frames = frames; - _loopCount = loopCount; - _animator = new FrameAnimator(_width, _height, frames); - _defaultPixels = (byte[])_pixels.Clone(); - _activeFrame = -1; - } - - internal List? GetAnimationFrames() => _frames; - - internal int GetAnimationLoopCount() => _loopCount; - - public override int GetFrameCount(FrameDimension dimension) - { - if (dimension != null && dimension.Equals(FrameDimension.Time) && _frames != null) - return _frames.Count; - return 1; - } - - public override int SelectActiveFrame(FrameDimension dimension, int idx) - { - if (dimension == null || !dimension.Equals(FrameDimension.Time) || _frames == null) - return 0; - - if (idx < 0 || idx >= _frames.Count) - throw new ArgumentOutOfRangeException(nameof(idx)); - - int previous = _activeFrame; - - if (_defaultPixels == null) - _defaultPixels = (byte[])_pixels.Clone(); - - if (idx == _activeFrame) - return previous; - - byte[] composed = _animator!.Compose(idx); - Buffer.BlockCopy(composed, 0, _pixels, 0, Math.Min(composed.Length, _pixels.Length)); - _activeFrame = idx; - - return previous < 0 ? 0 : previous; - } - - // ── Pixel access ───────────────────────────────────────────────────────── - - /// - /// Gets the color of the pixel at the specified coordinates. - /// - /// The x-coordinate of the pixel. - /// The y-coordinate of the pixel. - /// The color of the pixel. - public Color GetPixel(int x, int y) - { - if ((uint)x >= (uint)_width || (uint)y >= (uint)_height) - throw new ArgumentOutOfRangeException(); - - int bpp = GetBytesPerPixel(_format); - int off = y * _stride + x * bpp; - - switch (_format) - { - case PixelFormat.Format32bppArgb: - case PixelFormat.Format32bppRgb: - { - byte b = _pixels[off], g = _pixels[off + 1], - r = _pixels[off + 2], a = _pixels[off + 3]; - return Color.FromArgb(a, r, g, b); - } - case PixelFormat.Format32bppPArgb: - { - byte pb = _pixels[off], pg = _pixels[off + 1], - pr = _pixels[off + 2], a = _pixels[off + 3]; - if (a == 0) return Color.FromArgb(0, 0, 0, 0); - int r = Math.Min(255, (pb * 255) / a); - int g = Math.Min(255, (pg * 255) / a); - int bl = Math.Min(255, (pr * 255) / a); - return Color.FromArgb(a, bl, g, r); - } - case PixelFormat.Format24bppRgb: - { - byte b = _pixels[off], g = _pixels[off + 1], r = _pixels[off + 2]; - return Color.FromArgb(255, r, g, b); - } - case PixelFormat.Format16bppRgb565: - { - int v = _pixels[off] | (_pixels[off + 1] << 8); - int r = ((v >> 11) & 0x1F) * 255 / 31; - int g = ((v >> 5) & 0x3F) * 255 / 63; - int b = ( v & 0x1F) * 255 / 31; - return Color.FromArgb(255, r, g, b); - } - default: - throw new NotSupportedException($"GetPixel not supported for {_format}."); - } - } - - /// - /// Sets the color of the pixel at the specified coordinates. - /// - /// The x-coordinate of the pixel. - /// The y-coordinate of the pixel. - /// The color to set. - public void SetPixel(int x, int y, Color color) - { - if ((uint)x >= (uint)_width || (uint)y >= (uint)_height) - throw new ArgumentOutOfRangeException(); - - int bpp = GetBytesPerPixel(_format); - int off = y * _stride + x * bpp; - - switch (_format) - { - case PixelFormat.Format32bppArgb: - case PixelFormat.Format32bppRgb: - _pixels[off] = color.B; - _pixels[off + 1] = color.G; - _pixels[off + 2] = color.R; - _pixels[off + 3] = color.A; - break; - - case PixelFormat.Format32bppPArgb: - { - byte a = color.A; - _pixels[off] = (byte)(color.B * a / 255); - _pixels[off + 1] = (byte)(color.G * a / 255); - _pixels[off + 2] = (byte)(color.R * a / 255); - _pixels[off + 3] = a; - break; - } - - case PixelFormat.Format24bppRgb: - _pixels[off] = color.B; - _pixels[off + 1] = color.G; - _pixels[off + 2] = color.R; - break; - - default: - throw new NotSupportedException($"SetPixel not supported for {_format}."); - } - } - - // ── LockBits / UnlockBits ─────────────────────────────────────────────── - - /// - /// Locks a rectangular region of the bitmap for pixel access. - /// - /// The region to lock. - /// The lock mode flags. - /// The pixel format to use for the locked data. - /// The locked bitmap data. - public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format) - { - if (_locked) throw new InvalidOperationException("Bitmap is already locked."); - ValidateRect(rect); - - // For same-format lock we pin the original buffer directly. - // For format-converting lock we create a temporary converted buffer. - byte[] buffer; - int stride; - - if (format == _format) - { - buffer = _pixels; - stride = _stride; - } - else - { - // Convert to requested format - buffer = ConvertRegion(rect, format, out stride); - } - - _lockHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); - _locked = true; - - int bpp = GetBytesPerPixel(format); - IntPtr scan0; - - if (format == _format) - { - // Offset within the main buffer - scan0 = IntPtr.Add(_lockHandle.AddrOfPinnedObject(), - rect.Y * _stride + rect.X * bpp); - } - else - { - scan0 = _lockHandle.AddrOfPinnedObject(); - } - - return new BitmapData - { - Width = rect.Width, - Height = rect.Height, - Stride = stride, - PixelFormat = format, - Scan0 = scan0, - Reserved = (format != _format) ? 1 : 0, // flag: converted - }; - } - - /// - /// Unlocks a previously locked region of the bitmap. - /// - /// The locked bitmap data to unlock. - public void UnlockBits(BitmapData bitmapData) - { - if (!_locked) return; - if (_lockHandle.IsAllocated) - _lockHandle.Free(); - _locked = false; - } - - // ── Transparency ──────────────────────────────────────────────────────── - - /// - /// Makes the default color transparent for this bitmap. - /// - public void MakeTransparent() - { - // Use the bottom-left pixel color as the transparent color - if (_width == 0 || _height == 0) return; - MakeTransparent(GetPixel(0, _height - 1)); - } - - /// - /// Makes the specified color transparent for this bitmap. - /// - /// The color to make transparent. - public void MakeTransparent(Color transparentColor) - { - EnsureAlpha(); - uint target = unchecked((uint)transparentColor.ToArgb()) | 0xFF000000u; // ignore source alpha - int bpp = GetBytesPerPixel(_format); - for (int y = 0; y < _height; y++) - for (int x = 0; x < _width; x++) - { - int off = y * _stride + x * bpp; - uint pix = ((uint)_pixels[off + 3] << 24) | ((uint)_pixels[off + 2] << 16) - | ((uint)_pixels[off + 1] << 8) | _pixels[off]; - uint cmp = pix | 0xFF000000u; - if (cmp == target) - _pixels[off + 3] = 0; // set alpha to 0 - } - } - - // ── Clone ──────────────────────────────────────────────────────────────── - - /// - /// Creates an exact copy of this . - /// - /// A new with the same pixel data. - public override Image Clone() => Clone(new Rectangle(0, 0, _width, _height), _format); - - /// - /// Creates a copy of the specified region of this in the specified format. - /// - /// The region to clone. - /// The pixel format for the cloned bitmap. - /// The cloned bitmap. - public Bitmap Clone(Rectangle rect, PixelFormat format) - { - ValidateRect(rect); - var dst = new Bitmap(rect.Width, rect.Height, format); - dst._dpiX = _dpiX; - dst._dpiY = _dpiY; - int srcBpp = GetBytesPerPixel(_format); - int dstBpp = GetBytesPerPixel(format); - for (int y = 0; y < rect.Height; y++) - for (int x = 0; x < rect.Width; x++) - { - var c = GetPixel(rect.X + x, rect.Y + y); - dst.SetPixel(x, y, c); - } - return dst; - } - - // ── RotateFlip ────────────────────────────────────────────────────────── - - /// - /// Rotates and flips the bitmap. - /// - /// The rotation and flip type. - public override void RotateFlip(RotateFlipType rft) - { - int rotations = (int)rft & 3; // 0–3 × 90° CW - bool flipX = ((int)rft & 4) != 0; - - for (int i = 0; i < rotations; i++) - Rotate90CW(); - if (flipX) - FlipHorizontal(); - } - - // ── Save ───────────────────────────────────────────────────────────────── - - /// - /// Saves this bitmap to the specified file. - /// - /// The file name to save to. - public override void Save(string filename) - { - var ext = Path.GetExtension(filename)?.ToLowerInvariant() ?? ".bmp"; - ImageFormat fmt; - switch (ext) - { - case ".png": fmt = ImageFormat.Png; break; - case ".jpg": - case ".jpeg": fmt = ImageFormat.Jpeg; break; - case ".gif": fmt = ImageFormat.Gif; break; - case ".tiff": - case ".tif": fmt = ImageFormat.Tiff; break; - default: fmt = ImageFormat.Bmp; break; - } - Save(filename, fmt); - } - - /// - /// Saves this bitmap to the specified file in the specified format. - /// - /// The file name to save to. - /// The format to save in. - public override void Save(string filename, ImageFormat format) - { - using (var fs = File.Open(filename, FileMode.Create, FileAccess.Write)) - Save(fs, format); - } - - /// - /// Saves this bitmap to the specified stream in the specified format. - /// - /// The stream to save to. - /// The format to save in. - public override void Save(Stream stream, ImageFormat format) - { - Codecs.CodecRegistry.Encode(this, stream, format ?? ImageFormat.Bmp, null); - } - - /// - /// Saves this bitmap to the specified stream in the specified format with encoder parameters. - /// - /// The stream to save to. - /// The format to save in. - /// The encoder parameters. - public override void Save(Stream stream, ImageFormat format, EncoderParameters? encoderParams) - { - Codecs.CodecRegistry.Encode(this, stream, format ?? ImageFormat.Bmp, encoderParams); - } - - // ── GetHbitmap ─────────────────────────────────────────────────────────── - - /// - /// Returns a handle to this bitmap. - /// - /// A handle to the bitmap. - /// This method is not supported on this platform. - public IntPtr GetHbitmap() - => throw new PlatformNotSupportedException("GDI HBITMAP is not supported on this platform."); - - /// - /// Returns a handle to this bitmap with the specified background color. - /// - /// The background color. - /// A handle to the bitmap. - /// This method is not supported on this platform. - public IntPtr GetHbitmap(Color background) - => GetHbitmap(); - - // ── Static factory ─────────────────────────────────────────────────────── - - /// - /// Creates a from the specified file. - /// - /// The file to load from. - /// The loaded bitmap. - public static new Bitmap FromFile(string filename) - => new Bitmap(filename); - - /// - /// Creates a from the specified stream. - /// - /// The stream to load from. - /// The loaded bitmap. - public static new Bitmap FromStream(Stream stream) - => new Bitmap(stream); - - // ── IDisposable ────────────────────────────────────────────────────────── - - /// - /// Releases the unmanaged resources used by this bitmap and optionally releases the managed resources. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected override void Dispose(bool disposing) - { - if (disposing && _locked && _lockHandle.IsAllocated) - _lockHandle.Free(); - base.Dispose(disposing); - } - - // ═══════════════════════════════════════════════════════════════════════ - // Private helpers - // ═══════════════════════════════════════════════════════════════════════ - - internal static int CalcStride(int width, PixelFormat format) - { - int bits = GetBitsPerPixel(format); - return ((width * bits + 31) / 32) * 4; - } - - private void CopyLoaded(Bitmap loaded) - { - _width = loaded._width; - _height = loaded._height; - _stride = loaded._stride; - _format = loaded._format; - _pixels = loaded._pixels; - _dpiX = loaded._dpiX; - _dpiY = loaded._dpiY; - _rawFormat = loaded._rawFormat; - - if (loaded._frames != null) - { - _frames = loaded._frames; - _animator = loaded._animator; - _loopCount = loaded._loopCount; - _defaultPixels = loaded._defaultPixels; - _activeFrame = loaded._activeFrame; - } - } - - internal static int GetBitsPerPixel(PixelFormat format) - { - switch (format) - { - case PixelFormat.Format1bppIndexed: return 1; - case PixelFormat.Format4bppIndexed: return 4; - case PixelFormat.Format8bppIndexed: return 8; - case PixelFormat.Format16bppRgb555: - case PixelFormat.Format16bppRgb565: - case PixelFormat.Format16bppArgb1555: - case PixelFormat.Format16bppGrayScale: return 16; - case PixelFormat.Format24bppRgb: return 24; - case PixelFormat.Format32bppRgb: - case PixelFormat.Format32bppArgb: - case PixelFormat.Format32bppPArgb: return 32; - case PixelFormat.Format48bppRgb: return 48; - case PixelFormat.Format64bppArgb: - case PixelFormat.Format64bppPArgb: return 64; - default: return 32; - } - } - - internal static int GetBytesPerPixel(PixelFormat format) - { - int bits = GetBitsPerPixel(format); - return Math.Max(1, (bits + 7) / 8); - } - - private void ValidateRect(Rectangle rect) - { - if (rect.X < 0 || rect.Y < 0 - || rect.Right > _width - || rect.Bottom > _height) - throw new ArgumentOutOfRangeException(nameof(rect)); - } - - private void EnsureAlpha() - { - if (_format != PixelFormat.Format32bppArgb && - _format != PixelFormat.Format32bppPArgb) - { - // Convert to 32bppArgb - int newStride = CalcStride(_width, PixelFormat.Format32bppArgb); - var newPixels = new byte[_height * newStride]; - for (int y = 0; y < _height; y++) - for (int x = 0; x < _width; x++) - { - var c = GetPixel(x, y); - int off = y * newStride + x * 4; - newPixels[off] = c.B; - newPixels[off + 1] = c.G; - newPixels[off + 2] = c.R; - newPixels[off + 3] = c.A; - } - _pixels = newPixels; - _stride = newStride; - _format = PixelFormat.Format32bppArgb; - } - } - - private void CopyFrom(Bitmap src) - { - for (int y = 0; y < Math.Min(_height, src._height); y++) - for (int x = 0; x < Math.Min(_width, src._width); x++) - SetPixel(x, y, src.GetPixel(x, y)); - } - - private byte[] ConvertRegion(Rectangle rect, PixelFormat format, out int stride) - { - stride = CalcStride(rect.Width, format); - var buf = new byte[rect.Height * stride]; - int dstBpp = GetBytesPerPixel(format); - for (int y = 0; y < rect.Height; y++) - for (int x = 0; x < rect.Width; x++) - { - var c = GetPixel(rect.X + x, rect.Y + y); - int off = y * stride + x * dstBpp; - if (dstBpp >= 4) { buf[off]=c.B; buf[off+1]=c.G; buf[off+2]=c.R; buf[off+3]=c.A; } - else if (dstBpp == 3) { buf[off]=c.B; buf[off+1]=c.G; buf[off+2]=c.R; } - } - return buf; - } - - // ── Rotate 90° clockwise ───────────────────────────────────────────────── - - private void Rotate90CW() - { - // new(nx, ny) = old(H-1-ny, nx) where newW=H, newH=W - int newW = _height, newH = _width; - int newStride = CalcStride(newW, _format); - var newPixels = new byte[newH * newStride]; - int bpp = GetBytesPerPixel(_format); - - for (int y = 0; y < _height; y++) - for (int x = 0; x < _width; x++) - { - int nx = _height - 1 - y; // new x - int ny = x; // new y - int srcOff = y * _stride + x * bpp; - int dstOff = ny * newStride + nx * bpp; - for (int b = 0; b < bpp; b++) - newPixels[dstOff + b] = _pixels[srcOff + b]; - } - - _pixels = newPixels; - _stride = newStride; - (_width, _height) = (newW, newH); - } - - // ── Flip horizontally (mirror left-right) ──────────────────────────────── - - private void FlipHorizontal() - { - int bpp = GetBytesPerPixel(_format); - for (int y = 0; y < _height; y++) - for (int x = 0; x < _width / 2; x++) - { - int x2 = _width - 1 - x; - int srcOff = y * _stride + x * bpp; - int dstOff = y * _stride + x2 * bpp; - for (int b = 0; b < bpp; b++) - { - byte tmp = _pixels[srcOff + b]; - _pixels[srcOff + b] = _pixels[dstOff + b]; - _pixels[dstOff + b] = tmp; - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/BitmapData.cs b/src/MiniPdf/Drawing/Imaging/BitmapData.cs deleted file mode 100644 index 779b1493..00000000 --- a/src/MiniPdf/Drawing/Imaging/BitmapData.cs +++ /dev/null @@ -1,41 +0,0 @@ -using MiniSoftware.Drawing.Enums; -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the attributes of a bitmap used for lock bits operations. - /// - public sealed class BitmapData - { - /// - /// Gets or sets the width of the locked portion of the bitmap in pixels. - /// - public int Width { get; set; } - - /// - /// Gets or sets the height of the locked portion of the bitmap in pixels. - /// - public int Height { get; set; } - - /// - /// Gets or sets the stride (bytes per scan line) of the locked portion of the bitmap. - /// - public int Stride { get; set; } - - /// - /// Gets or sets the pixel format of the locked portion of the bitmap. - /// - public PixelFormat PixelFormat { get; set; } - - /// - /// Gets or sets a pointer to the beginning of the scan line data. - /// - public IntPtr Scan0 { get; set; } - - /// - /// Gets or sets the reserved value (reserved for future use). - /// - public int Reserved { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ColorAdjustType.cs b/src/MiniPdf/Drawing/Imaging/ColorAdjustType.cs deleted file mode 100644 index b756f3b1..00000000 --- a/src/MiniPdf/Drawing/Imaging/ColorAdjustType.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the type of color adjustment for image attributes. - /// - public enum ColorAdjustType - { - /// - /// Default color adjustment type. - /// - Default = 0, - - /// - /// Bitmap color adjustment. - /// - Bitmap = 1, - - /// - /// Brush color adjustment. - /// - Brush = 2, - - /// - /// Pen color adjustment. - /// - Pen = 3, - - /// - /// Text color adjustment. - /// - Text = 4, - - /// - /// Count of color adjustment types. - /// - Count = 5, - - /// - /// Any color adjustment type. - /// - Any = 6, - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ColorMap.cs b/src/MiniPdf/Drawing/Imaging/ColorMap.cs deleted file mode 100644 index 1259eccf..00000000 --- a/src/MiniPdf/Drawing/Imaging/ColorMap.cs +++ /dev/null @@ -1,20 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Maps one color to another during image rendering. - /// - public sealed class ColorMap - { - /// - /// Gets or sets the source color to map from. - /// - public Color OldColor { get; set; } - - /// - /// Gets or sets the destination color to map to. - /// - public Color NewColor { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ColorMatrix.cs b/src/MiniPdf/Drawing/Imaging/ColorMatrix.cs deleted file mode 100644 index a778e6f6..00000000 --- a/src/MiniPdf/Drawing/Imaging/ColorMatrix.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// A 5×5 float matrix that defines a linear transformation applied to every pixel's - /// (R, G, B, A, W) tuple during image rendering. Row 4 (W) is the bias / translation row. - /// Column order is R, G, B, A, W. - /// - public sealed class ColorMatrix - { - private readonly float[,] _m; - - /// - /// Initializes a new with an identity matrix. - /// - public ColorMatrix() - { - _m = new float[5, 5]; - // identity - _m[0, 0] = _m[1, 1] = _m[2, 2] = _m[3, 3] = _m[4, 4] = 1f; - } - - /// - /// Initializes a new from a 2D float array. - /// - /// The matrix values. - public ColorMatrix(float[][] newColorMatrix) - { - if (newColorMatrix == null) throw new ArgumentNullException(nameof(newColorMatrix)); - _m = new float[5, 5]; - for (int r = 0; r < 5 && r < newColorMatrix.Length; r++) - for (int c = 0; c < 5 && c < newColorMatrix[r].Length; c++) - _m[r, c] = newColorMatrix[r][c]; - } - - /// - /// Gets or sets the matrix element at the specified row and column. - /// - /// The row index (0-4). - /// The column index (0-4). - /// The matrix value. - public float this[int row, int col] - { - get => _m[row, col]; - set => _m[row, col] = value; - } - - // Named properties (GDI+ API compatibility) - /// - /// Gets or sets the matrix element at row 0, column 0. - /// - public float Matrix00 { get => _m[0, 0]; set => _m[0, 0] = value; } - - /// - /// Gets or sets the matrix element at row 0, column 1. - /// - public float Matrix01 { get => _m[0, 1]; set => _m[0, 1] = value; } - - /// - /// Gets or sets the matrix element at row 0, column 2. - /// - public float Matrix02 { get => _m[0, 2]; set => _m[0, 2] = value; } - - /// - /// Gets or sets the matrix element at row 0, column 3. - /// - public float Matrix03 { get => _m[0, 3]; set => _m[0, 3] = value; } - - /// - /// Gets or sets the matrix element at row 0, column 4. - /// - public float Matrix04 { get => _m[0, 4]; set => _m[0, 4] = value; } - - /// - /// Gets or sets the matrix element at row 1, column 0. - /// - public float Matrix10 { get => _m[1, 0]; set => _m[1, 0] = value; } - - /// - /// Gets or sets the matrix element at row 1, column 1. - /// - public float Matrix11 { get => _m[1, 1]; set => _m[1, 1] = value; } - - /// - /// Gets or sets the matrix element at row 1, column 2. - /// - public float Matrix12 { get => _m[1, 2]; set => _m[1, 2] = value; } - - /// - /// Gets or sets the matrix element at row 1, column 3. - /// - public float Matrix13 { get => _m[1, 3]; set => _m[1, 3] = value; } - - /// - /// Gets or sets the matrix element at row 1, column 4. - /// - public float Matrix14 { get => _m[1, 4]; set => _m[1, 4] = value; } - - /// - /// Gets or sets the matrix element at row 2, column 0. - /// - public float Matrix20 { get => _m[2, 0]; set => _m[2, 0] = value; } - - /// - /// Gets or sets the matrix element at row 2, column 1. - /// - public float Matrix21 { get => _m[2, 1]; set => _m[2, 1] = value; } - - /// - /// Gets or sets the matrix element at row 2, column 2. - /// - public float Matrix22 { get => _m[2, 2]; set => _m[2, 2] = value; } - - /// - /// Gets or sets the matrix element at row 2, column 3. - /// - public float Matrix23 { get => _m[2, 3]; set => _m[2, 3] = value; } - - /// - /// Gets or sets the matrix element at row 2, column 4. - /// - public float Matrix24 { get => _m[2, 4]; set => _m[2, 4] = value; } - - /// - /// Gets or sets the matrix element at row 3, column 0. - /// - public float Matrix30 { get => _m[3, 0]; set => _m[3, 0] = value; } - - /// - /// Gets or sets the matrix element at row 3, column 1. - /// - public float Matrix31 { get => _m[3, 1]; set => _m[3, 1] = value; } - - /// - /// Gets or sets the matrix element at row 3, column 2. - /// - public float Matrix32 { get => _m[3, 2]; set => _m[3, 2] = value; } - - /// - /// Gets or sets the matrix element at row 3, column 3. - /// - public float Matrix33 { get => _m[3, 3]; set => _m[3, 3] = value; } - - /// - /// Gets or sets the matrix element at row 3, column 4. - /// - public float Matrix34 { get => _m[3, 4]; set => _m[3, 4] = value; } - - /// - /// Gets or sets the matrix element at row 4, column 0. - /// - public float Matrix40 { get => _m[4, 0]; set => _m[4, 0] = value; } - - /// - /// Gets or sets the matrix element at row 4, column 1. - /// - public float Matrix41 { get => _m[4, 1]; set => _m[4, 1] = value; } - - /// - /// Gets or sets the matrix element at row 4, column 2. - /// - public float Matrix42 { get => _m[4, 2]; set => _m[4, 2] = value; } - - /// - /// Gets or sets the matrix element at row 4, column 3. - /// - public float Matrix43 { get => _m[4, 3]; set => _m[4, 3] = value; } - - /// - /// Gets or sets the matrix element at row 4, column 4. - /// - public float Matrix44 { get => _m[4, 4]; set => _m[4, 4] = value; } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ColorMatrixFlag.cs b/src/MiniPdf/Drawing/Imaging/ColorMatrixFlag.cs deleted file mode 100644 index 524e67d5..00000000 --- a/src/MiniPdf/Drawing/Imaging/ColorMatrixFlag.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the flags for color matrix operations. - /// - public enum ColorMatrixFlag - { - /// - /// Default color matrix behavior. - /// - Default = 0, - - /// - /// Skip grayscale colors. - /// - SkipGrays = 1, - - /// - /// Use alternate grayscale. - /// - AltGray = 2, - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ColorPalette.cs b/src/MiniPdf/Drawing/Imaging/ColorPalette.cs deleted file mode 100644 index 28ce8416..00000000 --- a/src/MiniPdf/Drawing/Imaging/ColorPalette.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Colors; -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Defines an array of colors that make up a color palette. - /// - public sealed class ColorPalette - { - /// - /// Gets or sets the array of colors in the palette. - /// - public Color[] Entries { get; set; } - - /// - /// Gets or sets the flags for the palette. - /// - public int Flags { get; set; } - - /// - /// Initializes a new with an empty entries array. - /// - public ColorPalette() - { - Entries = Array.Empty(); - } - - /// - /// Initializes a new with the specified flags and entries. - /// - /// The palette flags. - /// The color entries for the palette. - public ColorPalette(int flags, Color[] entries) - { - Flags = flags; - Entries = entries ?? Array.Empty(); - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/Cursor.cs b/src/MiniPdf/Drawing/Imaging/Cursor.cs deleted file mode 100644 index a420ee0b..00000000 --- a/src/MiniPdf/Drawing/Imaging/Cursor.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Codecs; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Represents a mouse cursor, optionally loaded from a .cur or .ico file. - /// The hotspot is extracted from CUR directory entries; ICO files default to (0, 0). - /// - public sealed class Cursor : IDisposable - { - private Bitmap _bitmap; - private Point _hotSpot; - private bool _disposed; - - // ── Constructors ───────────────────────────────────────────────────────── - - /// - /// Initializes a new from the specified file. - /// - /// The path to the cursor file (.cur or .ico). - public Cursor(string fileName) - { - if (fileName == null) throw new ArgumentNullException(nameof(fileName)); - using var fs = File.OpenRead(fileName); - (_bitmap, _hotSpot) = LoadFromStream(fs); - } - - /// - /// Initializes a new from the specified stream. - /// - /// The stream containing cursor data. - public Cursor(Stream stream) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - (_bitmap, _hotSpot) = LoadFromStream(stream); - } - - /// - /// Initializes a new with the specified bitmap and hotspot. - /// - /// The bitmap that represents the cursor. - /// The hotspot point of the cursor. - internal Cursor(Bitmap bitmap, Point hotSpot) - { - _bitmap = bitmap ?? throw new ArgumentNullException(nameof(bitmap)); - _hotSpot = hotSpot; - } - - // ── Properties ─────────────────────────────────────────────────────────── - - /// - /// Gets the size of the cursor. - /// - public Size Size => new Size(_bitmap.Width, _bitmap.Height); - - /// - /// Gets the hotspot point of the cursor. - /// - public Point HotSpot => _hotSpot; - - // Default cursor — initialized before Current so the auto-property is non-null. - private static readonly Cursor s_default = - new Cursor(new Bitmap(1, 1, PixelFormat.Format32bppArgb), Point.Empty); - - /// - /// Returns a default 1×1 transparent cursor. - /// Setting the cursor is a no-op in the pure-managed implementation. - /// - public static Cursor Current { get; set; } = s_default; - - // ── Draw ───────────────────────────────────────────────────────────────── - - /// Draws the cursor image into . - public void Draw(Graphics g, Rectangle targetRect) - { - ThrowIfDisposed(); - if (g == null) throw new ArgumentNullException(nameof(g)); - g.DrawImage(_bitmap, targetRect); - } - - /// Draws the cursor stretched to fill . - public void DrawStretched(Graphics g, Rectangle targetRect) => Draw(g, targetRect); - - // ── IDisposable ────────────────────────────────────────────────────────── - - /// - /// Releases all resources used by this . - /// - public void Dispose() - { - if (!_disposed) - { - _bitmap.Dispose(); - _disposed = true; - } - } - - // ── Private helpers ────────────────────────────────────────────────────── - - private static (Bitmap bitmap, Point hotSpot) LoadFromStream(Stream stream) - { - // Buffer the whole stream so we can inspect and optionally patch the header. - byte[] data; - if (stream.CanSeek && stream.Length - stream.Position < int.MaxValue) - { - int len = (int)(stream.Length - stream.Position); - data = new byte[len]; - int read = 0; - while (read < len) - { - int n = stream.Read(data, read, len - read); - if (n == 0) break; - read += n; - } - } - else - { - using var ms = new MemoryStream(); - stream.CopyTo(ms); - data = ms.ToArray(); - } - - Point hotSpot = Point.Empty; - - // CUR file: ICONDIR type == 2; hotspot in ICONDIRENTRY[0] at offsets 10–13. - if (data.Length >= 14 - && data[0] == 0 && data[1] == 0 - && data[2] == 2 && data[3] == 0) - { - int hx = data[10] | (data[11] << 8); - int hy = data[12] | (data[13] << 8); - hotSpot = new Point(hx, hy); - - // Patch type field to 1 (ICO) so the existing IcoCodec can decode it. - data[2] = 1; - } - - using var buf = new MemoryStream(data); - var bitmap = CodecRegistry.Decode(buf); - return (bitmap, hotSpot); - } - - private void ThrowIfDisposed() - { - if (_disposed) throw new ObjectDisposedException(nameof(Cursor)); - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/EmfType.cs b/src/MiniPdf/Drawing/Imaging/EmfType.cs deleted file mode 100644 index 6ab875b1..00000000 --- a/src/MiniPdf/Drawing/Imaging/EmfType.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the type of Enhanced Metafile (EMF) to create. - /// - public enum EmfType - { - /// - /// Enhanced Metafile only (no EMF+). - /// - EmfOnly, - - /// - /// EMF+ only (no original EMF records). - /// - EmfPlusOnly, - - /// - /// Both EMF and EMF+ records. - /// - EmfPlusDual, - } -} diff --git a/src/MiniPdf/Drawing/Imaging/Encoder.cs b/src/MiniPdf/Drawing/Imaging/Encoder.cs deleted file mode 100644 index d7e80420..00000000 --- a/src/MiniPdf/Drawing/Imaging/Encoder.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Identifies an image encoder parameter category. - /// - public sealed class Encoder - { - /// - /// Gets the GUID of this encoder. - /// - public Guid Guid { get; } - - private Encoder(string guid) { Guid = new Guid(guid); } - - /// - /// Gets the compression encoder. - /// - public static readonly Encoder Compression = new Encoder("e09d739d-ccd4-44ee-8eba-3fbef14a6159"); - - /// - /// Gets the color depth encoder. - /// - public static readonly Encoder ColorDepth = new Encoder("66087055-ad66-4c7c-9a18-38a2310b8337"); - - /// - /// Gets the scan method encoder. - /// - public static readonly Encoder ScanMethod = new Encoder("3a4e2661-3109-4e56-8536-42c156e7dcfa"); - - /// - /// Gets the version encoder. - /// - public static readonly Encoder Version = new Encoder("24d18c76-814a-41a4-bf53-1c219cccf797"); - - /// - /// Gets the render method encoder. - /// - public static readonly Encoder RenderMethod = new Encoder("6d42c53a-229a-4825-8bb7-5c99e2b9a8b8"); - - /// - /// Gets the quality encoder. - /// - public static readonly Encoder Quality = new Encoder("1d5be4b5-fa4a-452d-9cdd-5db35105e7eb"); - - /// - /// Gets the transformation encoder. - /// - public static readonly Encoder Transformation = new Encoder("8d0eb2d1-a58e-4ea8-aa14-108074b7b6f9"); - - /// - /// Gets the luminance table encoder. - /// - public static readonly Encoder LuminanceTable = new Encoder("edb33bce-0266-4a77-b904-27216099e717"); - - /// - /// Gets the chrominance table encoder. - /// - public static readonly Encoder ChrominanceTable = new Encoder("f2e455dc-09b3-4316-8260-676ada32481c"); - - /// - /// Gets the save flag encoder. - /// - public static readonly Encoder SaveFlag = new Encoder("292266fc-ac40-47bf-8cfc-a85b89a655de"); - } -} diff --git a/src/MiniPdf/Drawing/Imaging/EncoderParameter.cs b/src/MiniPdf/Drawing/Imaging/EncoderParameter.cs deleted file mode 100644 index a5b02b7a..00000000 --- a/src/MiniPdf/Drawing/Imaging/EncoderParameter.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Represents a single parameter for an image encoder. - /// - public sealed class EncoderParameter : IDisposable - { - /// - /// Gets or sets the encoder GUID for this parameter. - /// - public Guid Encoder { get; set; } - - /// - /// Gets or sets the number of values in this parameter. - /// - public int NumberOfValues { get; set; } - - /// - /// Gets or sets the type of the parameter value. - /// - public int Type { get; set; } - - // Internal storage for common value types - internal long _valueLong; - internal byte[] _valueBytes = Array.Empty(); - - /// - /// Initializes a new with a long value. - /// - /// The encoder for this parameter. - /// The long value. - public EncoderParameter(Encoder encoder, long value) - { - if (encoder == null) throw new ArgumentNullException(nameof(encoder)); - Encoder = encoder.Guid; - NumberOfValues = 1; - Type = 4; // ValueTypeLong - _valueLong = value; - } - - /// - /// Initializes a new with a byte array value. - /// - /// The encoder for this parameter. - /// The byte array value. - public EncoderParameter(Encoder encoder, byte[] value) - { - if (encoder == null) throw new ArgumentNullException(nameof(encoder)); - Encoder = encoder.Guid; - NumberOfValues = value?.Length ?? 0; - Type = 1; // ValueTypeByte - _valueBytes = value ?? Array.Empty(); - } - - /// - /// Releases resources used by the . - /// - public void Dispose() { } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/EncoderParameters.cs b/src/MiniPdf/Drawing/Imaging/EncoderParameters.cs deleted file mode 100644 index d513a7c0..00000000 --- a/src/MiniPdf/Drawing/Imaging/EncoderParameters.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Contains a collection of objects for image encoding. - /// - public sealed class EncoderParameters : IDisposable - { - /// - /// Gets or sets the array of encoder parameters. - /// - public EncoderParameter[] Param { get; set; } - - /// - /// Initializes a new with an empty parameter array. - /// - public EncoderParameters() { Param = Array.Empty(); } - - /// - /// Initializes a new with the specified capacity. - /// - /// The number of parameters to allocate space for. - public EncoderParameters(int count) { Param = new EncoderParameter[count]; } - - /// - /// Releases resources used by the . - /// - public void Dispose() { } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/FrameAnimator.cs b/src/MiniPdf/Drawing/Imaging/FrameAnimator.cs deleted file mode 100644 index b00787f7..00000000 --- a/src/MiniPdf/Drawing/Imaging/FrameAnimator.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - internal sealed class FrameAnimator - { - private readonly int _canvasWidth; - private readonly int _canvasHeight; - private readonly int _canvasStride; - private readonly List _frames; - - private readonly byte[] _output; - private readonly byte[] _previous; - private int _lastComposedIndex = -1; - - public FrameAnimator(int canvasWidth, int canvasHeight, List frames) - { - _canvasWidth = canvasWidth; - _canvasHeight = canvasHeight; - _canvasStride = canvasWidth * 4; - _frames = frames; - _output = new byte[canvasHeight * _canvasStride]; - _previous = new byte[canvasHeight * _canvasStride]; - } - - public byte[] Compose(int targetIndex) - { - if (targetIndex < 0 || targetIndex >= _frames.Count) - throw new ArgumentOutOfRangeException(nameof(targetIndex)); - - if (targetIndex < _lastComposedIndex) - { - Array.Clear(_output, 0, _output.Length); - _lastComposedIndex = -1; - } - - for (int i = _lastComposedIndex + 1; i <= targetIndex; i++) - { - var frame = _frames[i]; - - if (frame.DisposeMethod == FrameDisposeMethod.Previous) - SnapshotRegion(_output, _previous, frame.Bounds); - - if (frame.BlendMethod == FrameBlendMethod.Source) - BlendSource(_output, frame); - else - BlendOver(_output, frame); - - if (i < targetIndex) - ApplyDispose(_output, frame); - } - - _lastComposedIndex = targetIndex; - return _output; - } - - private void BlendSource(byte[] canvas, AnimationFrame frame) - { - var b = frame.Bounds; - int frameStride = frame.Stride; - byte[] src = frame.Pixels; - for (int y = 0; y < b.Height; y++) - { - int srcOff = y * frameStride; - int dstOff = (b.Y + y) * _canvasStride + b.X * 4; - Buffer.BlockCopy(src, srcOff, canvas, dstOff, b.Width * 4); - } - } - - private void BlendOver(byte[] canvas, AnimationFrame frame) - { - var b = frame.Bounds; - int frameStride = frame.Stride; - byte[] src = frame.Pixels; - for (int y = 0; y < b.Height; y++) - { - int srcOff = y * frameStride; - int dstOff = (b.Y + y) * _canvasStride + b.X * 4; - for (int x = 0; x < b.Width; x++) - { - int s = srcOff + x * 4; - int d = dstOff + x * 4; - byte sa = src[s + 3]; - if (sa == 0) continue; - if (sa == 255) - { - canvas[d] = src[s]; - canvas[d + 1] = src[s + 1]; - canvas[d + 2] = src[s + 2]; - canvas[d + 3] = src[s + 3]; - continue; - } - int inv = 255 - sa; - canvas[d] = (byte)((src[s] * sa + canvas[d] * inv) / 255); - canvas[d + 1] = (byte)((src[s + 1] * sa + canvas[d + 1] * inv) / 255); - canvas[d + 2] = (byte)((src[s + 2] * sa + canvas[d + 2] * inv) / 255); - canvas[d + 3] = (byte)(sa + canvas[d + 3] * inv / 255); - } - } - } - - private void ApplyDispose(byte[] canvas, AnimationFrame frame) - { - var b = frame.Bounds; - switch (frame.DisposeMethod) - { - case FrameDisposeMethod.None: - break; - case FrameDisposeMethod.Background: - for (int y = 0; y < b.Height; y++) - { - int off = (b.Y + y) * _canvasStride + b.X * 4; - Array.Clear(canvas, off, b.Width * 4); - } - break; - case FrameDisposeMethod.Previous: - RestoreRegion(_previous, canvas, frame.Bounds); - break; - } - } - - private void SnapshotRegion(byte[] src, byte[] dst, Rectangle b) - { - for (int y = 0; y < b.Height; y++) - { - int off = (b.Y + y) * _canvasStride + b.X * 4; - Buffer.BlockCopy(src, off, dst, off, b.Width * 4); - } - } - - private void RestoreRegion(byte[] src, byte[] dst, Rectangle b) - { - for (int y = 0; y < b.Height; y++) - { - int off = (b.Y + y) * _canvasStride + b.X * 4; - Buffer.BlockCopy(src, off, dst, off, b.Width * 4); - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/FrameBlendMethod.cs b/src/MiniPdf/Drawing/Imaging/FrameBlendMethod.cs deleted file mode 100644 index 3f17f2a8..00000000 --- a/src/MiniPdf/Drawing/Imaging/FrameBlendMethod.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - internal enum FrameBlendMethod - { - Source = 0, - Over = 1 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/FrameDimension.cs b/src/MiniPdf/Drawing/Imaging/FrameDimension.cs deleted file mode 100644 index 5c096660..00000000 --- a/src/MiniPdf/Drawing/Imaging/FrameDimension.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Provides properties that represent dimensions of an image, such as page number or time. - /// - public sealed class FrameDimension - { - /// - /// Gets the GUID that identifies this frame dimension. - /// - public Guid Guid { get; } - - private FrameDimension(string guid) { Guid = new Guid(guid); } - - /// - /// Gets the time dimension for multi-frame images. - /// - public static readonly FrameDimension Time = new FrameDimension("6aedbd6d-3fb5-418a-83a6-7f45229dc872"); - - /// - /// Gets the resolution dimension for multi-frame images. - /// - public static readonly FrameDimension Resolution = new FrameDimension("84236f7b-3bd3-428f-8dab-4ea1439ca315"); - - /// - /// Gets the page dimension for multi-frame images. - /// - public static readonly FrameDimension Page = new FrameDimension("7462dc86-6180-4c7e-8e3f-ee7333a7a483"); - - /// - /// Determines whether the specified object is equal to this . - /// - public override bool Equals(object? obj) => obj is FrameDimension fd && fd.Guid == Guid; - - /// - /// Serves as a hash function for this . - /// - public override int GetHashCode() => Guid.GetHashCode(); - - /// - /// Returns a string representation of this . - /// - public override string ToString() => Guid.ToString(); - } -} diff --git a/src/MiniPdf/Drawing/Imaging/FrameDisposeMethod.cs b/src/MiniPdf/Drawing/Imaging/FrameDisposeMethod.cs deleted file mode 100644 index fe9a6445..00000000 --- a/src/MiniPdf/Drawing/Imaging/FrameDisposeMethod.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - internal enum FrameDisposeMethod - { - None = 0, - Background = 1, - Previous = 2 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/Icon.cs b/src/MiniPdf/Drawing/Imaging/Icon.cs deleted file mode 100644 index 98ba9c62..00000000 --- a/src/MiniPdf/Drawing/Imaging/Icon.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Codecs; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Represents a Windows icon (.ico) as a managed . - /// Loading is performed by ; saving writes a single-frame - /// PNG-compressed ICO container. - /// - public sealed class Icon : IDisposable - { - private Bitmap _bitmap; - private bool _disposed; - - // ── Internal constructor (SystemIcons stubs) ───────────────────────────── - - internal Icon(Bitmap bitmap) - { - _bitmap = bitmap ?? throw new ArgumentNullException(nameof(bitmap)); - } - - // ── Public constructors ────────────────────────────────────────────────── - - /// - /// Initializes a new from the specified file. - /// - /// The path to the icon file. - public Icon(string filename) - { - if (filename == null) throw new ArgumentNullException(nameof(filename)); - using var fs = File.OpenRead(filename); - _bitmap = CodecRegistry.Decode(fs); - } - - /// - /// Initializes a new from the specified stream. - /// - /// The stream containing icon data. - public Icon(Stream stream) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - _bitmap = CodecRegistry.Decode(stream); - } - - /// - /// Initializes a new as a copy of the specified icon with the specified dimensions. - /// - /// The original icon to copy. - /// The width of the new icon. - /// The height of the new icon. - public Icon(Icon original, int width, int height) - { - if (original == null) throw new ArgumentNullException(nameof(original)); - original.ThrowIfDisposed(); - // Clone the backing bitmap (resize is deferred to post-v1). - _bitmap = (Bitmap)original._bitmap.Clone(); - } - - /// - /// Initializes a new as a copy of the specified icon with the specified size. - /// - /// The original icon to copy. - /// The size of the new icon. - public Icon(Icon original, Size size) : this(original, size.Width, size.Height) { } - - // ── Properties ─────────────────────────────────────────────────────────── - - /// - /// Gets the width of the icon. - /// - public int Width => _bitmap.Width; - - /// - /// Gets the height of the icon. - /// - public int Height => _bitmap.Height; - - /// - /// Gets the size of the icon. - /// - public Size Size => new Size(Width, Height); - - // ── Static factory ─────────────────────────────────────────────────────── - - /// Not supported on this platform. - public static Icon FromHandle(IntPtr handle) - => throw new PlatformNotSupportedException("Icon.FromHandle is not supported on this platform."); - - /// Returns null; OS-level association lookup is not available. - public static Icon? ExtractAssociatedIcon(string filePath) => null; - - // ── Operations ─────────────────────────────────────────────────────────── - - /// Returns a new copied from this icon's pixels. - public Bitmap ToBitmap() - { - ThrowIfDisposed(); - return (Bitmap)_bitmap.Clone(); - } - - /// - /// Writes this icon to as a single-frame - /// PNG-compressed ICO container. - /// - public void Save(Stream outputStream) - { - ThrowIfDisposed(); - if (outputStream == null) throw new ArgumentNullException(nameof(outputStream)); - - // Encode the bitmap as PNG first, then wrap it in an ICO container. - var pngBuf = new MemoryStream(); - _bitmap.Save(pngBuf, ImageFormat.Png); - byte[] png = pngBuf.ToArray(); - - int dataOffset = 6 + 16; // ICONDIR(6) + one ICONDIRENTRY(16) - int w = Math.Min(Width, 255); - int h = Math.Min(Height, 255); - - // ICONDIR (6 bytes) - outputStream.WriteByte(0); outputStream.WriteByte(0); // reserved - outputStream.WriteByte(1); outputStream.WriteByte(0); // type = 1 (ICO) - outputStream.WriteByte(1); outputStream.WriteByte(0); // count = 1 - - // ICONDIRENTRY (16 bytes) - outputStream.WriteByte((byte)(w == 256 ? 0 : w)); - outputStream.WriteByte((byte)(h == 256 ? 0 : h)); - outputStream.WriteByte(0); // color count - outputStream.WriteByte(0); // reserved - outputStream.WriteByte(1); outputStream.WriteByte(0); // planes - outputStream.WriteByte(32); outputStream.WriteByte(0); // bpp - WriteInt32LE(outputStream, png.Length); - WriteInt32LE(outputStream, dataOffset); - - // PNG payload - outputStream.Write(png, 0, png.Length); - } - - // ── IDisposable ────────────────────────────────────────────────────────── - - /// - /// Releases all resources used by this . - /// - public void Dispose() - { - if (!_disposed) - { - _bitmap.Dispose(); - _disposed = true; - } - } - - // ── Private helpers ────────────────────────────────────────────────────── - - private static void WriteInt32LE(Stream s, int value) - { - s.WriteByte((byte)( value & 0xFF)); - s.WriteByte((byte)((value >> 8) & 0xFF)); - s.WriteByte((byte)((value >> 16) & 0xFF)); - s.WriteByte((byte)((value >> 24) & 0xFF)); - } - - private void ThrowIfDisposed() - { - if (_disposed) throw new ObjectDisposedException(nameof(Icon)); - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/Image.cs b/src/MiniPdf/Drawing/Imaging/Image.cs deleted file mode 100644 index 5b36b464..00000000 --- a/src/MiniPdf/Drawing/Imaging/Image.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - /// Callback used by GetThumbnailImage. - public delegate bool GetThumbnailImageAbort(); - - /// - /// Abstract base class for raster and vector images. - /// Full save/load codecs are added in later batches; BMP I/O is available in Batch 6. - /// - public abstract class Image : IDisposable - { - // Resolution (pixels per inch); subclasses may override. - internal float _dpiX = 96f; - internal float _dpiY = 96f; - - // ── Dimensions ─────────────────────────────────────────────────────────── - - /// - /// Gets the width of this image in pixels. - /// - public abstract int Width { get; } - - /// - /// Gets the height of this image in pixels. - /// - public abstract int Height { get; } - - /// - /// Gets the size of this image in pixels. - /// - public Size Size => new Size(Width, Height); - - /// - /// Gets the physical size of this image in pixels. - /// - public SizeF PhysicalDimension => new SizeF(Width, Height); - - // ── Format / flags ─────────────────────────────────────────────────────── - - /// - /// Gets the pixel format of this image. - /// - public abstract PixelFormat PixelFormat { get; } - - /// - /// Gets the format of this image. - /// - public abstract ImageFormat RawFormat { get; } - - /// - /// Gets the flags for this image. - /// - public virtual int Flags => (int)ImageFlags.ColorSpaceRgb; - - // ── Resolution ─────────────────────────────────────────────────────────── - - /// - /// Gets the horizontal resolution in pixels per inch. - /// - public virtual float HorizontalResolution => _dpiX; - - /// - /// Gets the vertical resolution in pixels per inch. - /// - public virtual float VerticalResolution => _dpiY; - - // ── Coordinate bounds ──────────────────────────────────────────────────── - - /// - /// Gets the bounds of this image in the specified unit. - /// - /// The unit to use for the bounds. - /// The bounds of the image. - public RectangleF GetBounds(ref GraphicsUnit pageUnit) - { - pageUnit = GraphicsUnit.Pixel; - return new RectangleF(0, 0, Width, Height); - } - - // ── Clone ──────────────────────────────────────────────────────────────── - - /// - /// Creates an exact copy of this image. - /// - /// A new with the same content. - public abstract Image Clone(); - - // ── Frame access (single-frame for Bitmap) ─────────────────────────────── - - /// - /// Gets the number of frames in the specified dimension. - /// - /// The dimension to count frames in. - /// The number of frames. - public virtual int GetFrameCount(FrameDimension dimension) => 1; - - /// - /// Selects the frame in the specified dimension. - /// - /// The dimension to select the frame in. - /// The index of the frame to select. - /// The index of the previously selected frame. - public virtual int SelectActiveFrame(FrameDimension dimension, int idx) => 0; - - // ── EXIF property items ────────────────────────────────────────────────── - - /// - /// Gets the property item for the specified property ID. - /// - /// The property ID. - /// The property item, or null if not found. - public virtual PropertyItem? GetPropertyItem(int propid) => null; - - /// - /// Gets the property IDs for all property items. - /// - /// An array of property IDs. - public virtual int[] GetPropertyIdList() => Array.Empty(); - - /// - /// Gets all property items. - /// - /// An array of property items. - public virtual PropertyItem[] PropertyItems => Array.Empty(); - - // ── Encoder parameter info (stub) ──────────────────────────────────────── - - /// - /// Gets the encoder parameters for the specified encoder. - /// - /// The encoder CLSID. - /// The encoder parameters. - public virtual EncoderParameters GetEncoderParameterList(Guid encoderClsid) - => new EncoderParameters(); - - // ── Save ───────────────────────────────────────────────────────────────── - - /// - /// Saves this image to the specified file. - /// - /// The file name to save to. - public abstract void Save(string filename); - - /// - /// Saves this image to the specified file in the specified format. - /// - /// The file name to save to. - /// The format to save in. - public abstract void Save(string filename, ImageFormat format); - - /// - /// Saves this image to the specified stream in the specified format. - /// - /// The stream to save to. - /// The format to save in. - public abstract void Save(Stream stream, ImageFormat format); - - /// - /// Saves this image to the specified stream in the specified format with encoder parameters. - /// - /// The stream to save to. - /// The format to save in. - /// The encoder parameters. - public virtual void Save(Stream stream, ImageFormat format, EncoderParameters? encoderParams) - => Save(stream, format); - - // ── Rotate/flip ────────────────────────────────────────────────────────── - - /// - /// Rotates and flips the image. - /// - /// The rotation and flip type. - public abstract void RotateFlip(RotateFlipType rotateFlipType); - - // ── Thumbnail (requires rasterizer — Batch 7) ──────────────────────────── - - /// - /// Returns a thumbnail image of the specified size. - /// - /// The width of the thumbnail. - /// The height of the thumbnail. - /// The callback for aborting the operation. - /// Callback data. - /// The thumbnail image. - public virtual Image GetThumbnailImage( - int thumbWidth, int thumbHeight, - GetThumbnailImageAbort? callback, IntPtr callbackData) - => throw new NotImplementedException("GetThumbnailImage requires the Batch 7 rasterizer."); - - // ── Static factory ─────────────────────────────────────────────────────── - - /// - /// Creates an from the specified file. - /// - /// The file to load from. - /// The loaded image. - public static Image FromFile(string filename) => Bitmap.FromFile(filename); - - /// - /// Creates an from the specified stream. - /// - /// The stream to load from. - /// The loaded image. - public static Image FromStream(Stream stream) => Bitmap.FromStream(stream); - - // ── IDisposable ────────────────────────────────────────────────────────── - - private bool _disposed; - - /// - /// Releases the unmanaged resources used by this image and optionally releases the managed resources. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected virtual void Dispose(bool disposing) { _disposed = true; } - - /// - /// Releases all resources used by this image. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ImageFlags.cs b/src/MiniPdf/Drawing/Imaging/ImageFlags.cs deleted file mode 100644 index bad10397..00000000 --- a/src/MiniPdf/Drawing/Imaging/ImageFlags.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the attributes of an image. - /// - [Flags] - public enum ImageFlags - { - /// - /// No attributes. - /// - None = 0, - - /// - /// Image is scalable. - /// - Scalable = 0x0001, - - /// - /// Image has an alpha channel. - /// - HasAlpha = 0x0002, - - /// - /// Image has translucent pixels. - /// - HasTranslucent = 0x0004, - - /// - /// Image is partially scalable. - /// - PartiallyScalable = 0x0008, - - /// - /// Image uses RGB color space. - /// - ColorSpaceRgb = 0x0010, - - /// - /// Image uses CMYK color space. - /// - ColorSpaceCmyk = 0x0020, - - /// - /// Image uses grayscale color space. - /// - ColorSpaceGray = 0x0040, - - /// - /// Image uses YCbCr color space. - /// - ColorSpaceYcbcr = 0x0080, - - /// - /// Image uses YCCK color space. - /// - ColorSpaceYcck = 0x0100, - - /// - /// Image has real DPI information. - /// - HasRealDpi = 0x1000, - - /// - /// Image has real pixel size information. - /// - HasRealPixelSize = 0x2000, - - /// - /// Image is read-only. - /// - ReadOnly = 0x00010000, - - /// - /// Image supports caching. - /// - Caching = 0x00020000, - } -} diff --git a/src/MiniPdf/Drawing/Imaging/ImageFormat.cs b/src/MiniPdf/Drawing/Imaging/ImageFormat.cs deleted file mode 100644 index bb8684f0..00000000 --- a/src/MiniPdf/Drawing/Imaging/ImageFormat.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Identifies an image codec (format). - /// - public sealed class ImageFormat - { - /// - /// Gets the GUID of this image format. - /// - public Guid Guid { get; } - - /// - /// Gets the name of this image format. - /// - public string Name { get; } - - private ImageFormat(string name, string guid) - { - Name = name; - Guid = new Guid(guid); - } - - // ── Known formats ──────────────────────────────────────────────────────── - - /// - /// Gets the Windows Bitmap (BMP) image format. - /// - public static readonly ImageFormat Bmp = new ImageFormat("Bmp", "b96b3cab-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Windows Enhanced Metafile (EMF) image format. - /// - public static readonly ImageFormat Emf = new ImageFormat("Emf", "b96b3cac-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Windows Metafile (WMF) image format. - /// - public static readonly ImageFormat Wmf = new ImageFormat("Wmf", "b96b3cad-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Joint Photographic Experts Group (JPEG) image format. - /// - public static readonly ImageFormat Jpeg = new ImageFormat("Jpeg", "b96b3cae-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Portable Network Graphics (PNG) image format. - /// - public static readonly ImageFormat Png = new ImageFormat("Png", "b96b3caf-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Graphics Interchange Format (GIF) image format. - /// - public static readonly ImageFormat Gif = new ImageFormat("Gif", "b96b3cb0-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Tagged Image File Format (TIFF) image format. - /// - public static readonly ImageFormat Tiff = new ImageFormat("Tiff", "b96b3cb1-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Windows Icon (ICO) image format. - /// - public static readonly ImageFormat Icon = new ImageFormat("Icon", "b96b3cb5-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Gets the Scalable Vector Graphics (SVG) image format. - /// - public static readonly ImageFormat Svg = new ImageFormat("Svg", "a6b1c000-0000-0000-0000-0000000000a6"); - - /// - /// Gets the memory bitmap image format. - /// - public static readonly ImageFormat MemoryBmp = new ImageFormat("MemoryBmp", "b96b3caa-0728-11d3-9d7b-0000f81ef32e"); - - /// - /// Returns a string representation of this image format. - /// - /// A string containing the format GUID. - public override string ToString() => $"[ImageFormat: {Guid}]"; - - /// - /// Determines whether this image format is equal to another object. - /// - /// The object to compare. - /// true if the formats are equal; otherwise, false. - public override bool Equals(object? obj) => obj is ImageFormat f && f.Guid == Guid; - - /// - /// Returns the hash code for this image format. - /// - /// The hash code. - public override int GetHashCode() => Guid.GetHashCode(); - } -} diff --git a/src/MiniPdf/Drawing/Imaging/Metafile.cs b/src/MiniPdf/Drawing/Imaging/Metafile.cs deleted file mode 100644 index 657e0eef..00000000 --- a/src/MiniPdf/Drawing/Imaging/Metafile.cs +++ /dev/null @@ -1,449 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes; -using MiniSoftware.Drawing.Rendering; -using EmfRecords = MiniSoftware.Drawing.Metafile.Emf.Records; -using WmfRecords = MiniSoftware.Drawing.Metafile.Wmf.Records; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Represents a Windows metafile (.wmf or .emf), which is a vector image format - /// containing a sequence of drawing commands. - /// - /// - /// A can be loaded from WMF or EMF files and rendered - /// to a using . Metafiles are - /// commonly used for scalable graphics that maintain quality at any resolution. - /// - public sealed class Metafile : Image - { - private readonly byte[] _rawBytes; - private readonly Drawing.Metafile.MetafileDocument _document; - private readonly Rectangle _logicalBounds; - private readonly ImageFormat _rawFormat; - private readonly MetafileHeader _header; - - /// - /// Initializes a new from the specified file. - /// - /// The file to load from. - public Metafile(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("The file name cannot be null or whitespace.", nameof(filename)); - - using var stream = File.OpenRead(filename); - (_rawBytes, _document, _logicalBounds, _rawFormat, _header) = Load(stream); - } - - /// - /// Initializes a new from the specified stream. - /// - /// The stream to load from. - public Metafile(Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - (_rawBytes, _document, _logicalBounds, _rawFormat, _header) = Load(stream); - } - - /// - /// Gets the width of this metafile in pixels. - /// - public override int Width => Math.Max(1, _logicalBounds.Width); - - /// - /// Gets the height of this metafile in pixels. - /// - public override int Height => Math.Max(1, _logicalBounds.Height); - - /// - /// Gets the pixel format of this metafile. - /// - public override PixelFormat PixelFormat => PixelFormat.Format32bppArgb; - - /// - /// Gets the format of this metafile. - /// - public override ImageFormat RawFormat => _rawFormat; - - /// - /// Gets the flags for this metafile. - /// - public override int Flags - => (int)(ImageFlags.Scalable | ImageFlags.ColorSpaceRgb | ImageFlags.HasRealDpi); - - /// - /// Gets the metafile header information. - /// - /// The metafile header. - public MetafileHeader GetMetafileHeader() => _header; - - /// - /// Renders this metafile to a . - /// - /// The rendered bitmap. - public Bitmap ToBitmap() => RenderToBitmap(); - - internal Bitmap RenderToBitmap() - => RenderToBitmap(Width, Height); - - internal Bitmap RenderToBitmap(int width, int height) - { - width = Math.Max(1, width); - height = Math.Max(1, height); - - var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); - switch (_document.Format) - { - case Drawing.Metafile.MetafileFormat.Wmf: - WmfPlayer.Render(_document, bitmap, _logicalBounds); - break; - - case Drawing.Metafile.MetafileFormat.Emf: - case Drawing.Metafile.MetafileFormat.EmfPlus: - EmfPlayer.Render(_document, bitmap, _logicalBounds); - break; - - default: - throw new NotSupportedException("Unsupported metafile format."); - } - - bitmap._rawFormat = _rawFormat; - return bitmap; - } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same content. - public override Image Clone() - => new Metafile(new MemoryStream(_rawBytes, writable: false)); - - /// - /// Saves this metafile to the specified file. - /// - /// The file name to save to. - public override void Save(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("The file name cannot be null or whitespace.", nameof(filename)); - - using var stream = File.Open(filename, FileMode.Create, FileAccess.Write); - Save(stream, _rawFormat); - } - - /// - /// Saves this metafile to the specified file in the specified format. - /// - /// The file name to save to. - /// The format to save in. - public override void Save(string filename, ImageFormat format) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("The file name cannot be null or whitespace.", nameof(filename)); - - using var stream = File.Open(filename, FileMode.Create, FileAccess.Write); - Save(stream, format); - } - - /// - /// Saves this metafile to the specified stream in the specified format. - /// - /// The stream to save to. - /// The format to save in. - public override void Save(Stream stream, ImageFormat format) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - if (format == null) - throw new ArgumentNullException(nameof(format)); - - bool supported = format.Equals(ImageFormat.Emf) || format.Equals(ImageFormat.Wmf); - if (!supported) - throw new NotSupportedException("Metafile saving supports only EMF and WMF formats."); - - if (!format.Equals(_rawFormat)) - throw new NotSupportedException("Metafile transcoding is not supported."); - - stream.Write(_rawBytes, 0, _rawBytes.Length); - } - - /// - /// Rotates and flips the metafile. - /// - /// The rotation and flip type. - /// This operation is not supported for vector metafiles. - public override void RotateFlip(RotateFlipType rotateFlipType) - => throw new NotSupportedException("RotateFlip is not supported for vector metafiles."); - - private static (byte[] rawBytes, Drawing.Metafile.MetafileDocument document, Rectangle bounds, ImageFormat rawFormat, MetafileHeader header) Load(Stream stream) - { - byte[] rawBytes = ReadAllBytes(stream); - using var parseStream = new MemoryStream(rawBytes, writable: false); - - var reader = new Drawing.Metafile.MetafileReader(); - var document = reader.Read(parseStream); - - Rectangle bounds = DetermineLogicalBounds(document); - ImageFormat rawFormat = document.Format == Drawing.Metafile.MetafileFormat.Wmf - ? ImageFormat.Wmf - : ImageFormat.Emf; - - EmfType emfType = DetermineEmfType(document); - bool isWmf = document.Format == Drawing.Metafile.MetafileFormat.Wmf; - bool isEmf = document.Format == Drawing.Metafile.MetafileFormat.Emf; - bool isEmfPlus = document.Format == Drawing.Metafile.MetafileFormat.EmfPlus || document.EmbeddedEmfPlusRecords.Count > 0; - - var header = new MetafileHeader( - bounds, - 96f, - 96f, - MetafileFrameUnit.Pixel, - emfType, - isWmf, - isEmf, - isEmfPlus); - - return (rawBytes, document, bounds, rawFormat, header); - } - - private static EmfType DetermineEmfType(Drawing.Metafile.MetafileDocument document) - { - if (document.Format == Drawing.Metafile.MetafileFormat.EmfPlus) - return EmfType.EmfPlusOnly; - - if (document.EmbeddedEmfPlusRecords.Count > 0) - return EmfType.EmfPlusDual; - - return EmfType.EmfOnly; - } - - private static Rectangle DetermineLogicalBounds(Drawing.Metafile.MetafileDocument document) - { - switch (document.Format) - { - case Drawing.Metafile.MetafileFormat.Wmf: - if (document.PlaceableHeader != null) - { - var box = document.PlaceableHeader.BoundingBox; - return NormalizeBounds(box.Left, box.Top, box.Right, box.Bottom); - } - - return ComputeWmfBounds(document.WmfRecords); - - case Drawing.Metafile.MetafileFormat.Emf: - case Drawing.Metafile.MetafileFormat.EmfPlus: - { - foreach (var record in document.EmfRecords) - { - if (record is EMR_HEADER header) - { - var b = header.HeaderObject.Bounds; - return NormalizeBounds(b.Left, b.Top, b.Right, b.Bottom); - } - } - - return ComputeEmfBounds(document.EmfRecords); - } - - default: - return new Rectangle(0, 0, 1, 1); - } - } - - private static Rectangle ComputeWmfBounds(IReadOnlyList records) - { - bool hasAny = false; - int minX = 0; - int minY = 0; - int maxX = 0; - int maxY = 0; - - void IncludePoint(int x, int y) - { - if (!hasAny) - { - minX = maxX = x; - minY = maxY = y; - hasAny = true; - return; - } - - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } - - void IncludeRect(int left, int top, int right, int bottom) - { - IncludePoint(left, top); - IncludePoint(right, bottom); - } - - foreach (var record in records) - { - switch (record) - { - case WmfRecords.META_SETPIXEL pixel: - IncludePoint(pixel.X, pixel.Y); - IncludePoint(pixel.X + 1, pixel.Y + 1); - break; - - case WmfRecords.StateRecordTypes.META_MOVETO moveTo: - IncludePoint(moveTo.X, moveTo.Y); - break; - - case WmfRecords.META_LINETO lineTo: - IncludePoint(lineTo.X, lineTo.Y); - break; - - case WmfRecords.META_RECTANGLE rectangle: - IncludeRect(rectangle.LeftRect, rectangle.TopRect, rectangle.RightRect, rectangle.BottomRect); - break; - - case WmfRecords.META_ELLIPSE ellipse: - IncludeRect(ellipse.LeftRect, ellipse.TopRect, ellipse.RightRect, ellipse.BottomRect); - break; - - case WmfRecords.META_POLYLINE polyline: - foreach (var point in polyline.aPoints) - { - IncludePoint(point.x, point.y); - } - break; - - case WmfRecords.META_POLYGON polygon: - foreach (Point point in polygon.Points) - { - IncludePoint(point.X, point.Y); - } - break; - } - } - - if (!hasAny) - return new Rectangle(0, 0, 1, 1); - - return NormalizeBounds(minX, minY, maxX, maxY); - } - - private static Rectangle ComputeEmfBounds(IReadOnlyList records) - { - bool hasAny = false; - int minX = 0; - int minY = 0; - int maxX = 0; - int maxY = 0; - - void IncludePoint(int x, int y) - { - if (!hasAny) - { - minX = maxX = x; - minY = maxY = y; - hasAny = true; - return; - } - - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY) maxY = y; - } - - void IncludeRect(int left, int top, int right, int bottom) - { - IncludePoint(left, top); - IncludePoint(right, bottom); - } - - foreach (var record in records) - { - switch (record) - { - case EMR_SETPIXELV pixel: - IncludePoint(pixel.Position.x, pixel.Position.y); - IncludePoint(pixel.Position.x + 1, pixel.Position.y + 1); - break; - - case EMR_MOVETOEX moveTo: - IncludePoint(moveTo.Offset.x, moveTo.Offset.y); - break; - - case EMR_LINETO lineTo: - IncludePoint(lineTo.Point.x, lineTo.Point.y); - break; - - case EMR_RECTANGLE rectangle: - IncludeRect(rectangle.Box.Left, rectangle.Box.Top, rectangle.Box.Right, rectangle.Box.Bottom); - break; - - case EMR_ELLIPSE ellipse: - IncludeRect(ellipse.Box.Left, ellipse.Box.Top, ellipse.Box.Right, ellipse.Box.Bottom); - break; - - case EMR_POLYLINE polyline: - foreach (var point in polyline.Points) - { - IncludePoint(point.x, point.y); - } - break; - - case EMR_POLYLINE16 polyline16: - foreach (var point in polyline16.Points) - { - IncludePoint(point.x, point.y); - } - break; - - case EMR_POLYGON polygon: - foreach (var point in polygon.Points) - { - IncludePoint(point.x, point.y); - } - break; - - case EMR_POLYGON16 polygon16: - foreach (var point in polygon16.Points) - { - IncludePoint(point.x, point.y); - } - break; - } - } - - if (!hasAny) - return new Rectangle(0, 0, 1, 1); - - return NormalizeBounds(minX, minY, maxX, maxY); - } - - private static Rectangle NormalizeBounds(int left, int top, int right, int bottom) - { - int minX = Math.Min(left, right); - int minY = Math.Min(top, bottom); - int width = Math.Abs(right - left); - int height = Math.Abs(bottom - top); - - if (width <= 0) width = 1; - if (height <= 0) height = 1; - - return new Rectangle(minX, minY, width, height); - } - - private static byte[] ReadAllBytes(Stream stream) - { - using var memory = new MemoryStream(); - stream.CopyTo(memory); - return memory.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/MetafileFrameUnit.cs b/src/MiniPdf/Drawing/Imaging/MetafileFrameUnit.cs deleted file mode 100644 index 4adc49b9..00000000 --- a/src/MiniPdf/Drawing/Imaging/MetafileFrameUnit.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Specifies the unit of measurement for metafile frames. - /// - public enum MetafileFrameUnit - { - /// - /// Pixel units. - /// - Pixel, - - /// - /// Point units (1/72 inch). - /// - Point, - - /// - /// Inch units. - /// - Inch, - - /// - /// Document units (1/300 inch). - /// - Document, - - /// - /// Millimeter units. - /// - Millimeter, - - /// - /// GDI-compatible units. - /// - GdiCompatible, - } -} diff --git a/src/MiniPdf/Drawing/Imaging/MetafileHeader.cs b/src/MiniPdf/Drawing/Imaging/MetafileHeader.cs deleted file mode 100644 index db147af3..00000000 --- a/src/MiniPdf/Drawing/Imaging/MetafileHeader.cs +++ /dev/null @@ -1,81 +0,0 @@ -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Contains attributes and dimensions of a metafile. - /// - public sealed class MetafileHeader - { - /// - /// Gets the bounding rectangle of the metafile. - /// - public Rectangle Bounds { get; } - - /// - /// Gets the horizontal DPI of the metafile. - /// - public float DpiX { get; } - - /// - /// Gets the vertical DPI of the metafile. - /// - public float DpiY { get; } - - /// - /// Gets the frame unit of the metafile. - /// - public MetafileFrameUnit FrameUnit { get; } - - /// - /// Gets the type of the metafile. - /// - public EmfType Type { get; } - - /// - /// Gets a value indicating whether the metafile is a WMF (Windows Metafile). - /// - public bool IsWmf { get; } - - /// - /// Gets a value indicating whether the metafile is an EMF (Enhanced Metafile). - /// - public bool IsEmf { get; } - - /// - /// Gets a value indicating whether the metafile is an EMF+ (Enhanced Metafile Plus). - /// - public bool IsEmfPlus { get; } - - /// - /// Initializes a new with the specified values. - /// - /// The bounding rectangle. - /// The horizontal DPI. - /// The vertical DPI. - /// The frame unit. - /// The metafile type. - /// Whether this is a WMF. - /// Whether this is an EMF. - /// Whether this is an EMF+. - internal MetafileHeader( - Rectangle bounds, - float dpiX, - float dpiY, - MetafileFrameUnit frameUnit, - EmfType type, - bool isWmf, - bool isEmf, - bool isEmfPlus) - { - Bounds = bounds; - DpiX = dpiX; - DpiY = dpiY; - FrameUnit = frameUnit; - Type = type; - IsWmf = isWmf; - IsEmf = isEmf; - IsEmfPlus = isEmfPlus; - } - } -} diff --git a/src/MiniPdf/Drawing/Imaging/PropertyItem.cs b/src/MiniPdf/Drawing/Imaging/PropertyItem.cs deleted file mode 100644 index 9f15721b..00000000 --- a/src/MiniPdf/Drawing/Imaging/PropertyItem.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Represents a metadata property item for an image. - /// - public sealed class PropertyItem - { - /// - /// Gets or sets the property identifier. - /// - public int Id { get; set; } - - /// - /// Gets or sets the length of the property value in bytes. - /// - public int Len { get; set; } - - /// - /// Gets or sets the property type. - /// - public short Type { get; set; } - - /// - /// Gets or sets the property value as a byte array. - /// - public byte[] Value { get; set; } = System.Array.Empty(); - } -} diff --git a/src/MiniPdf/Drawing/Imaging/SvgImage.cs b/src/MiniPdf/Drawing/Imaging/SvgImage.cs deleted file mode 100644 index 3755aee1..00000000 --- a/src/MiniPdf/Drawing/Imaging/SvgImage.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Vector; -using MiniSoftware.Drawing.Vector.Svg; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// A vector image backed by a , loadable from and - /// savable to SVG, EMF, WMF, and raster formats. Mirrors . - /// - public sealed class SvgImage : Image - { - private readonly VectorScene _scene; - - /// - /// Initializes a new empty with the specified - /// dimensions. - /// - /// The canvas width in pixels. - /// The canvas height in pixels. - public SvgImage(int width, int height) - { - _scene = new VectorScene { Width = width, Height = height }; - } - - /// - /// Initializes a new by loading an SVG document - /// from the specified file. - /// - /// The SVG file to load. - public SvgImage(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("Filename cannot be null or whitespace.", nameof(filename)); - using var stream = File.OpenRead(filename); - _scene = LoadScene(stream); - } - - /// - /// Initializes a new by loading an SVG document - /// from the specified stream. - /// - /// The stream to load from. - public SvgImage(Stream stream) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - _scene = LoadScene(stream); - } - - /// - /// Gets the underlying . - /// - internal VectorScene Scene => _scene; - - /// - public override int Width => _scene.Width; - - /// - public override int Height => _scene.Height; - - /// - public override PixelFormat PixelFormat => PixelFormat.Format32bppArgb; - - /// - public override ImageFormat RawFormat => ImageFormat.Svg; - - /// - public override int Flags - => (int)(ImageFlags.Scalable | ImageFlags.ColorSpaceRgb | ImageFlags.HasRealDpi); - - /// - /// Creates a surface for drawing onto this SVG - /// image. Drawing operations are recorded as vector commands; no - /// rasterization occurs until is called. - /// - /// A backed by a . - public Graphics CreateGraphics() - { - return new RecordingGraphics(_scene, _scene.Width, _scene.Height); - } - - /// - /// Renders this SVG image to a by replaying the - /// recorded commands onto a raster surface. - /// - /// The rendered bitmap. - public Bitmap RenderToBitmap() - => RenderToBitmap(Width, Height); - - /// - /// Renders this SVG image to a of the specified - /// size by replaying the recorded commands onto a scaled raster surface. - /// - /// The output bitmap width. - /// The output bitmap height. - /// The rendered bitmap. - public Bitmap RenderToBitmap(int width, int height) - { - width = Math.Max(1, width); - height = Math.Max(1, height); - - var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); - using var g = Graphics.FromImage(bitmap); - - // If scaled, apply a scale transform - if (width != _scene.Width || height != _scene.Height) - { - float sx = (float)width / _scene.Width; - float sy = (float)height / _scene.Height; - g.ScaleTransform(sx, sy); - } - - VectorScenePlayer.Play(_scene, g); - return bitmap; - } - - /// - public override void Save(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("Filename cannot be null or whitespace.", nameof(filename)); - using var stream = File.Open(filename, FileMode.Create, FileAccess.Write); - Save(stream, ImageFormat.Svg); - } - - /// - public override void Save(string filename, ImageFormat format) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("Filename cannot be null or whitespace.", nameof(filename)); - using var stream = File.Open(filename, FileMode.Create, FileAccess.Write); - Save(stream, format); - } - - /// - public override void Save(Stream stream, ImageFormat format) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - if (format == null) throw new ArgumentNullException(nameof(format)); - - if (format.Equals(ImageFormat.Svg)) - { - SvgWriter.Write(stream, _scene, SvgEncoderParameters.Default); - return; - } - - // Raster formats: render to bitmap then save - if (format.Equals(ImageFormat.Png) || format.Equals(ImageFormat.Bmp) || - format.Equals(ImageFormat.Jpeg) || format.Equals(ImageFormat.Gif) || - format.Equals(ImageFormat.Tiff)) - { - using var bmp = RenderToBitmap(); - bmp.Save(stream, format); - return; - } - - throw new NotSupportedException($"SvgImage does not support saving to format '{format.Name}'."); - } - - /// - public override void Save(Stream stream, ImageFormat format, EncoderParameters? encoderParams) - => Save(stream, format); - - /// - public override Image Clone() - { - var clone = new SvgImage(_scene.Width, _scene.Height); - // Deep-copy commands - foreach (var cmd in _scene.Commands) - clone._scene.Commands.Add(cmd.Clone()); - clone._scene.DpiX = _scene.DpiX; - clone._scene.DpiY = _scene.DpiY; - return clone; - } - - /// - public override void RotateFlip(RotateFlipType rotateFlipType) - { - // For v1, apply the transform to the scene by wrapping commands - // in a transform group. A full implementation would transform - // each command's coordinates. - // For now, throw as vector rotation is non-trivial. - if (rotateFlipType == RotateFlipType.RotateNoneFlipNone) return; - throw new NotSupportedException("RotateFlip is not supported for SvgImage in this version."); - } - - // ── SVG loading ─────────────────────────────────────────────────────── - - private static VectorScene LoadScene(Stream stream) - { - return SvgReader.Read(stream); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Imaging/SystemIcons.cs b/src/MiniPdf/Drawing/Imaging/SystemIcons.cs deleted file mode 100644 index 78a2841a..00000000 --- a/src/MiniPdf/Drawing/Imaging/SystemIcons.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Threading; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Enums; - -namespace MiniSoftware.Drawing.Imaging -{ - /// - /// Provides a set of pre-defined system icons as stub implementations. - /// Each icon is a 16×16 solid-color bitmap; the instances are cached after first access. - /// - public static class SystemIcons - { - /// - /// Gets the application system icon. - /// - public static Icon Application => GetOrCreate(ref s_application, Color.DarkGray); - - /// - /// Gets the error system icon. - /// - public static Icon Error => GetOrCreate(ref s_error, Color.Red); - - /// - /// Gets the hand system icon. - /// - public static Icon Hand => GetOrCreate(ref s_hand, Color.DarkRed); - - /// - /// Gets the exclamation system icon. - /// - public static Icon Exclamation => GetOrCreate(ref s_exclamation, Color.Gold); - - /// - /// Gets the warning system icon. - /// - public static Icon Warning => GetOrCreate(ref s_warning, Color.Orange); - - /// - /// Gets the information system icon. - /// - public static Icon Information => GetOrCreate(ref s_information, Color.DodgerBlue); - - /// - /// Gets the asterisk system icon. - /// - public static Icon Asterisk => GetOrCreate(ref s_asterisk, Color.SteelBlue); - - /// - /// Gets the question system icon. - /// - public static Icon Question => GetOrCreate(ref s_question, Color.RoyalBlue); - - /// - /// Gets the Windows logo system icon. - /// - public static Icon WinLogo => GetOrCreate(ref s_winLogo, Color.CornflowerBlue); - - /// - /// Gets the shield system icon. - /// - public static Icon Shield => GetOrCreate(ref s_shield, Color.SlateBlue); - - // ── Backing fields ─────────────────────────────────────────────────────── - - private static Icon? s_application; - private static Icon? s_error; - private static Icon? s_hand; - private static Icon? s_exclamation; - private static Icon? s_warning; - private static Icon? s_information; - private static Icon? s_asterisk; - private static Icon? s_question; - private static Icon? s_winLogo; - private static Icon? s_shield; - - // ── Helper ─────────────────────────────────────────────────────────────── - - private static Icon GetOrCreate(ref Icon? field, Color fill) - { - if (field == null) - { - var icon = new Icon(MakeStub(fill)); - Interlocked.CompareExchange(ref field, icon, null); - } - return field!; - } - - private static Bitmap MakeStub(Color fill) - { - const int Size = 16; - var bmp = new Bitmap(Size, Size, PixelFormat.Format32bppArgb); - for (int y = 0; y < Size; y++) - for (int x = 0; x < Size; x++) - bmp.SetPixel(x, y, fill); - return bmp; - } - } -} diff --git a/src/MiniPdf/Drawing/LICENSE.DRIT.Drawing b/src/MiniPdf/Drawing/LICENSE.DRIT.Drawing deleted file mode 100644 index 5462bb35..00000000 --- a/src/MiniPdf/Drawing/LICENSE.DRIT.Drawing +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 DR-IT Ltd. - -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. \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Metafile/BitUtils.cs b/src/MiniPdf/Drawing/Metafile/BitUtils.cs deleted file mode 100644 index 0512637c..00000000 --- a/src/MiniPdf/Drawing/Metafile/BitUtils.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile -{ - /// - /// Provides helper methods for extracting bit fields from integer values. - /// - public static class BitHelper - { - /// - /// Extracts a specified number of bits from an unsigned integer value. - /// - /// The source value to extract bits from. - /// The zero-based starting bit position. - /// The number of bits to extract. - /// Whether the extracted value should be treated as signed. - /// The extracted bit field value. - public static int GetBits(uint value, int start, int length, bool signed) - { - int mask = (1 << length) - 1; - return (int)((value >> start) & mask); - } - } - - /// - /// Provides helper methods for bit manipulation operations. - /// - public static class BitManipulation - { - /// - /// Extracts a specified number of bits from a byte value. - /// - /// The source byte to extract bits from. - /// The zero-based starting bit position. - /// The number of bits to extract. - /// The extracted bit field value. - public static int GetBits(byte value, int start, int length) - { - int mask = (1 << length) - 1; - return (value >> start) & mask; - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/EmfReader.cs b/src/MiniPdf/Drawing/Metafile/Emf/EmfReader.cs deleted file mode 100644 index d53f9ecc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/EmfReader.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Records; - using MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes; - using MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes; - using MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes; - using MiniSoftware.Drawing.Metafile.EmfPlus; - - internal class EmfReader - { - public List Records = new List(); - - //public MetaHeader Header { get; private set; } - - public void Read(Stream stream) - { - var reader = new BinaryReader(stream); - - - - while (stream.Position < stream.Length) - { - var header = new RecordHeader(); - header.Read(reader); - - long expectedEndPosition = stream.Position + (header.Size) - 8; - var record = CreateRecord(header, reader); - if (record == null) - { - record = new Record(); - record.Header = header; - record.Data = reader.ReadBytes(Convert.ToInt32(header.Size) - 8); - - } - - if (header.Type == RecordType.EMR_COMMENT) - { - byte[] commentPayload = record switch - { - EMR_COMMENT commentRecord => commentRecord.CommentData, - _ => record.Data, - }; - - using (var commentStream = new MemoryStream(commentPayload)) - { - var emfPlusReader = new EmfPlusReader(); - emfPlusReader.Read(commentStream); - } - } - - this.Records.Add(record); - stream.Position = expectedEndPosition; - } - } - - public static Record? CreateRecord(RecordHeader header, BinaryReader reader) - { - Record? record = header.Type switch - { - RecordType.EMR_HEADER => new EMR_HEADER(), - RecordType.EMR_POLYBEZIER => new EMR_POLYBEZIER(), - RecordType.EMR_POLYGON => new EMR_POLYGON(), - RecordType.EMR_POLYLINE => new EMR_POLYLINE(), - RecordType.EMR_POLYBEZIERTO => new EMR_POLYBEZIERTO(), - RecordType.EMR_POLYLINETO => new EMR_POLYLINETO(), - RecordType.EMR_POLYPOLYLINE => new EMR_POLYPOLYLINE(), - RecordType.EMR_POLYPOLYGON => new EMR_POLYPOLYGON(), - RecordType.EMR_ANGLEARC => new EMR_ANGLEARC(), - RecordType.EMR_EOF => new EMR_EOF(), - RecordType.EMR_LINETO => new EMR_LINETO(), - RecordType.EMR_ARCTO => new EMR_ARCTO(), - RecordType.EMR_ARC => new EMR_ARC(), - RecordType.EMR_CHORD => new EMR_CHORD(), - RecordType.EMR_ELLIPSE => new EMR_ELLIPSE(), - RecordType.EMR_RECTANGLE => new EMR_RECTANGLE(), - RecordType.EMR_ROUNDRECT => new EMR_ROUNDRECT(), - RecordType.EMR_PIE => new EMR_PIE(), - RecordType.EMR_EXTFLOODFILL => new EMR_EXTFLOODFILL(), - RecordType.EMR_SETWINDOWEXTEX => new EMR_SETWINDOWEXTEX(), - RecordType.EMR_SETWINDOWORGEX => new EMR_SETWINDOWORGEX(), - RecordType.EMR_SETVIEWPORTEXTEX => new EMR_SETVIEWPORTEXTEX(), - RecordType.EMR_SETVIEWPORTORGEX => new EMR_SETVIEWPORTORGEX(), - RecordType.EMR_SETBRUSHORGEX => new EMR_SETBRUSHORGEX(), - RecordType.EMR_SETPIXELV => new EMR_SETPIXELV(), - RecordType.EMR_SETMAPPERFLAGS => new EMR_SETMAPPERFLAGS(), - RecordType.EMR_SETMAPMODE => new EMR_SETMAPMODE(), - RecordType.EMR_SETBKMODE => new EMR_SETBKMODE(), - RecordType.EMR_SETPOLYFILLMODE => new EMR_SETPOLYFILLMODE(), - RecordType.EMR_SETROP2 => new EMR_SETROP2(), - RecordType.EMR_SETSTRETCHBLTMODE => new EMR_SETSTRETCHBLTMODE(), - RecordType.EMR_SETTEXTALIGN => new EMR_SETTEXTALIGN(), - RecordType.EMR_SETCOLORADJUSTMENT => new EMR_SETCOLORADJUSTMENT(), - RecordType.EMR_SETTEXTCOLOR => new EMR_SETTEXTCOLOR(), - RecordType.EMR_SETBKCOLOR => new EMR_SETBKCOLOR(), - RecordType.EMR_OFFSETCLIPRGN => new EMR_OFFSETCLIPRGN(), - RecordType.EMR_MOVETOEX => new EMR_MOVETOEX(), - RecordType.EMR_SETMETARGN => new EMR_SETMETARGN(), - RecordType.EMR_EXCLUDECLIPRECT => new EMR_EXCLUDECLIPRECT(), - RecordType.EMR_INTERSECTCLIPRECT => new EMR_INTERSECTCLIPRECT(), - RecordType.EMR_SCALEVIEWPORTEXTEX => new EMR_SCALEVIEWPORTEXTEX(), - RecordType.EMR_SCALEWINDOWEXTEX => new EMR_SCALEWINDOWEXTEX(), - RecordType.EMR_SAVEDC => new EMR_SAVEDC(), - RecordType.EMR_RESTOREDC => new EMR_RESTOREDC(), - RecordType.EMR_SETWORLDTRANSFORM => new EMR_SETWORLDTRANSFORM(), - RecordType.EMR_MODIFYWORLDTRANSFORM => new EMR_MODIFYWORLDTRANSFORM(), - RecordType.EMR_SELECTOBJECT => new EMR_SELECTOBJECT(), - RecordType.EMR_CREATEPEN => new EMR_CREATEPEN(), - RecordType.EMR_CREATEBRUSHINDIRECT => new EMR_CREATEBRUSHINDIRECT(), - RecordType.EMR_SELECTPALETTE => new EMR_SELECTPALETTE(), - RecordType.EMR_CREATEPALETTE => new EMR_CREATEPALETTE(), - RecordType.EMR_SETPALETTEENTRIES => new EMR_SETPALETTEENTRIES(), - RecordType.EMR_RESIZEPALETTE => new EMR_RESIZEPALETTE(), - RecordType.EMR_REALIZEPALETTE => new EMR_REALIZEPALETTE(), - RecordType.EMR_DELETEOBJECT => new EMR_DELETEOBJECT(), - RecordType.EMR_SETARCDIRECTION => new EMR_SETARCDIRECTION(), - RecordType.EMR_SETMITERLIMIT => new EMR_SETMITERLIMIT(), - RecordType.EMR_POLYDRAW => new EMR_POLYDRAW(), - RecordType.EMR_BEGINPATH => new EMR_BEGINPATH(), - RecordType.EMR_ENDPATH => new EMR_ENDPATH(), - RecordType.EMR_CLOSEFIGURE => new EMR_CLOSEFIGURE(), - RecordType.EMR_FILLPATH => new EMR_FILLPATH(), - RecordType.EMR_STROKEANDFILLPATH => new EMR_STROKEANDFILLPATH(), - RecordType.EMR_STROKEPATH => new EMR_STROKEPATH(), - RecordType.EMR_FLATTENPATH => new EMR_FLATTENPATH(), - RecordType.EMR_WIDENPATH => new EMR_WIDENPATH(), - RecordType.EMR_SELECTCLIPPATH => new EMR_SELECTCLIPPATH(), - RecordType.EMR_ABORTPATH => new EMR_ABORTPATH(), - RecordType.EMR_COMMENT => new EMR_COMMENT(), - RecordType.EMR_FILLRGN => new EMR_FILLRGN(), - RecordType.EMR_FRAMERGN => new EMR_FRAMERGN(), - RecordType.EMR_INVERTRGN => new EMR_INVERTRGN(), - RecordType.EMR_PAINTRGN => new EMR_PAINTRGN(), - RecordType.EMR_EXTSELECTCLIPRGN => new EMR_EXTSELECTCLIPRGN(), - RecordType.EMR_BITBLT => new EMR_BITBLT(), - RecordType.EMR_STRETCHBLT => new EMR_STRETCHBLT(), - RecordType.EMR_MASKBLT => new EMR_MASKBLT(), - RecordType.EMR_PLGBLT => new EMR_PLGBLT(), - RecordType.EMR_SETDIBITSTODEVICE => new EMR_SETDIBITSTODEVICE(), - RecordType.EMR_STRETCHDIBITS => new EMR_STRETCHDIBITS(), - RecordType.EMR_EXTCREATEFONTINDIRECTW => new EMR_EXTCREATEFONTINDIRECTW(), - RecordType.EMR_EXTTEXTOUTA => new EMR_EXTTEXTOUTA(), - RecordType.EMR_EXTTEXTOUTW => new EMR_EXTTEXTOUTW(), - RecordType.EMR_POLYBEZIER16 => new EMR_POLYBEZIER16(), - RecordType.EMR_POLYGON16 => new EMR_POLYGON16(), - RecordType.EMR_POLYLINE16 => new EMR_POLYLINE16(), - RecordType.EMR_POLYBEZIERTO16 => new EMR_POLYBEZIERTO16(), - RecordType.EMR_POLYLINETO16 => new EMR_POLYLINETO16(), - RecordType.EMR_POLYPOLYLINE16 => new EMR_POLYPOLYLINE16(), - RecordType.EMR_POLYPOLYGON16 => new EMR_POLYPOLYGON16(), - RecordType.EMR_POLYDRAW16 => new EMR_POLYDRAW16(), - RecordType.EMR_CREATEMONOBRUSH => new EMR_CREATEMONOBRUSH(), - RecordType.EMR_CREATEDIBPATTERNBRUSHPT => new EMR_CREATEDIBPATTERNBRUSHPT(), - RecordType.EMR_EXTCREATEPEN => new EMR_EXTCREATEPEN(), - RecordType.EMR_POLYTEXTOUTA => new EMR_POLYTEXTOUTA(), - RecordType.EMR_POLYTEXTOUTW => new EMR_POLYTEXTOUTW(), - RecordType.EMR_SETICMMODE => new EMR_SETICMMODE(), - RecordType.EMR_CREATECOLORSPACE => new EMR_CREATECOLORSPACE(), - RecordType.EMR_SETCOLORSPACE => new EMR_SETCOLORSPACE(), - RecordType.EMR_DELETECOLORSPACE => new EMR_DELETECOLORSPACE(), - RecordType.EMR_GLSRECORD => new EMR_GLSRECORD(), - RecordType.EMR_GLSBOUNDEDRECORD => new EMR_GLSBOUNDEDRECORD(), - RecordType.EMR_PIXELFORMAT => new EMR_PIXELFORMAT(), - RecordType.EMR_DRAWESCAPE => new EMR_DRAWESCAPE(), - RecordType.EMR_EXTESCAPE => new EMR_EXTESCAPE(), - RecordType.EMR_SMALLTEXTOUT => new EMR_SMALLTEXTOUT(), - RecordType.EMR_FORCEUFIMAPPING => new EMR_FORCEUFIMAPPING(), - RecordType.EMR_NAMEDESCAPE => new EMR_NAMEDESCAPE(), - RecordType.EMR_COLORCORRECTPALETTE => new EMR_COLORCORRECTPALETTE(), - RecordType.EMR_SETICMPROFILEA => new EMR_SETICMPROFILEA(), - RecordType.EMR_SETICMPROFILEW => new EMR_SETICMPROFILEW(), - RecordType.EMR_ALPHABLEND => new EMR_ALPHABLEND(), - RecordType.EMR_TRANSPARENTBLT => new EMR_TRANSPARENTBLT(), - RecordType.EMR_GRADIENTFILL => new EMR_GRADIENTFILL(), - RecordType.EMR_SETLINKEDUFIS => new EMR_SETLINKEDUFIS(), - RecordType.EMR_COLORMATCHTOTARGETW => new EMR_COLORMATCHTOTARGETW(), - RecordType.EMR_CREATECOLORSPACEW => new EMR_CREATECOLORSPACEW(), - RecordType.EMR_SETLAYOUT => new EMR_SETLAYOUT(), - RecordType.EMR_SETTEXTJUSTIFICATION => new EMR_SETTEXTJUSTIFICATION(), - _ => null, - }; - - if (record is not null) - { - record.Header = header; - record.Read(reader); - } - - return record; - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArcDirection.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArcDirection.cs deleted file mode 100644 index d12f4f53..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArcDirection.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// - /// - /// - /// 2.1.2 ArcDirection Enumeration - /// - internal enum ArcDirection - { - AD_COUNTERCLOCKWISE = 0x0001, - AD_CLOCKWISE = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArmStyle.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArmStyle.cs deleted file mode 100644 index 68dfa96f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ArmStyle.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The ArmStyle enumeration defines values for one of the characteristics in the PANOSE system for classifying typefaces. - /// - internal enum ArmStyle - { - PAN_ANY = 0x00, - PAN_NO_FIT = 0x01, - PAN_STRAIGHT_ARMS_HORZ = 0x02, - PAN_STRAIGHT_ARMS_WEDGE = 0x03, - PAN_STRAIGHT_ARMS_VERT = 0x04, - /// - /// Straight arms/single-serif. - /// - PAN_STRAIGHT_ARMS_SINGLE_SERIF = 0x05, - PAN_STRAIGHT_ARMS_DOUBLE_SERIF = 0x06, - PAN_BENT_ARMS_HORZ = 0x07, - PAN_BENT_ARMS_WEDGE = 0x08, - PAN_BENT_ARMS_VERT = 0x09, - PAN_BENT_ARMS_SINGLE_SERIF = 0x0A, - PAN_BENT_ARMS_DOUBLE_SERIF = 0x0B - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/BackgroundMode.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/BackgroundMode.cs deleted file mode 100644 index a931a90b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/BackgroundMode.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The BackgroundMode enumeration is used to specify the background mode to be used with text, hatched brushes, and pen styles that are not solid. The background mode determines how to combine the background with foreground text, hatched brushes, and pen styles that are not solid lines. - /// - /// - /// 2.1.4 BackgroundMode Enumeration - /// - internal enum BackgroundMode - { - TRANSPARENT = 0x0001, - OPAQUE = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorAdjustment.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorAdjustment.cs deleted file mode 100644 index 61ffccfc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorAdjustment.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The ColorAdjustment enumeration is used to specify how the output image should be prepared when the stretch mode is HALFTONE. - /// - /// - /// 2.1.5 ColorAdjustment Enumeration - /// - internal enum ColorAdjustment - { - /// - /// Specifies that the negative of the original image SHOULD be displayed. - /// - CA_NEGATIVE = 0x0001, - - /// - /// Specifies that a logarithmic process SHOULD be applied to the final density of the output colors. This will increase the color contrast when the luminance is low. - /// - CA_LOG_FILTER = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTarget.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTarget.cs deleted file mode 100644 index 82558378..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTarget.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The ColorMatchToTarget enumeration is used to determine whether a color profile has been embedded in the metafile. - /// - /// - /// 2.1.6 ColorMatchToTarget Enumeration - /// - internal enum ColorMatchToTarget - { - /// - /// Indicates that a color profile has not been embedded in the metafile. - /// - ColorMatchToTargetNotembedded = 0x00000000, - - /// - /// Indicates that a color profile has been embedded in the metafile. - /// - ColorMatchToTargetEmbedded = 0x00000001 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTargetAction.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTargetAction.cs deleted file mode 100644 index 791e9331..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorMatchToTargetAction.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - internal enum ColorMatchToTargetAction : uint - { - Enable = 0x00000000, - Disable = 0x00000001, - DeleteTransform = 0x00000002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorSpace.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorSpace.cs deleted file mode 100644 index 38f72ffb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ColorSpace.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The ColorSpace enumeration is used to specify when to turn color proofing on and off, and when to delete transforms. - /// - /// - /// 2.1.7 ColorSpace Enumeration - /// - internal enum ColorSpace - { - /// - /// Maps colors to the target device's color gamut. This enables color proofing. All subsequent draw commands to the playback device context will render colors as they would appear on the target device. - /// - CsEnable = 0x00000001, - - /// - /// Disables color proofing. - /// - CsDisable = 0x00000002, - - /// - /// If color management is enabled for the target profile, disables it and deletes the concatenated transform. - /// - CsDeleteTransform = 0x00000003 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/Contrast.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/Contrast.cs deleted file mode 100644 index 030561e2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/Contrast.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The Contrast enumeration defines values for one of the characteristics in the PANOSE system for classifying typefaces. - /// - /// - /// 2.1.8 Contrast Enumeration - /// - internal enum Contrast - { - PAN_ANY = 0x00, - PAN_NO_FIT = 0x01, - PAN_CONTRAST_NONE = 0x02, - PAN_CONTRAST_VERY_LOW = 0x03, - PAN_CONTRAST_LOW = 0x04, - PAN_CONTRAST_MEDIUM_LOW = 0x05, - PAN_CONTRAST_MEDIUM = 0x06, - PAN_CONTRAST_MEDIUM_HIGH = 0x07, - PAN_CONTRAST_HIGH = 0x08, - PAN_CONTRAST_VERY_HIGH = 0x09 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/DIBColors.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/DIBColors.cs deleted file mode 100644 index e600f785..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/DIBColors.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The DIBColors enumeration defines how to interpret the values in the color table of a DIB. - /// - /// - /// 2.1.9 DIBColors Enumeration - /// - internal enum DIBColors - { - /// - /// The color table contains literal RGB values. - /// - DibRgbColors = 0x00, - - /// - /// The color table consists of an array of 16-bit indexes into the LogPalette object (section 2.2.17) that is currently defined in the playback device context. - /// - DibPalColors = 0x01, - - /// - /// No color table exists. The pixels in the DIB are indices into the current logical palette in the playback device context. - /// - DibPalIndices = 0x02 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/EmrComment.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/EmrComment.cs deleted file mode 100644 index 6c7b9518..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/EmrComment.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The EmrComment enumeration defines the types of data that a public comment record can contain, as specified in section 2.3.3.4. - /// - /// - /// 2.1.10 EmrComment Enumeration - /// - internal enum EmrComment : uint - { - /// - /// This comment record contains a specification of an image in WMF. See [MS-WMF] for more information. - /// - EmrCommentWindowsMetafile = 0x80000001, - - /// - /// This comment record identifies the beginning of a group of drawing records. It identifies an object within an EMF metafile. - /// - EmrCommentBegingroup = 0x00000002, - - /// - /// This comment record identifies the end of a group of drawing records. For every EMR_COMMENT_BEGINGROUP record, an EMR_COMMENT_ENDGROUP record MUST be included in the metafile, and they MAY be nested. - /// - EMR_COMMENT_ENDGROUP = 0x00000003, - - /// - /// This comment record allows multiple definitions of an image to be included in the metafile. Using this comment, for example, an application can include encapsulated PostScript text as well as an EMF definition of an image. - /// - EMR_COMMENT_MULTIFORMATS = 0x40000004, - - /// - /// This comment record is reserved and MUST NOT be used in an EMF metafile. - /// - EMR_COMMENT_UNICODE_STRING = 0x00000040, - - /// - /// This comment record is reserved and MUST NOT be used in an EMF metafile. - /// - EMR_COMMENT_UNICODE_END = 0x00000080 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ExtTextOutOptions.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ExtTextOutOptions.cs deleted file mode 100644 index f8af380b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ExtTextOutOptions.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The ExtTextOutOptions enumeration specifies parameters that control various aspects of the output of text by EMR_SMALLTEXTOUT (section 2.3.5.37) records and in EmrText objects. - /// - /// - /// 2.1.11 ExtTextOutOptions Enumeration - /// - internal enum ExtTextOutOptions - { - /// - /// This bit indicates that the current background color SHOULD be used to fill the rectangle. - /// - ETO_OPAQUE = 0x00000002, - /// - /// This bit indicates that the text SHOULD be clipped to the rectangle. - /// - ETO_CLIPPED = 0x00000004, - - /// - /// This bit indicates that the codes for characters in an output text string are actually indexes of the character glyphs in a TrueType font. Glyph indexes are font-specific, so to display the correct characters on playback, the font that is used MUST be identical to the font used to generate the indexes. - /// - ETO_GLYPH_INDEX = 0x00000010, - - ETO_RTLREADING = 0x00000080, - /// - /// This bit indicates that the record does not specify a bounding rectangle for the text output. - /// - ETO_NO_RECT = 0x00000100, - ETO_SMALL_CHARS = 0x00000200, - ETO_NUMERICSLOCAL = 0x00000400, - ETO_NUMERICSLATIN = 0x00000800, - ETO_IGNORELANGUAGE = 0x00001000, - ETO_PDY = 0x00002000, - ETO_REVERSE_INDEX_MAP = 0x00010000 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FamilyType.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FamilyType.cs deleted file mode 100644 index e6ff0dfd..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FamilyType.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The FamilyType enumeration defines values for one of the characteristics in the PANOSE system for classifying typefaces. - /// - /// - /// 2.1.12 FamilyType Enumeration - /// - internal enum FamilyType - { - /// - /// Any. - /// - PanAny = 0x00, - - /// - /// No fit. - /// - PanNoFit = 0x01, - PanFamilyTextDisplay = 0x02, - PanFamilyScript = 0x03, - PanFamilyDecorative = 0x04, - PanFamilyPictorial = 0x05 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FormatSignature.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FormatSignature.cs deleted file mode 100644 index a4d82fbf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/FormatSignature.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The FormatSignature enumeration defines values that are used to identify the format of embedded data in EMF records. - /// - /// - /// 2.1.14 FormatSignature Enumeration - /// - internal enum FormatSignature - { - /// - /// The value of this member is the sequence of ASCII characters "FME ", which happens to be the reverse of the string "EMF", and it denotes EMF record data. - /// - ENHMETA_SIGNATURE, - - /// - /// The value of this member is the sequence of ASCII characters "FSPE", which happens to be the reverse of the string "EPSF", and it denotes encapsulated PostScript (EPS) format data. - /// - EPS_SIGNATURE - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GradientFill.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GradientFill.cs deleted file mode 100644 index 7626091d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GradientFill.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The GradientFill enumeration defines the modes for gradient fill operations. - /// - /// - /// 2.1.15 GradientFill Enumeration - /// - internal enum GradientFill - { - /// - /// A mode in which color interpolation is performed along a gradient from the left to the right edges of a rectangle. - /// - GradientFillRectH = 0x00000000, - - /// - /// A mode in which color interpolation is performed along a gradient from the top to the bottom edges of a rectangle. - /// - GradientFillRectV = 0x00000001, - - /// - /// A mode in which color interpolation is performed between vertexes of a triangle. - /// - GradientFillTriangle = 0x00000002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GraphicsMode.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GraphicsMode.cs deleted file mode 100644 index 1df1d67b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/GraphicsMode.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The GraphicsMode enumeration is used to specify how to interpret shape data such as rectangle coordinates. - /// - /// - /// 2.1.16 GraphicsMode Enumeration - /// - internal enum GraphicsMode - { - /// - /// TrueType text MUST be written from left to right and right side up, even if the rest of the graphics are rotated about the x-axis or y-axis because of the current world-to- - /// device transformation in the playback device context. Only the height of the text SHOULD be scaled. - /// - GM_COMPATIBLE = 0x00000001, - GM_ADVANCED = 0x00000002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/HatchStyle.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/HatchStyle.cs deleted file mode 100644 index d4b28ccb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/HatchStyle.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - /// - /// The HatchStyle enumeration is an extension to the WMF HatchStyle enumeration ([MS-WMF] section 2.1.1.12). - /// - /// - /// 2.1.17 HatchStyle Enumeration - /// - internal enum HatchStyle - { - HS_SOLIDCLR = 0x0006, - HS_DITHEREDCLR = 0x0007, - HS_SOLIDTEXTCLR = 0x0008, - HS_DITHEREDTEXTCLR = 0x0009, - HS_SOLIDBKCLR = 0x000A, - HS_DITHEREDBKCLR = 0x000B - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmMode.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmMode.cs deleted file mode 100644 index beb65d63..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - internal enum IcmMode : uint - { - ICM_OFF = 0x0001, - ICM_ON = 0x0002, - ICM_QUERY = 0x0003, - ICM_DONE_OUTSIDEDC = 0x0004 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmProfileFlags.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmProfileFlags.cs deleted file mode 100644 index 0d136f9f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/IcmProfileFlags.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - using System; - - [Flags] - internal enum IcmProfileFlags : uint - { - None = 0x00000000, - SourceLinked = 0x00000001, - EmbedProfile = 0x00000002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ModifyWorldTransformMode.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ModifyWorldTransformMode.cs deleted file mode 100644 index 41f85af3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/ModifyWorldTransformMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - internal enum ModifyWorldTransformMode : uint - { - MWT_IDENTITY = 0x0001, - MWT_LEFTMULTIPLY = 0x0002, - MWT_RIGHTMULTIPLY = 0x0003, - MWT_SET = 0x0004 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RecordType.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RecordType.cs deleted file mode 100644 index 733c7137..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RecordType.cs +++ /dev/null @@ -1,125 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - internal enum RecordType : uint - { - EMR_HEADER = 0x00000001, - EMR_POLYBEZIER = 0x00000002, - EMR_POLYGON = 0x00000003, - EMR_POLYLINE = 0x00000004, - EMR_POLYBEZIERTO = 0x00000005, - EMR_POLYLINETO = 0x00000006, - EMR_POLYPOLYLINE = 0x00000007, - EMR_POLYPOLYGON = 0x00000008, - EMR_SETWINDOWEXTEX = 0x00000009, - EMR_SETWINDOWORGEX = 0x0000000A, - EMR_SETVIEWPORTEXTEX = 0x0000000B, - EMR_SETVIEWPORTORGEX = 0x0000000C, - EMR_SETBRUSHORGEX = 0x0000000D, - EMR_EOF = 0x0000000E, - EMR_SETPIXELV = 0x0000000F, - EMR_SETMAPPERFLAGS = 0x00000010, - EMR_SETMAPMODE = 0x00000011, - EMR_SETBKMODE = 0x00000012, - EMR_SETPOLYFILLMODE = 0x00000013, - EMR_SETROP2 = 0x00000014, - EMR_SETSTRETCHBLTMODE = 0x00000015, - EMR_SETTEXTALIGN = 0x00000016, - EMR_SETCOLORADJUSTMENT = 0x00000017, - EMR_SETTEXTCOLOR = 0x00000018, - EMR_SETBKCOLOR = 0x00000019, - EMR_OFFSETCLIPRGN = 0x0000001A, - EMR_MOVETOEX = 0x0000001B, - EMR_SETMETARGN = 0x0000001C, - EMR_EXCLUDECLIPRECT = 0x0000001D, - EMR_INTERSECTCLIPRECT = 0x0000001E, - EMR_SCALEVIEWPORTEXTEX = 0x0000001F, - EMR_SCALEWINDOWEXTEX = 0x00000020, - EMR_SAVEDC = 0x00000021, - EMR_RESTOREDC = 0x00000022, - EMR_SETWORLDTRANSFORM = 0x00000023, - EMR_MODIFYWORLDTRANSFORM = 0x00000024, - EMR_SELECTOBJECT = 0x00000025, - EMR_CREATEPEN = 0x00000026, - EMR_CREATEBRUSHINDIRECT = 0x00000027, - EMR_DELETEOBJECT = 0x00000028, - EMR_ANGLEARC = 0x00000029, - EMR_ELLIPSE = 0x0000002A, - EMR_RECTANGLE = 0x0000002B, - EMR_ROUNDRECT = 0x0000002C, - EMR_ARC = 0x0000002D, - EMR_CHORD = 0x0000002E, - EMR_PIE = 0x0000002F, - EMR_SELECTPALETTE = 0x00000030, - EMR_CREATEPALETTE = 0x00000031, - EMR_SETPALETTEENTRIES = 0x00000032, - EMR_RESIZEPALETTE = 0x00000033, - EMR_REALIZEPALETTE = 0x00000034, - EMR_EXTFLOODFILL = 0x00000035, - EMR_LINETO = 0x00000036, - EMR_ARCTO = 0x00000037, - EMR_POLYDRAW = 0x00000038, - EMR_SETARCDIRECTION = 0x00000039, - EMR_SETMITERLIMIT = 0x0000003A, - EMR_BEGINPATH = 0x0000003B, - EMR_ENDPATH = 0x0000003C, - EMR_CLOSEFIGURE = 0x0000003D, - EMR_FILLPATH = 0x0000003E, - EMR_STROKEANDFILLPATH = 0x0000003F, - EMR_STROKEPATH = 0x00000040, - EMR_FLATTENPATH = 0x00000041, - EMR_WIDENPATH = 0x00000042, - EMR_SELECTCLIPPATH = 0x00000043, - EMR_ABORTPATH = 0x00000044, - EMR_COMMENT = 0x00000046, - EMR_FILLRGN = 0x00000047, - EMR_FRAMERGN = 0x00000048, - EMR_INVERTRGN = 0x00000049, - EMR_PAINTRGN = 0x0000004A, - EMR_EXTSELECTCLIPRGN = 0x0000004B, - EMR_BITBLT = 0x0000004C, - EMR_STRETCHBLT = 0x0000004D, - EMR_MASKBLT = 0x0000004E, - EMR_PLGBLT = 0x0000004F, - EMR_SETDIBITSTODEVICE = 0x00000050, - EMR_STRETCHDIBITS = 0x00000051, - EMR_EXTCREATEFONTINDIRECTW = 0x00000052, - EMR_EXTTEXTOUTA = 0x00000053, - EMR_EXTTEXTOUTW = 0x00000054, - EMR_POLYBEZIER16 = 0x00000055, - EMR_POLYGON16 = 0x00000056, - EMR_POLYLINE16 = 0x00000057, - EMR_POLYBEZIERTO16 = 0x00000058, - EMR_POLYLINETO16 = 0x00000059, - EMR_POLYPOLYLINE16 = 0x0000005A, - EMR_POLYPOLYGON16 = 0x0000005B, - EMR_POLYDRAW16 = 0x0000005C, - EMR_CREATEMONOBRUSH = 0x0000005D, - EMR_CREATEDIBPATTERNBRUSHPT = 0x0000005E, - EMR_EXTCREATEPEN = 0x0000005F, - EMR_POLYTEXTOUTA = 0x00000060, - EMR_POLYTEXTOUTW = 0x00000061, - EMR_SETICMMODE = 0x00000062, - EMR_CREATECOLORSPACE = 0x00000063, - EMR_SETCOLORSPACE = 0x00000064, - EMR_DELETECOLORSPACE = 0x00000065, - EMR_GLSRECORD = 0x00000066, - EMR_GLSBOUNDEDRECORD = 0x00000067, - EMR_PIXELFORMAT = 0x00000068, - EMR_DRAWESCAPE = 0x00000069, - EMR_EXTESCAPE = 0x0000006A, - EMR_SMALLTEXTOUT = 0x0000006C, - EMR_FORCEUFIMAPPING = 0x0000006D, - EMR_NAMEDESCAPE = 0x0000006E, - EMR_COLORCORRECTPALETTE = 0x0000006F, - EMR_SETICMPROFILEA = 0x00000070, - EMR_SETICMPROFILEW = 0x00000071, - EMR_ALPHABLEND = 0x00000072, - EMR_SETLAYOUT = 0x00000073, - EMR_TRANSPARENTBLT = 0x00000074, - EMR_GRADIENTFILL = 0x00000076, - EMR_SETLINKEDUFIS = 0x00000077, - EMR_SETTEXTJUSTIFICATION = 0x00000078, - EMR_COLORMATCHTOTARGETW = 0x00000079, - EMR_CREATECOLORSPACEW = 0x0000007A - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RegionMode.cs b/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RegionMode.cs deleted file mode 100644 index 3e4a8f1f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Enumerations/RegionMode.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Enumerations -{ - internal enum RegionMode : uint - { - RGN_AND = 0x0001, - RGN_OR = 0x0002, - RGN_XOR = 0x0003, - RGN_DIFF = 0x0004, - RGN_COPY = 0x0005 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/ColorAdjustment.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/ColorAdjustment.cs deleted file mode 100644 index b91aa296..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/ColorAdjustment.cs +++ /dev/null @@ -1,110 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - /// - /// The ColorAdjustment object defines values for adjusting the colors in source bitmaps in bit-block transfers. - /// - /// - /// 2.2.2 ColorAdjustment Object - /// - internal class ColorAdjustment - { - /// - /// A 16-bit unsigned integer that specifies the size in bytes of this object. This MUST be 0x0018. - /// - public ushort Size { get; set; } - - /// - /// A 16-bit unsigned integer that specifies how to prepare the output image. This field can be set to NULL or to any combination of values in the ColorAdjustment enumeration (section 2.1.5). - /// - public ushort Values { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the type of standard light source under which the image is viewed, from the Illuminant enumeration (section 2.1.19). - /// - public ushort IlluminantIndex { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the nth power gamma correction value for the red primary of the source colors. This value SHOULD be in the range from 2,500 to 65,000. A value of 10,000 means gamma correction MUST NOT be performed. - /// - public ushort RedGamma { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the nth power gamma correction value for the green primary of the source colors. This value SHOULD be in the range from 2,500 to 65,000. A value of 10,000 means gamma correction MUST NOT be performed. - /// - public ushort GreenGamma { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the nth power gamma correction value for the blue primary of the source colors. This value SHOULD be in the range from 2,500 to 65,000. A value of 10,000 means gamma correction MUST NOT be performed. - /// - public ushort BlueGamma { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the black reference for the source colors. Any colors that are darker than this are treated as black. This value SHOULD be in the range from zero to 4,000. - /// - public ushort ReferenceBlack { get; set; } - - /// - /// A 16-bit unsigned integer that specifies the white reference for the source colors. Any colors that are lighter than this are treated as white. This value SHOULD be in the range from 6,000 to 10,000. - /// - public ushort ReferenceWhite { get; set; } - - /// - /// A 16-bit signed integer that specifies the amount of contrast to be applied to the source object. This value SHOULD be in the range from –100 to 100. A value of zero means contrast adjustment MUST NOT be performed. - /// - public short Contrast { get; set; } - - /// - /// A 16-bit signed integer that specifies the amount of brightness to be applied to the source object. This value SHOULD be in the range from –100 to 100. A value of zero means brightness adjustment MUST NOT be performed. - /// - public short Brightness { get; set; } - - /// - /// A 16-bit signed integer that specifies the amount of colorfulness to be applied to the source object. This value SHOULD be in the range from –100 to 100. A value of zero means colorfulness adjustment MUST NOT be performed. - /// - public short Colorfulness { get; set; } - - /// - /// A 16-bit signed integer that specifies the amount of red or green tint adjustment to be applied to the source object. This value SHOULD be in the range from –100 to 100. Positive numbers adjust towards red and negative numbers adjust towards green. A value of zero means tint adjustment MUST NOT be performed. - /// - public short RedGreenTint { get; set; } - - public ColorAdjustment() - { - Size = 0x0018; - } - - public void Read(BinaryReader reader) - { - Size = reader.ReadUInt16(); - Values = reader.ReadUInt16(); - IlluminantIndex = reader.ReadUInt16(); - RedGamma = reader.ReadUInt16(); - GreenGamma = reader.ReadUInt16(); - BlueGamma = reader.ReadUInt16(); - ReferenceBlack = reader.ReadUInt16(); - ReferenceWhite = reader.ReadUInt16(); - Contrast = reader.ReadInt16(); - Brightness = reader.ReadInt16(); - Colorfulness = reader.ReadInt16(); - RedGreenTint = reader.ReadInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(Size); - writer.Write(Values); - writer.Write(IlluminantIndex); - writer.Write(RedGamma); - writer.Write(GreenGamma); - writer.Write(BlueGamma); - writer.Write(ReferenceBlack); - writer.Write(ReferenceWhite); - writer.Write(Contrast); - writer.Write(Brightness); - writer.Write(Colorfulness); - writer.Write(RedGreenTint); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/EmrText.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/EmrText.cs deleted file mode 100644 index 91442dd4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/EmrText.cs +++ /dev/null @@ -1,167 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EmrText object contains values for text output. - /// - /// - /// 2.2.5 EmrText Object - MS-EMF Page 56 - /// - internal class EmrText - { - /// - /// A WMF PointL object ([MS-WMF] section 2.2.2.15) that specifies the coordinates of the reference point used to position the string. The reference point is defined by the last EMR_SETTEXTALIGN record (section 2.3.11.25). - /// If no such record has been set, the default alignment is TA_LEFT,TA_TOP. - /// - public PointL Reference { get; set; } - - /// - /// A 32-bit unsigned integer that specifies the number of characters in the string. - /// - public uint Chars { get; set; } - - /// - /// A 32-bit unsigned integer that specifies the offset to the output string, in bytes, from the start of the record in which this object is contained. - /// This value MUST be 8- or 16-bit aligned, according to the character format. - /// - public uint offString { get; set; } - - /// - /// A 32-bit unsigned integer that specifies how to use the rectangle specified in the Rectangle field. - /// This field can be a combination of more than one ExtTextOutOptions enumeration (section 2.1.11) values. - /// - public ExtTextOutOptions Options { get; set; } - - /// - /// An optional WMF RectL object ([MS-WMF] section 2.2.2.19) that defines a clipping and/or opaquing rectangle in logical units. - /// This rectangle is applied to the text output performed by the containing record. - /// - public RectL Rectangle { get; set; } - - /// - /// A 32-bit unsigned integer that specifies the offset to an intercharacter spacing array, in bytes, from the start of the record in which this object is contained. This value MUST be 32-bit aligned. - /// - public uint offDx { get; set; } - - /// - /// An optional number of unused bytes. The OutputString field is not required to follow immediately the preceding portion of this structure. - /// - public byte[] UndefinedSpace1 { get; set; } = Array.Empty(); - - /// - /// An array of characters that specify the string to output. The location of this field is specified by the value of offString in bytes from the start of this record. The number of characters is specified by the value of Chars. - /// - public byte[] OutputString { get; set; } = Array.Empty(); - - /// - /// An optional number of unused bytes. The OutputDx field is not required to follow immediately the preceding portion of this structure. - /// - public byte[] UndefinedSpace2 { get; set; } = Array.Empty(); - - /// - /// An array of 32-bit unsigned integers that specify the output spacing between the origins of adjacent character cells in logical units. - /// The location of this field is specified by the value of offDx in bytes from the start of this record. - /// If spacing is defined, this field contains the same number of values as characters in the output string. - /// If the Options field of the EmrText object contains the ETO_PDY flag, then this buffer contains twice as many values as there are characters in the output string, one horizontal and one vertical offset for each, in that order. - /// If ETO_RTLREADING is specified, characters are laid right to left instead of left to right. No other options affect the interpretation of this field. - /// - public byte[] OutputDx { get; set; } = Array.Empty(); - - public void Read(BinaryReader reader) - { - long startPosition = reader.BaseStream.Position; - - var reference = new PointL(); - reference.Read(reader); - this.Reference = reference; - Chars = reader.ReadUInt32(); - offString = reader.ReadUInt32(); - Options = (ExtTextOutOptions)reader.ReadUInt32(); - var rectangle = new RectL(); - rectangle.Read(reader); - this.Rectangle = rectangle; - offDx = reader.ReadUInt32(); - - long headerSize = reader.BaseStream.Position - startPosition; - - int undefinedSpace1Length = (int)(offString - headerSize); - if (undefinedSpace1Length < 0) throw new InvalidDataException("Invalid offString value."); - if (undefinedSpace1Length > 0) - { - UndefinedSpace1 = reader.ReadBytes(undefinedSpace1Length); - } - - OutputString = reader.ReadBytes((int)Chars); - - long currentOffset = headerSize + undefinedSpace1Length + Chars; - int undefinedSpace2Length = (int)(offDx - currentOffset); - if (undefinedSpace2Length < 0) throw new InvalidDataException("Invalid offDx value."); - if (undefinedSpace2Length > 0) - { - UndefinedSpace2 = reader.ReadBytes(undefinedSpace2Length); - } - - int outputDxLength = (int)(reader.BaseStream.Length - reader.BaseStream.Position); - if (outputDxLength > 0) - { - OutputDx = reader.ReadBytes(outputDxLength); - } - } - - public void Write(BinaryWriter writer) - { - const uint headerSize = 40; - uint chars = Chars == 0 ? (uint)OutputString.Length : Chars; - uint offStringValue = offString == 0 ? headerSize + (uint)UndefinedSpace1.Length : offString; - uint offDxValue = offDx == 0 ? offStringValue + chars + (uint)UndefinedSpace2.Length : offDx; - - int undefinedSpace1Length = (int)Math.Max(0, offStringValue - headerSize); - int undefinedSpace2Length = (int)Math.Max(0, offDxValue - (offStringValue + chars)); - - Reference.Write(writer); - writer.Write(chars); - writer.Write(offStringValue); - writer.Write((uint)Options); - Rectangle.Write(writer); - writer.Write(offDxValue); - - if (undefinedSpace1Length > 0) - { - if (UndefinedSpace1.Length >= undefinedSpace1Length) - { - writer.Write(UndefinedSpace1, 0, undefinedSpace1Length); - } - else - { - writer.Write(UndefinedSpace1); - writer.Write(new byte[undefinedSpace1Length - UndefinedSpace1.Length]); - } - } - - writer.Write(OutputString, 0, (int)Math.Min(chars, (uint)OutputString.Length)); - if (chars > OutputString.Length) - { - writer.Write(new byte[chars - OutputString.Length]); - } - - if (undefinedSpace2Length > 0) - { - if (UndefinedSpace2.Length >= undefinedSpace2Length) - { - writer.Write(UndefinedSpace2, 0, undefinedSpace2Length); - } - else - { - writer.Write(UndefinedSpace2); - writer.Write(new byte[undefinedSpace2Length - UndefinedSpace2.Length]); - } - } - - writer.Write(OutputDx); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientRectangle.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientRectangle.cs deleted file mode 100644 index b0ea5774..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientRectangle.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - internal class GradientRectangle - { - public uint UpperLeft; - - public uint LowerRight; - - public void Read(BinaryReader reader) - { - UpperLeft = reader.ReadUInt32(); - LowerRight = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(UpperLeft); - writer.Write(LowerRight); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientTriangle.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientTriangle.cs deleted file mode 100644 index edf9f438..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/GradientTriangle.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - internal class GradientTriangle - { - public uint Vertex1; - - public uint Vertex2; - - public uint Vertex3; - - public void Read(BinaryReader reader) - { - Vertex1 = reader.ReadUInt32(); - Vertex2 = reader.ReadUInt32(); - Vertex3 = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(Vertex1); - writer.Write(Vertex2); - writer.Write(Vertex3); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/Header.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/Header.cs deleted file mode 100644 index e9683ecb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/Header.cs +++ /dev/null @@ -1,116 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The Header object defines the EMF metafile header. - /// It specifies properties of the device on which the image in the metafile was created. - /// - /// - /// 2.2.9 Header Object - /// - internal class Header - { - /// - /// A WMF RectL object ([MS-WMF] section 2.2.2.19) that specifies the rectangular inclusive-inclusive bounds in device units of the smallest rectangle that can be drawn around the image stored in the metafile. - /// - public RectL Bounds; - - /// - /// A WMF RectL object that specifies the rectangular inclusive-inclusive dimensions, in .01 millimeter units, of a rectangle that surrounds the image stored in the metafile. - /// - public RectL Frame; - - /// - /// A 32-bit unsigned integer that specifies the record signature. This MUST be ENHMETA_SIGNATURE, from the FormatSignature enumeration (section 2.1.14). - /// - public uint RecordSignature; - - /// - /// A 32-bit unsigned integer that specifies EMF metafile interoperability. This SHOULD be 0x00010000. - /// - public uint Version; - - /// - /// A 32-bit unsigned integer that specifies the size of the metafile, in bytes. - /// - public uint Bytes; - - /// - /// A 32-bit unsigned integer that specifies the number of records in the metafile. - /// - public uint Records; - - /// - /// A 16-bit unsigned integer that specifies the number of graphics objects that will be used during the processing of the metafile. - /// - public ushort Handles; - - public ushort Reserved; - - /// - /// A 32-bit unsigned integer that specifies the number of characters in the array that contains the description of the metafile's contents. This is zero if there is no description string. - /// - public uint nDescription; - - /// - /// A 32-bit unsigned integer that specifies the offset from the beginning of this record to the array that contains the description of the metafile's contents. - /// - public uint offDescription; - - /// - /// A 32-bit unsigned integer that specifies the number of entries in the metafile palette. The palette is located in the EMR_EOF record. - /// - public uint nPalEntries; - - /// - /// A WMF SizeL object ([MS-WMF] section 2.2.2.22) that specifies the size of the reference device, in pixels. - /// - public SizeL Device; - - /// - /// A WMF SizeL object that specifies the size of the reference device, in millimeters. - /// - public SizeL Millimeters; - - public void Read(BinaryReader reader) - { - this.Bounds = new RectL(); - this.Bounds.Read(reader); - this.Frame = new RectL(); - this.Frame.Read(reader); - this.RecordSignature = reader.ReadUInt32(); - this.Version = reader.ReadUInt32(); - this.Bytes = reader.ReadUInt32(); - this.Records = reader.ReadUInt32(); - this.Handles = reader.ReadUInt16(); - this.Reserved = reader.ReadUInt16(); - this.nDescription = reader.ReadUInt32(); - this.offDescription = reader.ReadUInt32(); - this.nPalEntries = reader.ReadUInt32(); - this.Device = new SizeL(); - this.Device.Read(reader); - this.Millimeters = new SizeL(); - this.Millimeters.Read(reader); - } - - public void Write(BinaryWriter writer) - { - this.Bounds.Write(writer); - this.Frame.Write(writer); - writer.Write(this.RecordSignature); - writer.Write(this.Version); - writer.Write(this.Bytes); - writer.Write(this.Records); - writer.Write(this.Handles); - writer.Write(this.Reserved); - writer.Write(this.nDescription); - writer.Write(this.offDescription); - writer.Write(this.nPalEntries); - this.Device.Write(writer); - this.Millimeters.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension1.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension1.cs deleted file mode 100644 index ed7bd9ed..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension1.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - /// - /// The HeaderExtension1 object defines the first extension to the EMF metafile header. It adds support for a PixelFormatDescriptor object (section 2.2.22) and OpenGL [OPENGL] records (section 2.3.9). - /// - /// - /// 2.2.10 HeaderExtension1 Object - /// - internal class HeaderExtension1 - { - /// - /// A 32-bit unsigned integer that specifies the size of the PixelFormatDescriptor object. This MUST be 0x00000000 if no pixel format is set. - /// - public uint cbPixelFormat; - - /// - /// A 32-bit unsigned integer that specifies the offset to the PixelFormatDescriptor object. This MUST be 0x00000000 if no pixel format is set. - /// - public uint offPixelFormat; - - /// - /// A 32-bit unsigned integer that indicates whether OpenGL commands are present in the metafile. - /// - public uint bOpenGL; - - public void Read(BinaryReader reader) - { - this.cbPixelFormat = reader.ReadUInt32(); - this.offPixelFormat = reader.ReadUInt32(); - this.bOpenGL = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.cbPixelFormat); - writer.Write(this.offPixelFormat); - writer.Write(this.bOpenGL); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension2.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension2.cs deleted file mode 100644 index 52b2976d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/HeaderExtension2.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - /// - /// The HeaderExtension2 object defines the second extension to the EMF metafile header. It adds the ability to measure device surfaces in micrometers, which enhances the resolution and scalability of EMF metafiles. - /// - /// - /// 2.2.11 HeaderExtension2 Object - /// - internal class HeaderExtension2 - { - /// - /// The 32-bit horizontal size of the display device for which the metafile image was generated, in micrometers. - /// - public uint MicrometersX; - - /// - /// The 32-bit vertical size of the display device for which the metafile image was generated, in micrometers. - /// - public uint MicrometersY; - - public void Read(BinaryReader reader) - { - this.MicrometersX = reader.ReadUInt32(); - this.MicrometersY = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.MicrometersX); - writer.Write(this.MicrometersY); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/TriVertex.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/TriVertex.cs deleted file mode 100644 index bd83c6a4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/TriVertex.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - internal class TriVertex - { - public int X; - - public int Y; - - public ushort Red; - - public ushort Green; - - public ushort Blue; - - public ushort Alpha; - - public void Read(BinaryReader reader) - { - X = reader.ReadInt32(); - Y = reader.ReadInt32(); - Red = reader.ReadUInt16(); - Green = reader.ReadUInt16(); - Blue = reader.ReadUInt16(); - Alpha = reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - writer.Write(Red); - writer.Write(Green); - writer.Write(Blue); - writer.Write(Alpha); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Objects/XForm.cs b/src/MiniPdf/Drawing/Metafile/Emf/Objects/XForm.cs deleted file mode 100644 index 3928cd60..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Objects/XForm.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Objects -{ - using System.IO; - - internal class XForm - { - public float M11; - - public float M12; - - public float M21; - - public float M22; - - public float Dx; - - public float Dy; - - public void Read(BinaryReader reader) - { - M11 = reader.ReadSingle(); - M12 = reader.ReadSingle(); - M21 = reader.ReadSingle(); - M22 = reader.ReadSingle(); - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(M11); - writer.Write(M12); - writer.Write(M21); - writer.Write(M22); - writer.Write(Dx); - writer.Write(Dy); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ALPHABLEND.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ALPHABLEND.cs deleted file mode 100644 index 7e4d07ba..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ALPHABLEND.cs +++ /dev/null @@ -1,125 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_ALPHABLEND : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int CxDest; - - public int CyDest; - - public uint BlendOperation; - - public int XSrc; - - public int YSrc; - - public XForm XFormSrc { get; set; } = new(); - - public uint ColorAdjust; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public int CxSrc; - - public int CySrc; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_ALPHABLEND() - { - Header = new RecordHeader { Type = RecordType.EMR_ALPHABLEND }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - BlendOperation = reader.ReadUInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - XFormSrc.Read(reader); - ColorAdjust = reader.ReadUInt32(); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 108; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write(BlendOperation); - writer.Write(XSrc); - writer.Write(YSrc); - XFormSrc.Write(writer); - writer.Write(ColorAdjust); - writer.Write((uint)UsageSrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(CxSrc); - writer.Write(CySrc); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ANGLEARC.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ANGLEARC.cs deleted file mode 100644 index 31f4d842..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ANGLEARC.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_ANGLEARC record specifies a line segment of an arc. The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the given radius and center. - /// The length of the arc is defined by the given start and sweep angles. - /// - /// - /// 2.3.5.1 EMR_ANGLEARC Record - /// - internal class EMR_ANGLEARC : Record - { - /// - /// A 64-bit WMF PointL object, specified in [MS-WMF] section 2.2.2.15, which specifies the logical coordinates of the circle's center. - /// - public PointL Center; - - public uint Radius; - - public float StartAngle; - - public float SweepAngle; - - public override void Read(BinaryReader reader) - { - this.Center = new PointL(); - this.Center.Read(reader); - this.Radius = reader.ReadUInt32(); - this.StartAngle = reader.ReadSingle(); - this.SweepAngle = reader.ReadSingle(); - } - - public override void Write(BinaryWriter writer) - { - this.Center.Write(writer); - writer.Write(this.Radius); - writer.Write(this.StartAngle); - writer.Write(this.SweepAngle); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARC.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARC.cs deleted file mode 100644 index d1d70adf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARC.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_ARC record specifies an elliptical arc. - /// - /// - /// 2.3.5.2 EMR_ARC Record - /// - internal class EMR_ARC : Record - { - /// - /// A 128-bit WMF RectL object, specified in [MS-WMF] section 2.2.2.19, which specifies the inclusive-inclusive bounding rectangle. - /// - public RectL Box; - - /// - /// A 64-bit WMF PointL object, specified in [MS-WMF] section 2.2.2.15, which specifies the coordinates, in logical units, of the ending point of the radial line defining the starting point of the arc. - /// - public PointL Start; - - /// - /// A 64-bit WMF PointL object that specifies the coordinates, in logical units, of the ending point of the radial line defining the ending point of the arc. - /// - public PointL End; - - public override void Read(BinaryReader reader) - { - this.Box = new RectL(); - this.Box.Read(reader); - this.Start = new PointL(); - this.Start.Read(reader); - this.End = new PointL(); - this.End.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - this.Box.Write(writer); - this.Start.Write(writer); - this.End.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARCTO.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARCTO.cs deleted file mode 100644 index eef5ffb1..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ARCTO.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_ARCTO record specifies an elliptical arc. It resets the current position to the end point of the arc - /// - /// - /// 2.3.5.3 EMR_ARCTO Record - /// - internal class EMR_ARCTO : Record - { - /// - /// A 128-bit WMF RectL object, specified in [MS-WMF] section 2.2.2.19, which specifies the inclusive-inclusive bounding rectangle. - /// - public RectL Box; - - /// - /// A 64-bit WMF PointL object, specified in [MS-WMF] section 2.2.2.15, which specifies the coordinates of the first radial ending point, in logical units. - /// - public PointL Start; - - /// - /// A 64-bit WMF PointL object that specifies the coordinates of the second radial ending point, in logical units. - /// - public PointL End; - - public override void Read(BinaryReader reader) - { - this.Box = new RectL(); - this.Box.Read(reader); - this.Start = new PointL(); - this.Start.Read(reader); - this.End = new PointL(); - this.End.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - this.Box.Write(writer); - this.Start.Write(writer); - this.End.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_BITBLT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_BITBLT.cs deleted file mode 100644 index 6f67be45..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_BITBLT.cs +++ /dev/null @@ -1,118 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_BITBLT : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int CxDest; - - public int CyDest; - - public Metafile.Wmf.Enumerations.TernaryRasterOperation BitBltRasterOperation; - - public int XSrc; - - public int YSrc; - - public XForm XFormSrc { get; set; } = new(); - - public ColorRef BkColorSrc; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_BITBLT() - { - Header = new RecordHeader { Type = RecordType.EMR_BITBLT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - BitBltRasterOperation = (Metafile.Wmf.Enumerations.TernaryRasterOperation)reader.ReadUInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - XFormSrc.Read(reader); - BkColorSrc.Read(reader); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 100; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write((uint)BitBltRasterOperation); - writer.Write(XSrc); - writer.Write(YSrc); - XFormSrc.Write(writer); - BkColorSrc.Write(writer); - writer.Write((uint)UsageSrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_CHORD.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_CHORD.cs deleted file mode 100644 index baf950dc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_CHORD.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_CHORD record specifies a chord, which is a region bounded by the intersection of an ellipse and a line segment, called a secant. - /// The chord is outlined by using the current pen and filled by using the current brush. - /// - internal class EMR_CHORD : Record - { - /// - /// A 128-bit WMF RectL object, specified in [MS-WMF] section 2.2.2.19, which specifies the inclusive-inclusive bounding rectangle. - /// - public RectL Box; - - /// - /// A 64-bit WMF PointL object, specified in [MS-WMF] section 2.2.2.15, which specifies the logical coordinates of the endpoint of the radial defining the beginning of the chord. - /// - public PointL Start; - - /// - /// A 64-bit WMF PointL object that specifies the logical coordinates of the endpoint of the radial defining the end of the chord. - /// - public PointL End; - - public override void Read(BinaryReader reader) - { - this.Box = new RectL(); - this.Box.Read(reader); - this.Start = new PointL(); - this.Start.Read(reader); - this.End = new PointL(); - this.End.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - this.Box.Write(writer); - this.Start.Write(writer); - this.End.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ELLIPSE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ELLIPSE.cs deleted file mode 100644 index 2a17215d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ELLIPSE.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_ELLIPSE record specifies an ellipse. The center of the ellipse is the center of the specified bounding rectangle. - /// The ellipse is outlined by using the current pen and is filled by using the current brush. - /// - /// - /// 2.3.5.5 EMR_ELLIPSE Record - MS-EMF Page 147 - /// - internal class EMR_ELLIPSE : Record - { - /// - /// A 128-bit WMF RectL object, specified in [MS-WMF] section 2.2.2.19, which specifies the inclusive-inclusive bounding rectangle. - /// - public RectL Box; - - public override void Read(BinaryReader reader) - { - this.Box = new RectL(); - this.Box.Read(reader); - - } - - public override void Write(BinaryWriter writer) - { - this.Box.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EOF.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EOF.cs deleted file mode 100644 index e080010b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EOF.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_EOF : Record - { - public uint NumberOfHandles; - - public ushort Reserved; - - public ushort NumberOfRecords; - - public byte[] EndOfFileData { get; set; } = Array.Empty(); - - public EMR_EOF() - { - Header = new RecordHeader { Type = RecordType.EMR_EOF }; - } - - public override void Read(BinaryReader reader) - { - NumberOfHandles = reader.ReadUInt32(); - Reserved = reader.ReadUInt16(); - NumberOfRecords = reader.ReadUInt16(); - - int extraBytes = Convert.ToInt32(Header.Size) - 16; - if (extraBytes > 0) - { - EndOfFileData = reader.ReadBytes(extraBytes); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(NumberOfHandles); - writer.Write(Reserved); - writer.Write(NumberOfRecords); - writer.Write(EndOfFileData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTFLOODFILL.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTFLOODFILL.cs deleted file mode 100644 index fcdc62fd..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTFLOODFILL.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_EXTFLOODFILL record fills an area of the display surface with the current brush. - /// - /// - /// 2.3.5.6 EMR_EXTFLOODFILL Record - /// - internal class EMR_EXTFLOODFILL : Record - { - - /// - /// A WMF PointL object ([MS-WMF] section 2.2.2.15), which specifies the coordinates, in logical units, where filling begins. - /// - public PointL Start; - - /// - /// A 64-bit WMF PointL object that specifies the coordinates, in logical units, of the ending point of the radial line defining the ending point of the arc. - /// - public ColorRef Color; - - /// - /// A 32-bit unsigned integer that specifies how to use the Color value to determine the area for the flood fill operation. - /// The value MUST be in the FloodFill enumeration (section 2.1.13). - /// - public FloodFill FloodFillMode; - - public override void Read(BinaryReader reader) - { - - this.Start = new PointL(); - this.Start.Read(reader); - this.Color = new ColorRef(); - this.Color.Read(reader); - this.FloodFillMode = (FloodFill)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - this.Start.Write(writer); - this.Color.Write(writer); - writer.Write((uint)this.FloodFillMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTA.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTA.cs deleted file mode 100644 index 45f888c9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTA.cs +++ /dev/null @@ -1,66 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The EMR_EXTTEXTOUTA record draws an ASCII text string using the current font and text colors. - /// - /// - /// 2.3.5.7 EMR_EXTTEXTOUTA Record - MS-EMF Page 149 - /// - internal class EMR_EXTTEXTOUTA : Record - { - /// - /// A WMF RectL object ([MS-WMF] section 2.2.2.19). It is not used and MUST be ignored on receipt. - /// - public RectL Bounds; - - /// - /// A 32-bit unsigned integer that specifies the graphics mode from the GraphicsMode enumeration (section 2.1.16). - /// - public GraphicsMode IGraphicsMode; - - /// - /// A 32-bit floating-point value that specifies the scale factor to apply along the X axis to convert from page space units to .01mm units. - /// This SHOULD be used only if the graphics mode specified by iGraphicsMode is GM_COMPATIBLE. - /// - public float ExScale; - - /// - /// A 32-bit floating-point value that specifies the scale factor to apply along the Y axis to convert from page space units to .01mm units. - /// This SHOULD be used only if the graphics mode specified by iGraphicsMode is GM_COMPATIBLE. - /// - public float EyScale; - - public EmrText EmrText { get; set; } = new(); - - public EMR_EXTTEXTOUTA() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTTEXTOUTA }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - IGraphicsMode = (GraphicsMode)reader.ReadUInt32(); - ExScale = reader.ReadSingle(); - EyScale = reader.ReadSingle(); - EmrText.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - this.Bounds.Write(writer); - writer.Write((uint)this.IGraphicsMode); - writer.Write(this.ExScale); - writer.Write(this.EyScale); - EmrText.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTW.cs deleted file mode 100644 index ec87b1db..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_EXTTEXTOUTW.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_EXTTEXTOUTW : Record - { - public RectL Bounds; - - public GraphicsMode IGraphicsMode; - - public float ExScale; - - public float EyScale; - - public EmrText EmrText { get; set; } = new(); - - public EMR_EXTTEXTOUTW() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTTEXTOUTW }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - IGraphicsMode = (GraphicsMode)reader.ReadUInt32(); - ExScale = reader.ReadSingle(); - EyScale = reader.ReadSingle(); - EmrText.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Bounds.Write(writer); - writer.Write((uint)IGraphicsMode); - writer.Write(ExScale); - writer.Write(EyScale); - EmrText.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_GRADIENTFILL.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_GRADIENTFILL.cs deleted file mode 100644 index 7af8f539..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_GRADIENTFILL.cs +++ /dev/null @@ -1,108 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_GRADIENTFILL : Record - { - public RectL Bounds = new(); - - public uint VertexCount; - - public uint GradientCount; - - public GradientFill Mode; - - public TriVertex[] Vertices { get; set; } = Array.Empty(); - - public GradientRectangle[] GradientRectangles { get; set; } = Array.Empty(); - - public GradientTriangle[] GradientTriangles { get; set; } = Array.Empty(); - - public EMR_GRADIENTFILL() - { - Header = new RecordHeader { Type = RecordType.EMR_GRADIENTFILL }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - VertexCount = reader.ReadUInt32(); - GradientCount = reader.ReadUInt32(); - Mode = (GradientFill)reader.ReadUInt32(); - - Vertices = new TriVertex[VertexCount]; - for (int i = 0; i < VertexCount; i++) - { - var vertex = new TriVertex(); - vertex.Read(reader); - Vertices[i] = vertex; - } - - if (Mode == GradientFill.GradientFillTriangle) - { - GradientTriangles = new GradientTriangle[GradientCount]; - for (int i = 0; i < GradientCount; i++) - { - var triangle = new GradientTriangle(); - triangle.Read(reader); - GradientTriangles[i] = triangle; - } - } - else - { - GradientRectangles = new GradientRectangle[GradientCount]; - for (int i = 0; i < GradientCount; i++) - { - var rectangle = new GradientRectangle(); - rectangle.Read(reader); - GradientRectangles[i] = rectangle; - } - } - } - - public override void Write(BinaryWriter writer) - { - uint vertexCount = VertexCount == 0 ? (uint)Vertices.Length : VertexCount; - - Bounds.Write(writer); - writer.Write(vertexCount); - - if (Mode == GradientFill.GradientFillTriangle) - { - uint gradientCount = GradientCount == 0 ? (uint)GradientTriangles.Length : GradientCount; - writer.Write(gradientCount); - writer.Write((uint)Mode); - for (int i = 0; i < vertexCount; i++) - { - Vertices[i].Write(writer); - } - - for (int i = 0; i < gradientCount; i++) - { - GradientTriangles[i].Write(writer); - } - } - else - { - uint gradientCount = GradientCount == 0 ? (uint)GradientRectangles.Length : GradientCount; - writer.Write(gradientCount); - writer.Write((uint)Mode); - for (int i = 0; i < vertexCount; i++) - { - Vertices[i].Write(writer); - } - - for (int i = 0; i < gradientCount; i++) - { - GradientRectangles[i].Write(writer); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_LINETO.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_LINETO.cs deleted file mode 100644 index 1bf73d68..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_LINETO.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_LINETO : Record - { - public PointL Point; - - public EMR_LINETO() - { - Header = new RecordHeader { Type = RecordType.EMR_LINETO }; - } - - public override void Read(BinaryReader reader) - { - Point = new PointL(); - Point.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Point.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_MASKBLT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_MASKBLT.cs deleted file mode 100644 index 9d447bf4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_MASKBLT.cs +++ /dev/null @@ -1,176 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_MASKBLT : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int CxDest; - - public int CyDest; - - public Metafile.Wmf.Enumerations.TernaryRasterOperation BitBltRasterOperation; - - public int XSrc; - - public int YSrc; - - public XForm XFormSrc { get; set; } = new(); - - public ColorRef BkColorSrc; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public int XMask; - - public int YMask; - - public DIBColors UsageMask; - - public uint OffBmiMask; - - public uint CbBmiMask; - - public uint OffBitsMask; - - public uint CbBitsMask; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public byte[] BmiMask { get; set; } = Array.Empty(); - - public byte[] BitsMask { get; set; } = Array.Empty(); - - public EMR_MASKBLT() - { - Header = new RecordHeader { Type = RecordType.EMR_MASKBLT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - BitBltRasterOperation = (Metafile.Wmf.Enumerations.TernaryRasterOperation)reader.ReadUInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - XFormSrc.Read(reader); - BkColorSrc.Read(reader); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - XMask = reader.ReadInt32(); - YMask = reader.ReadInt32(); - UsageMask = (DIBColors)reader.ReadUInt32(); - OffBmiMask = reader.ReadUInt32(); - CbBmiMask = reader.ReadUInt32(); - OffBitsMask = reader.ReadUInt32(); - CbBitsMask = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - if (CbBmiMask > 0 && OffBmiMask > 0) - { - reader.BaseStream.Position = recordStart + OffBmiMask; - BmiMask = reader.ReadBytes(Convert.ToInt32(CbBmiMask)); - } - - if (CbBitsMask > 0 && OffBitsMask > 0) - { - reader.BaseStream.Position = recordStart + OffBitsMask; - BitsMask = reader.ReadBytes(Convert.ToInt32(CbBitsMask)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmiSrc = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBitsSrc = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - uint cbBmiMask = CbBmiMask == 0 ? (uint)BmiMask.Length : CbBmiMask; - uint cbBitsMask = CbBitsMask == 0 ? (uint)BitsMask.Length : CbBitsMask; - - const uint fixedSizeAfterHeader = 128; - uint cursor = fixedSizeAfterHeader; - - uint offBmiSrc = cbBmiSrc > 0 ? cursor : 0; - cursor += cbBmiSrc; - - uint offBitsSrc = cbBitsSrc > 0 ? cursor : 0; - cursor += cbBitsSrc; - - uint offBmiMask = cbBmiMask > 0 ? cursor : 0; - cursor += cbBmiMask; - - uint offBitsMask = cbBitsMask > 0 ? cursor : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write((uint)BitBltRasterOperation); - writer.Write(XSrc); - writer.Write(YSrc); - XFormSrc.Write(writer); - BkColorSrc.Write(writer); - writer.Write((uint)UsageSrc); - writer.Write(offBmiSrc); - writer.Write(cbBmiSrc); - writer.Write(offBitsSrc); - writer.Write(cbBitsSrc); - writer.Write(XMask); - writer.Write(YMask); - writer.Write((uint)UsageMask); - writer.Write(offBmiMask); - writer.Write(cbBmiMask); - writer.Write(offBitsMask); - writer.Write(cbBitsMask); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - writer.Write(BmiMask); - writer.Write(BitsMask); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PIE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PIE.cs deleted file mode 100644 index 7b7eaa6d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PIE.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_PIE : Record - { - public RectL Box; - - public PointL Start; - - public PointL End; - - public EMR_PIE() - { - Header = new RecordHeader { Type = RecordType.EMR_PIE }; - } - - public override void Read(BinaryReader reader) - { - Box = new RectL(); - Box.Read(reader); - Start = new PointL(); - Start.Read(reader); - End = new PointL(); - End.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Box.Write(writer); - Start.Write(writer); - End.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PLGBLT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PLGBLT.cs deleted file mode 100644 index daffb93d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_PLGBLT.cs +++ /dev/null @@ -1,171 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_PLGBLT : Record - { - public RectL Bounds = new(); - - public PointL[] AptlDest { get; set; } = new[] { new PointL(), new PointL(), new PointL() }; - - public int XSrc; - - public int YSrc; - - public int CxSrc; - - public int CySrc; - - public XForm XFormSrc { get; set; } = new(); - - public ColorRef BkColorSrc; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public int XMask; - - public int YMask; - - public DIBColors UsageMask; - - public uint OffBmiMask; - - public uint CbBmiMask; - - public uint OffBitsMask; - - public uint CbBitsMask; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public byte[] BmiMask { get; set; } = Array.Empty(); - - public byte[] BitsMask { get; set; } = Array.Empty(); - - public EMR_PLGBLT() - { - Header = new RecordHeader { Type = RecordType.EMR_PLGBLT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - AptlDest[0].Read(reader); - AptlDest[1].Read(reader); - AptlDest[2].Read(reader); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - XFormSrc.Read(reader); - BkColorSrc.Read(reader); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - XMask = reader.ReadInt32(); - YMask = reader.ReadInt32(); - UsageMask = (DIBColors)reader.ReadUInt32(); - OffBmiMask = reader.ReadUInt32(); - CbBmiMask = reader.ReadUInt32(); - OffBitsMask = reader.ReadUInt32(); - CbBitsMask = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - if (CbBmiMask > 0 && OffBmiMask > 0) - { - reader.BaseStream.Position = recordStart + OffBmiMask; - BmiMask = reader.ReadBytes(Convert.ToInt32(CbBmiMask)); - } - - if (CbBitsMask > 0 && OffBitsMask > 0) - { - reader.BaseStream.Position = recordStart + OffBitsMask; - BitsMask = reader.ReadBytes(Convert.ToInt32(CbBitsMask)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmiSrc = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBitsSrc = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - uint cbBmiMask = CbBmiMask == 0 ? (uint)BmiMask.Length : CbBmiMask; - uint cbBitsMask = CbBitsMask == 0 ? (uint)BitsMask.Length : CbBitsMask; - - const uint fixedSizeAfterHeader = 140; - uint cursor = fixedSizeAfterHeader; - - uint offBmiSrc = cbBmiSrc > 0 ? cursor : 0; - cursor += cbBmiSrc; - - uint offBitsSrc = cbBitsSrc > 0 ? cursor : 0; - cursor += cbBitsSrc; - - uint offBmiMask = cbBmiMask > 0 ? cursor : 0; - cursor += cbBmiMask; - - uint offBitsMask = cbBitsMask > 0 ? cursor : 0; - - Bounds.Write(writer); - AptlDest[0].Write(writer); - AptlDest[1].Write(writer); - AptlDest[2].Write(writer); - writer.Write(XSrc); - writer.Write(YSrc); - writer.Write(CxSrc); - writer.Write(CySrc); - XFormSrc.Write(writer); - BkColorSrc.Write(writer); - writer.Write((uint)UsageSrc); - writer.Write(offBmiSrc); - writer.Write(cbBmiSrc); - writer.Write(offBitsSrc); - writer.Write(cbBitsSrc); - writer.Write(XMask); - writer.Write(YMask); - writer.Write((uint)UsageMask); - writer.Write(offBmiMask); - writer.Write(cbBmiMask); - writer.Write(offBitsMask); - writer.Write(cbBitsMask); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - writer.Write(BmiMask); - writer.Write(BitsMask); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER.cs deleted file mode 100644 index 0e7accc5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYBEZIER : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYBEZIER() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYBEZIER }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER16.cs deleted file mode 100644 index 6f7d5c4c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIER16.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYBEZIER16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYBEZIER16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYBEZIER16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO.cs deleted file mode 100644 index a63fc7bb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYBEZIERTO : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYBEZIERTO() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYBEZIERTO }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO16.cs deleted file mode 100644 index a950a463..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYBEZIERTO16.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYBEZIERTO16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYBEZIERTO16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYBEZIERTO16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW.cs deleted file mode 100644 index 07abd782..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW.cs +++ /dev/null @@ -1,66 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYDRAW : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public byte[] AbTypes { get; set; } = Array.Empty(); - - public EMR_POLYDRAW() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYDRAW }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - - AbTypes = reader.ReadBytes(Convert.ToInt32(Count)); - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(count); - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - - if (AbTypes.Length == count) - { - writer.Write(AbTypes); - } - else - { - for (int i = 0; i < count; i++) - { - writer.Write((byte)0); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW16.cs deleted file mode 100644 index 46236efe..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYDRAW16.cs +++ /dev/null @@ -1,67 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYDRAW16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public byte[] AbTypes { get; set; } = Array.Empty(); - - public EMR_POLYDRAW16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYDRAW16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - - AbTypes = reader.ReadBytes(Convert.ToInt32(Count)); - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(count); - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - - if (AbTypes.Length == count) - { - writer.Write(AbTypes); - } - else - { - for (int i = 0; i < count; i++) - { - writer.Write((byte)0); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON.cs deleted file mode 100644 index 3c8a89da..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYGON : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYGON() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYGON }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON16.cs deleted file mode 100644 index 4d17195c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYGON16.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYGON16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYGON16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYGON16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE.cs deleted file mode 100644 index 487a109e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYLINE : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYLINE() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYLINE }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE16.cs deleted file mode 100644 index b2f8b2c6..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINE16.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYLINE16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYLINE16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYLINE16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO.cs deleted file mode 100644 index ff2e6b01..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYLINETO : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYLINETO() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYLINETO }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO16.cs deleted file mode 100644 index 8b0aacae..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYLINETO16.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYLINETO16 : Record - { - public RectL Bounds = new(); - - public uint Count; - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYLINETO16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYLINETO16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - Count = reader.ReadUInt32(); - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint count = Count == 0 ? (uint)Points.Length : Count; - Bounds.Write(writer); - writer.Write(count); - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON.cs deleted file mode 100644 index 364e3a9e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON.cs +++ /dev/null @@ -1,67 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYPOLYGON : Record - { - public RectL Bounds = new(); - - public uint NumberOfPolys; - - public uint Count; - - public uint[] PolyCounts { get; set; } = Array.Empty(); - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYPOLYGON() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYPOLYGON }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - NumberOfPolys = reader.ReadUInt32(); - Count = reader.ReadUInt32(); - - PolyCounts = new uint[NumberOfPolys]; - for (int i = 0; i < NumberOfPolys; i++) - { - PolyCounts[i] = reader.ReadUInt32(); - } - - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint numberOfPolys = NumberOfPolys == 0 ? (uint)PolyCounts.Length : NumberOfPolys; - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(numberOfPolys); - writer.Write(count); - for (int i = 0; i < numberOfPolys; i++) - { - writer.Write(PolyCounts[i]); - } - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON16.cs deleted file mode 100644 index 92aa5fb8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYGON16.cs +++ /dev/null @@ -1,67 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYPOLYGON16 : Record - { - public RectL Bounds = new(); - - public uint NumberOfPolys; - - public uint Count; - - public uint[] PolyCounts { get; set; } = Array.Empty(); - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYPOLYGON16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYPOLYGON16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - NumberOfPolys = reader.ReadUInt32(); - Count = reader.ReadUInt32(); - - PolyCounts = new uint[NumberOfPolys]; - for (int i = 0; i < NumberOfPolys; i++) - { - PolyCounts[i] = reader.ReadUInt32(); - } - - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint numberOfPolys = NumberOfPolys == 0 ? (uint)PolyCounts.Length : NumberOfPolys; - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(numberOfPolys); - writer.Write(count); - for (int i = 0; i < numberOfPolys; i++) - { - writer.Write(PolyCounts[i]); - } - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE.cs deleted file mode 100644 index 400e9fa4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE.cs +++ /dev/null @@ -1,67 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYPOLYLINE : Record - { - public RectL Bounds = new(); - - public uint NumberOfPolys; - - public uint Count; - - public uint[] PolyCounts { get; set; } = Array.Empty(); - - public PointL[] Points { get; set; } = Array.Empty(); - - public EMR_POLYPOLYLINE() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYPOLYLINE }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - NumberOfPolys = reader.ReadUInt32(); - Count = reader.ReadUInt32(); - - PolyCounts = new uint[NumberOfPolys]; - for (int i = 0; i < NumberOfPolys; i++) - { - PolyCounts[i] = reader.ReadUInt32(); - } - - Points = new PointL[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointL(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint numberOfPolys = NumberOfPolys == 0 ? (uint)PolyCounts.Length : NumberOfPolys; - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(numberOfPolys); - writer.Write(count); - for (int i = 0; i < numberOfPolys; i++) - { - writer.Write(PolyCounts[i]); - } - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE16.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE16.cs deleted file mode 100644 index de1bb18b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYPOLYLINE16.cs +++ /dev/null @@ -1,68 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYPOLYLINE16 : Record - { - public RectL Bounds = new(); - - public uint NumberOfPolys; - - public uint Count; - - public uint[] PolyCounts { get; set; } = Array.Empty(); - - public PointS[] Points { get; set; } = Array.Empty(); - - public EMR_POLYPOLYLINE16() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYPOLYLINE16 }; - } - - public override void Read(BinaryReader reader) - { - Bounds.Read(reader); - NumberOfPolys = reader.ReadUInt32(); - Count = reader.ReadUInt32(); - - PolyCounts = new uint[NumberOfPolys]; - for (int i = 0; i < NumberOfPolys; i++) - { - PolyCounts[i] = reader.ReadUInt32(); - } - - Points = new PointS[Count]; - for (int i = 0; i < Count; i++) - { - var point = new PointS(); - point.Read(reader); - Points[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - uint numberOfPolys = NumberOfPolys == 0 ? (uint)PolyCounts.Length : NumberOfPolys; - uint count = Count == 0 ? (uint)Points.Length : Count; - - Bounds.Write(writer); - writer.Write(numberOfPolys); - writer.Write(count); - for (int i = 0; i < numberOfPolys; i++) - { - writer.Write(PolyCounts[i]); - } - - for (int i = 0; i < count; i++) - { - Points[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTA.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTA.cs deleted file mode 100644 index 6f0dd5a0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTA.cs +++ /dev/null @@ -1,62 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYTEXTOUTA : Record - { - public RectL Bounds; - - public GraphicsMode IGraphicsMode; - - public float ExScale; - - public float EyScale; - - public uint CStrings; - - public EmrText[] EmrTexts { get; set; } = []; - - public EMR_POLYTEXTOUTA() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYTEXTOUTA }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - IGraphicsMode = (GraphicsMode)reader.ReadUInt32(); - ExScale = reader.ReadSingle(); - EyScale = reader.ReadSingle(); - CStrings = reader.ReadUInt32(); - - EmrTexts = new EmrText[CStrings]; - for (int i = 0; i < CStrings; i++) - { - var emrText = new EmrText(); - emrText.Read(reader); - EmrTexts[i] = emrText; - } - } - - public override void Write(BinaryWriter writer) - { - uint stringsCount = CStrings == 0 ? (uint)EmrTexts.Length : CStrings; - - Bounds.Write(writer); - writer.Write((uint)IGraphicsMode); - writer.Write(ExScale); - writer.Write(EyScale); - writer.Write(stringsCount); - for (int i = 0; i < stringsCount; i++) - { - EmrTexts[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTW.cs deleted file mode 100644 index 207ccb9d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_POLYTEXTOUTW.cs +++ /dev/null @@ -1,62 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_POLYTEXTOUTW : Record - { - public RectL Bounds; - - public GraphicsMode IGraphicsMode; - - public float ExScale; - - public float EyScale; - - public uint CStrings; - - public EmrText[] EmrTexts { get; set; } = []; - - public EMR_POLYTEXTOUTW() - { - Header = new RecordHeader { Type = RecordType.EMR_POLYTEXTOUTW }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - IGraphicsMode = (GraphicsMode)reader.ReadUInt32(); - ExScale = reader.ReadSingle(); - EyScale = reader.ReadSingle(); - CStrings = reader.ReadUInt32(); - - EmrTexts = new EmrText[CStrings]; - for (int i = 0; i < CStrings; i++) - { - var emrText = new EmrText(); - emrText.Read(reader); - EmrTexts[i] = emrText; - } - } - - public override void Write(BinaryWriter writer) - { - uint stringsCount = CStrings == 0 ? (uint)EmrTexts.Length : CStrings; - - Bounds.Write(writer); - writer.Write((uint)IGraphicsMode); - writer.Write(ExScale); - writer.Write(EyScale); - writer.Write(stringsCount); - for (int i = 0; i < stringsCount; i++) - { - EmrTexts[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_RECTANGLE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_RECTANGLE.cs deleted file mode 100644 index 0fca0bfd..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_RECTANGLE.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_RECTANGLE : Record - { - public RectL Box; - - public EMR_RECTANGLE() - { - Header = new RecordHeader { Type = RecordType.EMR_RECTANGLE }; - } - - public override void Read(BinaryReader reader) - { - Box = new RectL(); - Box.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Box.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ROUNDRECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ROUNDRECT.cs deleted file mode 100644 index 393ca7f0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_ROUNDRECT.cs +++ /dev/null @@ -1,35 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_ROUNDRECT : Record - { - public RectL Box; - - public SizeL Corner; - - public EMR_ROUNDRECT() - { - Header = new RecordHeader { Type = RecordType.EMR_ROUNDRECT }; - } - - public override void Read(BinaryReader reader) - { - Box = new RectL(); - Box.Read(reader); - Corner = new SizeL(); - Corner.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Box.Write(writer); - Corner.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_SETDIBITSTODEVICE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_SETDIBITSTODEVICE.cs deleted file mode 100644 index 06e33440..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_SETDIBITSTODEVICE.cs +++ /dev/null @@ -1,112 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_SETDIBITSTODEVICE : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int XSrc; - - public int YSrc; - - public int CxSrc; - - public int CySrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public DIBColors UsageSrc; - - public uint IStartScan; - - public uint CScans; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_SETDIBITSTODEVICE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETDIBITSTODEVICE }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - UsageSrc = (DIBColors)reader.ReadUInt32(); - IStartScan = reader.ReadUInt32(); - CScans = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 76; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(XSrc); - writer.Write(YSrc); - writer.Write(CxSrc); - writer.Write(CySrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write((uint)UsageSrc); - writer.Write(IStartScan); - writer.Write(CScans); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHBLT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHBLT.cs deleted file mode 100644 index 0893105e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHBLT.cs +++ /dev/null @@ -1,126 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_STRETCHBLT : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int CxDest; - - public int CyDest; - - public Metafile.Wmf.Enumerations.TernaryRasterOperation BitBltRasterOperation; - - public int XSrc; - - public int YSrc; - - public XForm XFormSrc { get; set; } = new(); - - public ColorRef BkColorSrc; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public int CxSrc; - - public int CySrc; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_STRETCHBLT() - { - Header = new RecordHeader { Type = RecordType.EMR_STRETCHBLT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - BitBltRasterOperation = (Metafile.Wmf.Enumerations.TernaryRasterOperation)reader.ReadUInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - XFormSrc.Read(reader); - BkColorSrc.Read(reader); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 108; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write((uint)BitBltRasterOperation); - writer.Write(XSrc); - writer.Write(YSrc); - XFormSrc.Write(writer); - BkColorSrc.Write(writer); - writer.Write((uint)UsageSrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(CxSrc); - writer.Write(CySrc); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHDIBITS.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHDIBITS.cs deleted file mode 100644 index de78208b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_STRETCHDIBITS.cs +++ /dev/null @@ -1,116 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_STRETCHDIBITS : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int XSrc; - - public int YSrc; - - public int CxSrc; - - public int CySrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public DIBColors UsageSrc; - - public Wmf.Enumerations.TernaryRasterOperation BitBltRasterOperation; - - public int CxDest; - - public int CyDest; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_STRETCHDIBITS() - { - Header = new RecordHeader { Type = RecordType.EMR_STRETCHDIBITS }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - UsageSrc = (DIBColors)reader.ReadUInt32(); - BitBltRasterOperation = (Metafile.Wmf.Enumerations.TernaryRasterOperation)reader.ReadUInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 80; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(XSrc); - writer.Write(YSrc); - writer.Write(CxSrc); - writer.Write(CySrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write((uint)UsageSrc); - writer.Write((uint)BitBltRasterOperation); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_TRANSPARENTBLT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_TRANSPARENTBLT.cs deleted file mode 100644 index 07954f77..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/DrawingRecordTypes/EMR_TRANSPARENTBLT.cs +++ /dev/null @@ -1,122 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_TRANSPARENTBLT : Record - { - public RectL Bounds = new(); - - public int XDest; - - public int YDest; - - public int CxDest; - - public int CyDest; - - public int XSrc; - - public int YSrc; - - public XForm XFormSrc { get; set; } = new(); - - public uint ColorTransparent; - - public DIBColors UsageSrc; - - public uint OffBmiSrc; - - public uint CbBmiSrc; - - public uint OffBitsSrc; - - public uint CbBitsSrc; - - public int CxSrc; - - public int CySrc; - - public byte[] BmiSrc { get; set; } = Array.Empty(); - - public byte[] BitsSrc { get; set; } = Array.Empty(); - - public EMR_TRANSPARENTBLT() - { - Header = new RecordHeader { Type = RecordType.EMR_TRANSPARENTBLT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - Bounds.Read(reader); - XDest = reader.ReadInt32(); - YDest = reader.ReadInt32(); - CxDest = reader.ReadInt32(); - CyDest = reader.ReadInt32(); - XSrc = reader.ReadInt32(); - YSrc = reader.ReadInt32(); - XFormSrc.Read(reader); - ColorTransparent = reader.ReadUInt32(); - UsageSrc = (DIBColors)reader.ReadUInt32(); - OffBmiSrc = reader.ReadUInt32(); - CbBmiSrc = reader.ReadUInt32(); - OffBitsSrc = reader.ReadUInt32(); - CbBitsSrc = reader.ReadUInt32(); - CxSrc = reader.ReadInt32(); - CySrc = reader.ReadInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmiSrc > 0 && OffBmiSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBmiSrc; - BmiSrc = reader.ReadBytes(Convert.ToInt32(CbBmiSrc)); - } - - if (CbBitsSrc > 0 && OffBitsSrc > 0) - { - reader.BaseStream.Position = recordStart + OffBitsSrc; - BitsSrc = reader.ReadBytes(Convert.ToInt32(CbBitsSrc)); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmiSrc == 0 ? (uint)BmiSrc.Length : CbBmiSrc; - uint cbBits = CbBitsSrc == 0 ? (uint)BitsSrc.Length : CbBitsSrc; - - const uint fixedSizeAfterHeader = 104; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - Bounds.Write(writer); - writer.Write(XDest); - writer.Write(YDest); - writer.Write(CxDest); - writer.Write(CyDest); - writer.Write(XSrc); - writer.Write(YSrc); - XFormSrc.Write(writer); - writer.Write(ColorTransparent); - writer.Write((uint)UsageSrc); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(CxSrc); - writer.Write(CySrc); - writer.Write(BmiSrc); - writer.Write(BitsSrc); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEBRUSHINDIRECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEBRUSHINDIRECT.cs deleted file mode 100644 index c313a3a3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEBRUSHINDIRECT.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_CREATEBRUSHINDIRECT : Record - { - public uint IhBrush; - - public LogBrush LogBrush { get; set; } = new(); - - public EMR_CREATEBRUSHINDIRECT() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATEBRUSHINDIRECT }; - } - - public override void Read(BinaryReader reader) - { - IhBrush = reader.ReadUInt32(); - LogBrush.BrushStyle = (Wmf.Enumerations.BrushStyle)reader.ReadUInt32(); - LogBrush.ColorRef.Read(reader); - LogBrush.BrushHatch = (Wmf.Enumerations.HatchStyle)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhBrush); - writer.Write((uint)LogBrush.BrushStyle); - LogBrush.ColorRef.Write(writer); - writer.Write((uint)(LogBrush.BrushHatch ?? Metafile.Wmf.Enumerations.HatchStyle.HS_HORIZONTAL)); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEDIBPATTERNBRUSHPT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEDIBPATTERNBRUSHPT.cs deleted file mode 100644 index e77c485a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEDIBPATTERNBRUSHPT.cs +++ /dev/null @@ -1,79 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_CREATEDIBPATTERNBRUSHPT : Record - { - public uint IhBrush; - - public DIBColors Usage; - - public uint OffBmi; - - public uint CbBmi; - - public uint OffBits; - - public uint CbBits; - - public byte[] Bmi { get; set; } = []; - - public byte[] Bits { get; set; } = []; - - public EMR_CREATEDIBPATTERNBRUSHPT() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATEDIBPATTERNBRUSHPT }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - IhBrush = reader.ReadUInt32(); - Usage = (DIBColors)reader.ReadUInt32(); - OffBmi = reader.ReadUInt32(); - CbBmi = reader.ReadUInt32(); - OffBits = reader.ReadUInt32(); - CbBits = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmi > 0 && OffBmi > 0) - { - reader.BaseStream.Position = recordStart + OffBmi; - Bmi = reader.ReadBytes((int)CbBmi); - } - - if (CbBits > 0 && OffBits > 0) - { - reader.BaseStream.Position = recordStart + OffBits; - Bits = reader.ReadBytes((int)CbBits); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmi == 0 ? (uint)Bmi.Length : CbBmi; - uint cbBits = CbBits == 0 ? (uint)Bits.Length : CbBits; - - const uint fixedSizeAfterHeader = 32; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - writer.Write(IhBrush); - writer.Write((uint)Usage); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(Bmi); - writer.Write(Bits); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEMONOBRUSH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEMONOBRUSH.cs deleted file mode 100644 index fb786d78..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEMONOBRUSH.cs +++ /dev/null @@ -1,78 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_CREATEMONOBRUSH : Record - { - public uint IhBrush; - - public DIBColors Usage; - - public uint OffBmi; - - public uint CbBmi; - - public uint OffBits; - - public uint CbBits; - - public byte[] Bmi { get; set; } = []; - - public byte[] Bits { get; set; } = []; - - public EMR_CREATEMONOBRUSH() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATEMONOBRUSH }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - IhBrush = reader.ReadUInt32(); - Usage = (DIBColors)reader.ReadUInt32(); - OffBmi = reader.ReadUInt32(); - CbBmi = reader.ReadUInt32(); - OffBits = reader.ReadUInt32(); - CbBits = reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmi > 0 && OffBmi > 0) - { - reader.BaseStream.Position = recordStart + OffBmi; - Bmi = reader.ReadBytes((int)CbBmi); - } - - if (CbBits > 0 && OffBits > 0) - { - reader.BaseStream.Position = recordStart + OffBits; - Bits = reader.ReadBytes((int)CbBits); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmi == 0 ? (uint)Bmi.Length : CbBmi; - uint cbBits = CbBits == 0 ? (uint)Bits.Length : CbBits; - - const uint fixedSizeAfterHeader = 32; - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - writer.Write(IhBrush); - writer.Write((uint)Usage); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(Bmi); - writer.Write(Bits); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEPEN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEPEN.cs deleted file mode 100644 index 09f5fd1c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_CREATEPEN.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_CREATEPEN : Record - { - internal uint IhPen; - - internal Pen Pen { get; set; } = new(); - - public EMR_CREATEPEN() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATEPEN }; - } - - public override void Read(BinaryReader reader) - { - IhPen = reader.ReadUInt32(); - Pen.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPen); - Pen.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEFONTINDIRECTW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEFONTINDIRECTW.cs deleted file mode 100644 index 94585ba0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEFONTINDIRECTW.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_EXTCREATEFONTINDIRECTW : Record - { - public uint IhFont; - - public Font Font { get; set; } = new(); - - public EMR_EXTCREATEFONTINDIRECTW() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTCREATEFONTINDIRECTW }; - } - - public override void Read(BinaryReader reader) - { - IhFont = reader.ReadUInt32(); - Font.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhFont); - Font.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEPEN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEPEN.cs deleted file mode 100644 index c4c245b7..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/ObjectRecordTypes/EMR_EXTCREATEPEN.cs +++ /dev/null @@ -1,117 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_EXTCREATEPEN : Record - { - public uint IhPen; - - public uint OffBmi; - - public uint CbBmi; - - public uint OffBits; - - public uint CbBits; - - public uint PenStyle; - - public uint Width; - - public uint BrushStyle; - - public uint ColorRef; - - public uint Hatch; - - public uint NumStyleEntries; - - public uint[] StyleEntries { get; set; } = []; - - public DIBColors Usage; - - public byte[] Bmi { get; set; } = []; - - public byte[] Bits { get; set; } = []; - - public EMR_EXTCREATEPEN() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTCREATEPEN }; - } - - public override void Read(BinaryReader reader) - { - long recordStart = reader.BaseStream.Position - 8; - - IhPen = reader.ReadUInt32(); - OffBmi = reader.ReadUInt32(); - CbBmi = reader.ReadUInt32(); - OffBits = reader.ReadUInt32(); - CbBits = reader.ReadUInt32(); - PenStyle = reader.ReadUInt32(); - Width = reader.ReadUInt32(); - BrushStyle = reader.ReadUInt32(); - ColorRef = reader.ReadUInt32(); - Hatch = reader.ReadUInt32(); - NumStyleEntries = reader.ReadUInt32(); - - StyleEntries = new uint[NumStyleEntries]; - for (int i = 0; i < NumStyleEntries; i++) - { - StyleEntries[i] = reader.ReadUInt32(); - } - - Usage = (DIBColors)reader.ReadUInt32(); - - long restorePosition = reader.BaseStream.Position; - - if (CbBmi > 0 && OffBmi > 0) - { - reader.BaseStream.Position = recordStart + OffBmi; - Bmi = reader.ReadBytes((int)CbBmi); - } - - if (CbBits > 0 && OffBits > 0) - { - reader.BaseStream.Position = recordStart + OffBits; - Bits = reader.ReadBytes((int)CbBits); - } - - reader.BaseStream.Position = restorePosition; - } - - public override void Write(BinaryWriter writer) - { - uint cbBmi = CbBmi == 0 ? (uint)Bmi.Length : CbBmi; - uint cbBits = CbBits == 0 ? (uint)Bits.Length : CbBits; - uint numStyleEntries = NumStyleEntries == 0 ? (uint)StyleEntries.Length : NumStyleEntries; - - uint fixedSizeAfterHeader = 56 + (numStyleEntries * 4); - uint offBmi = cbBmi > 0 ? fixedSizeAfterHeader : 0; - uint offBits = cbBits > 0 ? fixedSizeAfterHeader + cbBmi : 0; - - writer.Write(IhPen); - writer.Write(offBmi); - writer.Write(cbBmi); - writer.Write(offBits); - writer.Write(cbBits); - writer.Write(PenStyle); - writer.Write(Width); - writer.Write(BrushStyle); - writer.Write(ColorRef); - writer.Write(Hatch); - writer.Write(numStyleEntries); - for (int i = 0; i < numStyleEntries; i++) - { - writer.Write(StyleEntries[i]); - } - writer.Write((uint)Usage); - writer.Write(Bmi); - writer.Write(Bits); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/Record.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/Record.cs deleted file mode 100644 index c7fec06b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/Record.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records -{ - using System; - using System.IO; - - internal class Record - { - public RecordHeader Header { get; set; } - - public byte[] Data { get; set; } = Array.Empty(); - - public virtual void Read(BinaryReader reader) - { - } - - public virtual void Write(BinaryWriter writer) - { - if (Data.Length > 0) - { - writer.Write(Data); - } - } - - public override string ToString() - { - return string.Format("{0} {1}", Header.Type.ToString(), Header.Size); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/RecordHeader.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/RecordHeader.cs deleted file mode 100644 index 4249cb88..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/RecordHeader.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal struct RecordHeader - { - - public RecordType Type; - - /// - /// A 32-bit unsigned integer that defines the number of 16-bit WORDs in the record. - /// - public uint Size; - - - - public void Read(BinaryReader reader) - { - this.Type = (RecordType)reader.ReadUInt32(); - this.Size = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write((uint)this.Type); - writer.Write(this.Size); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ABORTPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ABORTPATH.cs deleted file mode 100644 index 7cd3e5d7..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ABORTPATH.cs +++ /dev/null @@ -1,24 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_ABORTPATH : Record - { - public EMR_ABORTPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_ABORTPATH }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_BEGINPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_BEGINPATH.cs deleted file mode 100644 index 78d6ce2f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_BEGINPATH.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_BEGINPATH : Record - { - public EMR_BEGINPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_BEGINPATH }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CLOSEFIGURE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CLOSEFIGURE.cs deleted file mode 100644 index ea7550da..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CLOSEFIGURE.cs +++ /dev/null @@ -1,24 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_CLOSEFIGURE : Record - { - public EMR_CLOSEFIGURE() - { - Header = new RecordHeader { Type = RecordType.EMR_CLOSEFIGURE }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORCORRECTPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORCORRECTPALETTE.cs deleted file mode 100644 index 700a8b82..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORCORRECTPALETTE.cs +++ /dev/null @@ -1,31 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_COLORCORRECTPALETTE : Record - { - public uint IhPalette; - - public uint NumberOfEntries; - - public EMR_COLORCORRECTPALETTE() - { - Header = new RecordHeader { Type = RecordType.EMR_COLORCORRECTPALETTE }; - } - - public override void Read(BinaryReader reader) - { - IhPalette = reader.ReadUInt32(); - NumberOfEntries = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPalette); - writer.Write(NumberOfEntries); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORMATCHTOTARGETW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORMATCHTOTARGETW.cs deleted file mode 100644 index 1992431c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COLORMATCHTOTARGETW.cs +++ /dev/null @@ -1,51 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_COLORMATCHTOTARGETW : Record - { - public ColorMatchToTargetAction DwAction; - - public ColorMatchToTarget DwFlags; - - public uint CbName; - - public uint CbData; - - public byte[] NameData { get; set; } = Array.Empty(); - - public byte[] ProfileData { get; set; } = Array.Empty(); - - public EMR_COLORMATCHTOTARGETW() - { - Header = new RecordHeader { Type = RecordType.EMR_COLORMATCHTOTARGETW }; - } - - public override void Read(BinaryReader reader) - { - DwAction = (ColorMatchToTargetAction)reader.ReadUInt32(); - DwFlags = (ColorMatchToTarget)reader.ReadUInt32(); - CbName = reader.ReadUInt32(); - CbData = reader.ReadUInt32(); - NameData = reader.ReadBytes(Convert.ToInt32(CbName)); - ProfileData = reader.ReadBytes(Convert.ToInt32(CbData)); - } - - public override void Write(BinaryWriter writer) - { - uint nameLength = CbName == 0 ? (uint)NameData.Length : CbName; - uint dataLength = CbData == 0 ? (uint)ProfileData.Length : CbData; - writer.Write((uint)DwAction); - writer.Write((uint)DwFlags); - writer.Write(nameLength); - writer.Write(dataLength); - writer.Write(NameData); - writer.Write(ProfileData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COMMENT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COMMENT.cs deleted file mode 100644 index f001ac34..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_COMMENT.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_COMMENT : Record - { - public uint DataSize; - - public byte[] CommentData { get; set; } = Array.Empty(); - - public EMR_COMMENT() - { - Header = new RecordHeader { Type = RecordType.EMR_COMMENT }; - } - - public override void Read(BinaryReader reader) - { - DataSize = reader.ReadUInt32(); - CommentData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)CommentData.Length : DataSize; - writer.Write(size); - writer.Write(CommentData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACE.cs deleted file mode 100644 index b7178efe..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACE.cs +++ /dev/null @@ -1,36 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_CREATECOLORSPACE : Record - { - public uint IhCS; - - public byte[] LogColorSpaceData { get; set; } = Array.Empty(); - - public EMR_CREATECOLORSPACE() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATECOLORSPACE }; - } - - public override void Read(BinaryReader reader) - { - IhCS = reader.ReadUInt32(); - int remaining = Convert.ToInt32(Header.Size) - 12; - if (remaining > 0) - { - LogColorSpaceData = reader.ReadBytes(remaining); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhCS); - writer.Write(LogColorSpaceData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACEW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACEW.cs deleted file mode 100644 index 3b0a00f2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATECOLORSPACEW.cs +++ /dev/null @@ -1,36 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_CREATECOLORSPACEW : Record - { - public uint IhCS; - - public byte[] LogColorSpaceData { get; set; } = Array.Empty(); - - public EMR_CREATECOLORSPACEW() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATECOLORSPACEW }; - } - - public override void Read(BinaryReader reader) - { - IhCS = reader.ReadUInt32(); - int remaining = Convert.ToInt32(Header.Size) - 12; - if (remaining > 0) - { - LogColorSpaceData = reader.ReadBytes(remaining); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhCS); - writer.Write(LogColorSpaceData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATEPALETTE.cs deleted file mode 100644 index 09e43a62..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_CREATEPALETTE.cs +++ /dev/null @@ -1,36 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_CREATEPALETTE : Record - { - public uint IhPal; - - public byte[] LogPaletteData { get; set; } = Array.Empty(); - - public EMR_CREATEPALETTE() - { - Header = new RecordHeader { Type = RecordType.EMR_CREATEPALETTE }; - } - - public override void Read(BinaryReader reader) - { - IhPal = reader.ReadUInt32(); - int remaining = Convert.ToInt32(Header.Size) - 12; - if (remaining > 0) - { - LogPaletteData = reader.ReadBytes(remaining); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPal); - writer.Write(LogPaletteData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETECOLORSPACE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETECOLORSPACE.cs deleted file mode 100644 index 1fd8a5bb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETECOLORSPACE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_DELETECOLORSPACE : Record - { - public uint IhCS; - - public EMR_DELETECOLORSPACE() - { - Header = new RecordHeader { Type = RecordType.EMR_DELETECOLORSPACE }; - } - - public override void Read(BinaryReader reader) - { - IhCS = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhCS); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETEOBJECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETEOBJECT.cs deleted file mode 100644 index 63c828e9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DELETEOBJECT.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_DELETEOBJECT : Record - { - public uint ObjectIndex; - - public EMR_DELETEOBJECT() - { - Header = new RecordHeader { Type = RecordType.EMR_DELETEOBJECT }; - } - - public override void Read(BinaryReader reader) - { - ObjectIndex = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(ObjectIndex); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DRAWESCAPE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DRAWESCAPE.cs deleted file mode 100644 index 864f99c8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_DRAWESCAPE.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_DRAWESCAPE : Record - { - public uint Escape; - - public uint DataSize; - - public byte[] EscapeData { get; set; } = Array.Empty(); - - public EMR_DRAWESCAPE() - { - Header = new RecordHeader { Type = RecordType.EMR_DRAWESCAPE }; - } - - public override void Read(BinaryReader reader) - { - Escape = reader.ReadUInt32(); - DataSize = reader.ReadUInt32(); - EscapeData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)EscapeData.Length : DataSize; - writer.Write(Escape); - writer.Write(size); - writer.Write(EscapeData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ENDPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ENDPATH.cs deleted file mode 100644 index 0f937429..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_ENDPATH.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_ENDPATH : Record - { - public EMR_ENDPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_ENDPATH }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXCLUDECLIPRECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXCLUDECLIPRECT.cs deleted file mode 100644 index 718379fe..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXCLUDECLIPRECT.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_EXCLUDECLIPRECT : Record - { - public RectL Clip; - - public EMR_EXCLUDECLIPRECT() - { - Header = new RecordHeader { Type = RecordType.EMR_EXCLUDECLIPRECT }; - } - - public override void Read(BinaryReader reader) - { - Clip = new RectL(); - Clip.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Clip.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTESCAPE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTESCAPE.cs deleted file mode 100644 index 5587782e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTESCAPE.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_EXTESCAPE : Record - { - public uint Escape; - - public uint DataSize; - - public byte[] EscapeData { get; set; } = Array.Empty(); - - public EMR_EXTESCAPE() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTESCAPE }; - } - - public override void Read(BinaryReader reader) - { - Escape = reader.ReadUInt32(); - DataSize = reader.ReadUInt32(); - EscapeData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)EscapeData.Length : DataSize; - writer.Write(Escape); - writer.Write(size); - writer.Write(EscapeData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTSELECTCLIPRGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTSELECTCLIPRGN.cs deleted file mode 100644 index 41f7a9a1..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_EXTSELECTCLIPRGN.cs +++ /dev/null @@ -1,38 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_EXTSELECTCLIPRGN : Record - { - public uint RegionDataSize; - - public uint RegionMode; - - public byte[] RegionData { get; set; } = Array.Empty(); - - public EMR_EXTSELECTCLIPRGN() - { - Header = new RecordHeader { Type = RecordType.EMR_EXTSELECTCLIPRGN }; - } - - public override void Read(BinaryReader reader) - { - RegionDataSize = reader.ReadUInt32(); - RegionMode = reader.ReadUInt32(); - RegionData = reader.ReadBytes(Convert.ToInt32(RegionDataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint regionSize = RegionDataSize == 0 ? (uint)RegionData.Length : RegionDataSize; - writer.Write(regionSize); - writer.Write(RegionMode); - writer.Write(RegionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLPATH.cs deleted file mode 100644 index a7fe0bc9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLPATH.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_FILLPATH : Record - { - public RectL Bounds; - - public EMR_FILLPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_FILLPATH }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Bounds.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLRGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLRGN.cs deleted file mode 100644 index ef0fa40c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FILLRGN.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_FILLRGN : Record - { - public RectL Bounds; - - public uint RegionDataSize; - - public uint IhBrush; - - public byte[] RegionData { get; set; } = Array.Empty(); - - public EMR_FILLRGN() - { - Header = new RecordHeader { Type = RecordType.EMR_FILLRGN }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - RegionDataSize = reader.ReadUInt32(); - IhBrush = reader.ReadUInt32(); - RegionData = reader.ReadBytes(Convert.ToInt32(RegionDataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint regionSize = RegionDataSize == 0 ? (uint)RegionData.Length : RegionDataSize; - Bounds.Write(writer); - writer.Write(regionSize); - writer.Write(IhBrush); - writer.Write(RegionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FLATTENPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FLATTENPATH.cs deleted file mode 100644 index 51cfe8f8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FLATTENPATH.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_FLATTENPATH : Record - { - public EMR_FLATTENPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_FLATTENPATH }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FORCEUFIMAPPING.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FORCEUFIMAPPING.cs deleted file mode 100644 index 5de1d39d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FORCEUFIMAPPING.cs +++ /dev/null @@ -1,24 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_FORCEUFIMAPPING : Record - { - public EMR_FORCEUFIMAPPING() - { - Header = new RecordHeader { Type = RecordType.EMR_FORCEUFIMAPPING }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FRAMERGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FRAMERGN.cs deleted file mode 100644 index 80d0fdd4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_FRAMERGN.cs +++ /dev/null @@ -1,51 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_FRAMERGN : Record - { - public RectL Bounds; - - public uint RegionDataSize; - - public uint IhBrush; - - public int Width; - - public int Height; - - public byte[] RegionData { get; set; } = Array.Empty(); - - public EMR_FRAMERGN() - { - Header = new RecordHeader { Type = RecordType.EMR_FRAMERGN }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - RegionDataSize = reader.ReadUInt32(); - IhBrush = reader.ReadUInt32(); - Width = reader.ReadInt32(); - Height = reader.ReadInt32(); - RegionData = reader.ReadBytes(Convert.ToInt32(RegionDataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint regionSize = RegionDataSize == 0 ? (uint)RegionData.Length : RegionDataSize; - Bounds.Write(writer); - writer.Write(regionSize); - writer.Write(IhBrush); - writer.Write(Width); - writer.Write(Height); - writer.Write(RegionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSBOUNDEDRECORD.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSBOUNDEDRECORD.cs deleted file mode 100644 index 7a425d9c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSBOUNDEDRECORD.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_GLSBOUNDEDRECORD : Record - { - public RectL Bounds; - - public uint DataSize; - - public byte[] GlsData { get; set; } = Array.Empty(); - - public EMR_GLSBOUNDEDRECORD() - { - Header = new RecordHeader { Type = RecordType.EMR_GLSBOUNDEDRECORD }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - DataSize = reader.ReadUInt32(); - GlsData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)GlsData.Length : DataSize; - Bounds.Write(writer); - writer.Write(size); - writer.Write(GlsData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSRECORD.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSRECORD.cs deleted file mode 100644 index 085592a2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_GLSRECORD.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_GLSRECORD : Record - { - public uint DataSize; - - public byte[] GlsData { get; set; } = Array.Empty(); - - public EMR_GLSRECORD() - { - Header = new RecordHeader { Type = RecordType.EMR_GLSRECORD }; - } - - public override void Read(BinaryReader reader) - { - DataSize = reader.ReadUInt32(); - GlsData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)GlsData.Length : DataSize; - writer.Write(size); - writer.Write(GlsData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_HEADER.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_HEADER.cs deleted file mode 100644 index a335f01e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_HEADER.cs +++ /dev/null @@ -1,60 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - - internal class EMR_HEADER : Record - { - public Header HeaderObject { get; set; } = new(); - - public HeaderExtension1? Extension1 { get; set; } - - public HeaderExtension2? Extension2 { get; set; } - - public byte[] DescriptionData { get; set; } = Array.Empty(); - - public EMR_HEADER() - { - Header = new RecordHeader { Type = RecordType.EMR_HEADER }; - } - - public override void Read(BinaryReader reader) - { - HeaderObject.Read(reader); - - long bytesRead = 72; - long remaining = Header.Size - 8 - bytesRead; - - if (remaining >= 12) - { - Extension1 = new HeaderExtension1(); - Extension1.Read(reader); - remaining -= 12; - } - - if (remaining >= 8) - { - Extension2 = new HeaderExtension2(); - Extension2.Read(reader); - remaining -= 8; - } - - if (remaining > 0) - { - DescriptionData = reader.ReadBytes(Convert.ToInt32(remaining)); - } - } - - public override void Write(BinaryWriter writer) - { - HeaderObject.Write(writer); - Extension1?.Write(writer); - Extension2?.Write(writer); - writer.Write(DescriptionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INTERSECTCLIPRECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INTERSECTCLIPRECT.cs deleted file mode 100644 index c3b621d2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INTERSECTCLIPRECT.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_INTERSECTCLIPRECT : Record - { - public RectL Clip; - - public EMR_INTERSECTCLIPRECT() - { - Header = new RecordHeader { Type = RecordType.EMR_INTERSECTCLIPRECT }; - } - - public override void Read(BinaryReader reader) - { - Clip = new RectL(); - Clip.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Clip.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INVERTRGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INVERTRGN.cs deleted file mode 100644 index c2484546..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_INVERTRGN.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_INVERTRGN : Record - { - public RectL Bounds; - - public uint RegionDataSize; - - public byte[] RegionData { get; set; } = Array.Empty(); - - public EMR_INVERTRGN() - { - Header = new RecordHeader { Type = RecordType.EMR_INVERTRGN }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - RegionDataSize = reader.ReadUInt32(); - RegionData = reader.ReadBytes(Convert.ToInt32(RegionDataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint regionSize = RegionDataSize == 0 ? (uint)RegionData.Length : RegionDataSize; - Bounds.Write(writer); - writer.Write(regionSize); - writer.Write(RegionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MODIFYWORLDTRANSFORM.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MODIFYWORLDTRANSFORM.cs deleted file mode 100644 index a29c81d6..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MODIFYWORLDTRANSFORM.cs +++ /dev/null @@ -1,51 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_MODIFYWORLDTRANSFORM : Record - { - public float M11; - - public float M12; - - public float M21; - - public float M22; - - public float Dx; - - public float Dy; - - public ModifyWorldTransformMode ModifyWorldTransformMode; - - public EMR_MODIFYWORLDTRANSFORM() - { - Header = new RecordHeader { Type = RecordType.EMR_MODIFYWORLDTRANSFORM }; - } - - public override void Read(BinaryReader reader) - { - M11 = reader.ReadSingle(); - M12 = reader.ReadSingle(); - M21 = reader.ReadSingle(); - M22 = reader.ReadSingle(); - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - ModifyWorldTransformMode = (ModifyWorldTransformMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(M11); - writer.Write(M12); - writer.Write(M21); - writer.Write(M22); - writer.Write(Dx); - writer.Write(Dy); - writer.Write((uint)ModifyWorldTransformMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MOVETOEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MOVETOEX.cs deleted file mode 100644 index 6b25eff8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_MOVETOEX.cs +++ /dev/null @@ -1,31 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_MOVETOEX : Record - { - public PointL Offset; - - public EMR_MOVETOEX() - { - Header = new RecordHeader { Type = RecordType.EMR_MOVETOEX }; - } - - public override void Read(BinaryReader reader) - { - Offset = new PointL(); - Offset.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Offset.Write(writer); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_NAMEDESCAPE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_NAMEDESCAPE.cs deleted file mode 100644 index 591dfdc8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_NAMEDESCAPE.cs +++ /dev/null @@ -1,38 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_NAMEDESCAPE : Record - { - public uint Escape; - - public uint DataSize; - - public byte[] EscapeData { get; set; } = Array.Empty(); - - public EMR_NAMEDESCAPE() - { - Header = new RecordHeader { Type = RecordType.EMR_NAMEDESCAPE }; - } - - public override void Read(BinaryReader reader) - { - Escape = reader.ReadUInt32(); - DataSize = reader.ReadUInt32(); - EscapeData = reader.ReadBytes(Convert.ToInt32(DataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = DataSize == 0 ? (uint)EscapeData.Length : DataSize; - writer.Write(Escape); - writer.Write(size); - writer.Write(EscapeData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_OFFSETCLIPRGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_OFFSETCLIPRGN.cs deleted file mode 100644 index f9211c34..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_OFFSETCLIPRGN.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_OFFSETCLIPRGN : Record - { - public int XOffset; - - public int YOffset; - - public EMR_OFFSETCLIPRGN() - { - Header = new RecordHeader { Type = RecordType.EMR_OFFSETCLIPRGN }; - } - - public override void Read(BinaryReader reader) - { - XOffset = reader.ReadInt32(); - YOffset = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(XOffset); - writer.Write(YOffset); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PAINTRGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PAINTRGN.cs deleted file mode 100644 index 1a930121..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PAINTRGN.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_PAINTRGN : Record - { - public RectL Bounds; - - public uint RegionDataSize; - - public byte[] RegionData { get; set; } = Array.Empty(); - - public EMR_PAINTRGN() - { - Header = new RecordHeader { Type = RecordType.EMR_PAINTRGN }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - RegionDataSize = reader.ReadUInt32(); - RegionData = reader.ReadBytes(Convert.ToInt32(RegionDataSize)); - } - - public override void Write(BinaryWriter writer) - { - uint regionSize = RegionDataSize == 0 ? (uint)RegionData.Length : RegionDataSize; - Bounds.Write(writer); - writer.Write(regionSize); - writer.Write(RegionData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PIXELFORMAT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PIXELFORMAT.cs deleted file mode 100644 index c2d0a19a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_PIXELFORMAT.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_PIXELFORMAT : Record - { - public uint PixelFormatSize; - - public byte[] PixelFormatDescriptor { get; set; } = Array.Empty(); - - public EMR_PIXELFORMAT() - { - Header = new RecordHeader { Type = RecordType.EMR_PIXELFORMAT }; - } - - public override void Read(BinaryReader reader) - { - PixelFormatSize = reader.ReadUInt32(); - PixelFormatDescriptor = reader.ReadBytes(Convert.ToInt32(PixelFormatSize)); - } - - public override void Write(BinaryWriter writer) - { - uint size = PixelFormatSize == 0 ? (uint)PixelFormatDescriptor.Length : PixelFormatSize; - writer.Write(size); - writer.Write(PixelFormatDescriptor); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_REALIZEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_REALIZEPALETTE.cs deleted file mode 100644 index ca3e74ed..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_REALIZEPALETTE.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_REALIZEPALETTE : Record - { - public EMR_REALIZEPALETTE() - { - Header = new RecordHeader { Type = RecordType.EMR_REALIZEPALETTE }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESIZEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESIZEPALETTE.cs deleted file mode 100644 index 7ad2e2fa..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESIZEPALETTE.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_RESIZEPALETTE : Record - { - public uint IhPal; - - public uint NumberOfEntries; - - public EMR_RESIZEPALETTE() - { - Header = new RecordHeader { Type = RecordType.EMR_RESIZEPALETTE }; - } - - public override void Read(BinaryReader reader) - { - IhPal = reader.ReadUInt32(); - NumberOfEntries = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPal); - writer.Write(NumberOfEntries); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESTOREDC.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESTOREDC.cs deleted file mode 100644 index e1f3f726..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_RESTOREDC.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_RESTOREDC : Record - { - public int SavedDC; - - public EMR_RESTOREDC() - { - Header = new RecordHeader { Type = RecordType.EMR_RESTOREDC }; - } - - public override void Read(BinaryReader reader) - { - SavedDC = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(SavedDC); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SAVEDC.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SAVEDC.cs deleted file mode 100644 index 9af1f048..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SAVEDC.cs +++ /dev/null @@ -1,25 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SAVEDC : Record - { - public EMR_SAVEDC() - { - Header = new RecordHeader { Type = RecordType.EMR_SAVEDC }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEVIEWPORTEXTEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEVIEWPORTEXTEX.cs deleted file mode 100644 index 7aca0c9b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEVIEWPORTEXTEX.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SCALEVIEWPORTEXTEX : Record - { - public int XNum; - - public int XDenom; - - public int YNum; - - public int YDenom; - - public EMR_SCALEVIEWPORTEXTEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SCALEVIEWPORTEXTEX }; - } - - public override void Read(BinaryReader reader) - { - XNum = reader.ReadInt32(); - XDenom = reader.ReadInt32(); - YNum = reader.ReadInt32(); - YDenom = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(XNum); - writer.Write(XDenom); - writer.Write(YNum); - writer.Write(YDenom); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEWINDOWEXTEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEWINDOWEXTEX.cs deleted file mode 100644 index f28506c3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SCALEWINDOWEXTEX.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SCALEWINDOWEXTEX : Record - { - public int XNum; - - public int XDenom; - - public int YNum; - - public int YDenom; - - public EMR_SCALEWINDOWEXTEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SCALEWINDOWEXTEX }; - } - - public override void Read(BinaryReader reader) - { - XNum = reader.ReadInt32(); - XDenom = reader.ReadInt32(); - YNum = reader.ReadInt32(); - YDenom = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(XNum); - writer.Write(XDenom); - writer.Write(YNum); - writer.Write(YDenom); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTCLIPPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTCLIPPATH.cs deleted file mode 100644 index cc76cd7b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTCLIPPATH.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SELECTCLIPPATH : Record - { - public RegionMode RegionMode; - - public EMR_SELECTCLIPPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_SELECTCLIPPATH }; - } - - public override void Read(BinaryReader reader) - { - RegionMode = (RegionMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)RegionMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTOBJECT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTOBJECT.cs deleted file mode 100644 index 9b75e06b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTOBJECT.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SELECTOBJECT : Record - { - public uint ObjectIndex; - - public EMR_SELECTOBJECT() - { - Header = new RecordHeader { Type = RecordType.EMR_SELECTOBJECT }; - } - - public override void Read(BinaryReader reader) - { - ObjectIndex = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(ObjectIndex); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTPALETTE.cs deleted file mode 100644 index b3f38c31..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SELECTPALETTE.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SELECTPALETTE : Record - { - public uint IhPal; - - public EMR_SELECTPALETTE() - { - Header = new RecordHeader { Type = RecordType.EMR_SELECTPALETTE }; - } - - public override void Read(BinaryReader reader) - { - IhPal = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPal); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETARCDIRECTION.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETARCDIRECTION.cs deleted file mode 100644 index 74991a13..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETARCDIRECTION.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SETARCDIRECTION : Record - { - public ArcDirection Direction; - - public EMR_SETARCDIRECTION() - { - Header = new RecordHeader { Type = RecordType.EMR_SETARCDIRECTION }; - } - - public override void Read(BinaryReader reader) - { - Direction = (ArcDirection)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)Direction); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKCOLOR.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKCOLOR.cs deleted file mode 100644 index aac6845d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKCOLOR.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_SETBKCOLOR : Record - { - public ColorRef Color; - - public EMR_SETBKCOLOR() - { - Header = new RecordHeader { Type = RecordType.EMR_SETBKCOLOR }; - } - - public override void Read(BinaryReader reader) - { - Color.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Color.Write(writer); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKMODE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKMODE.cs deleted file mode 100644 index 0c149ef0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBKMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SETBKMODE : Record - { - public BackgroundMode BackgroundMode; - - public EMR_SETBKMODE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETBKMODE }; - } - - public override void Read(BinaryReader reader) - { - BackgroundMode = (BackgroundMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)BackgroundMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBRUSHORGEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBRUSHORGEX.cs deleted file mode 100644 index f03dcef5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETBRUSHORGEX.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETBRUSHORGEX : Record - { - public int X; - - public int Y; - - public EMR_SETBRUSHORGEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SETBRUSHORGEX }; - } - - public override void Read(BinaryReader reader) - { - X = reader.ReadInt32(); - Y = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORADJUSTMENT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORADJUSTMENT.cs deleted file mode 100644 index f77d12c3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORADJUSTMENT.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Emf.Objects; - - - internal class EMR_SETCOLORADJUSTMENT : Record - { - public Objects.ColorAdjustment ColorAdjustment { get; set; } = new(); - - public EMR_SETCOLORADJUSTMENT() - { - Header = new RecordHeader { Type = RecordType.EMR_SETCOLORADJUSTMENT }; - } - - public override void Read(BinaryReader reader) - { - ColorAdjustment.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - ColorAdjustment.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORSPACE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORSPACE.cs deleted file mode 100644 index 08b6f57e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETCOLORSPACE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETCOLORSPACE : Record - { - public uint IhCS; - - public EMR_SETCOLORSPACE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETCOLORSPACE }; - } - - public override void Read(BinaryReader reader) - { - IhCS = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhCS); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMMODE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMMODE.cs deleted file mode 100644 index 00c1fd0f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMMODE.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SETICMMODE : Record - { - public IcmMode IcmMode; - - public EMR_SETICMMODE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETICMMODE }; - } - - public override void Read(BinaryReader reader) - { - IcmMode = (IcmMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)IcmMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEA.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEA.cs deleted file mode 100644 index 00639647..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEA.cs +++ /dev/null @@ -1,46 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SETICMPROFILEA : Record - { - public IcmProfileFlags DwFlags; - - public uint CbName; - - public uint CbData; - - public byte[] NameData { get; set; } = Array.Empty(); - - public byte[] ProfileData { get; set; } = Array.Empty(); - - public EMR_SETICMPROFILEA() - { - Header = new RecordHeader { Type = RecordType.EMR_SETICMPROFILEA }; - } - - public override void Read(BinaryReader reader) - { - DwFlags = (IcmProfileFlags)reader.ReadUInt32(); - CbName = reader.ReadUInt32(); - CbData = reader.ReadUInt32(); - NameData = reader.ReadBytes(Convert.ToInt32(CbName)); - ProfileData = reader.ReadBytes(Convert.ToInt32(CbData)); - } - - public override void Write(BinaryWriter writer) - { - uint nameLength = CbName == 0 ? (uint)NameData.Length : CbName; - uint dataLength = CbData == 0 ? (uint)ProfileData.Length : CbData; - writer.Write((uint)DwFlags); - writer.Write(nameLength); - writer.Write(dataLength); - writer.Write(NameData); - writer.Write(ProfileData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEW.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEW.cs deleted file mode 100644 index ac43a50d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETICMPROFILEW.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - - internal class EMR_SETICMPROFILEW : Record - { - public IcmProfileFlags DwFlags; - - public uint CbName; - - public uint CbData; - - public byte[] NameData { get; set; } = Array.Empty(); - - public byte[] ProfileData { get; set; } = Array.Empty(); - - public EMR_SETICMPROFILEW() - { - Header = new RecordHeader { Type = RecordType.EMR_SETICMPROFILEW }; - } - - public override void Read(BinaryReader reader) - { - DwFlags = (IcmProfileFlags)reader.ReadUInt32(); - CbName = reader.ReadUInt32(); - CbData = reader.ReadUInt32(); - NameData = reader.ReadBytes(Convert.ToInt32(CbName)); - ProfileData = reader.ReadBytes(Convert.ToInt32(CbData)); - } - - public override void Write(BinaryWriter writer) - { - uint nameLength = CbName == 0 ? (uint)NameData.Length : CbName; - uint dataLength = CbData == 0 ? (uint)ProfileData.Length : CbData; - writer.Write((uint)DwFlags); - writer.Write(nameLength); - writer.Write(dataLength); - writer.Write(NameData); - writer.Write(ProfileData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLAYOUT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLAYOUT.cs deleted file mode 100644 index 2f894db4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLAYOUT.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETLAYOUT : Record - { - public Metafile.Wmf.Enumerations.Layout LayoutMode; - - public EMR_SETLAYOUT() - { - Header = new RecordHeader { Type = RecordType.EMR_SETLAYOUT }; - } - - public override void Read(BinaryReader reader) - { - LayoutMode = (Metafile.Wmf.Enumerations.Layout)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)LayoutMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLINKEDUFIS.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLINKEDUFIS.cs deleted file mode 100644 index 810617dc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETLINKEDUFIS.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_SETLINKEDUFIS : Record - { - public uint NumberOfLinkedUfis; - - public byte[] LinkedUfisData { get; set; } = Array.Empty(); - - public EMR_SETLINKEDUFIS() - { - Header = new RecordHeader { Type = RecordType.EMR_SETLINKEDUFIS }; - } - - public override void Read(BinaryReader reader) - { - NumberOfLinkedUfis = reader.ReadUInt32(); - int remaining = Convert.ToInt32(Header.Size) - 12; - if (remaining > 0) - { - LinkedUfisData = reader.ReadBytes(remaining); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(NumberOfLinkedUfis); - writer.Write(LinkedUfisData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPMODE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPMODE.cs deleted file mode 100644 index ed4bc5df..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPMODE.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - - internal class EMR_SETMAPMODE : Record - { - public Wmf.Enumerations.MapMode MapMode; - - public EMR_SETMAPMODE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETMAPMODE }; - } - - public override void Read(BinaryReader reader) - { - MapMode = (Wmf.Enumerations.MapMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)MapMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPPERFLAGS.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPPERFLAGS.cs deleted file mode 100644 index 173738cd..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMAPPERFLAGS.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETMAPPERFLAGS : Record - { - public uint MapperValues; - - public EMR_SETMAPPERFLAGS() - { - Header = new RecordHeader { Type = RecordType.EMR_SETMAPPERFLAGS }; - } - - public override void Read(BinaryReader reader) - { - MapperValues = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(MapperValues); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMETARGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMETARGN.cs deleted file mode 100644 index b3875511..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMETARGN.cs +++ /dev/null @@ -1,24 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETMETARGN : Record - { - public EMR_SETMETARGN() - { - Header = new RecordHeader { Type = RecordType.EMR_SETMETARGN }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMITERLIMIT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMITERLIMIT.cs deleted file mode 100644 index 771bcb45..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETMITERLIMIT.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETMITERLIMIT : Record - { - public float MiterLimit; - - public EMR_SETMITERLIMIT() - { - Header = new RecordHeader { Type = RecordType.EMR_SETMITERLIMIT }; - } - - public override void Read(BinaryReader reader) - { - MiterLimit = reader.ReadSingle(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(MiterLimit); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPALETTEENTRIES.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPALETTEENTRIES.cs deleted file mode 100644 index ef10a775..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPALETTEENTRIES.cs +++ /dev/null @@ -1,47 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System; - using System.IO; - - internal class EMR_SETPALETTEENTRIES : Record - { - public uint IhPal; - - public uint Start; - - public uint NumberOfEntries; - - public byte[] PaletteEntries { get; set; } = Array.Empty(); - - public EMR_SETPALETTEENTRIES() - { - Header = new RecordHeader { Type = RecordType.EMR_SETPALETTEENTRIES }; - } - - public override void Read(BinaryReader reader) - { - IhPal = reader.ReadUInt32(); - Start = reader.ReadUInt32(); - NumberOfEntries = reader.ReadUInt32(); - - int remaining = Convert.ToInt32(Header.Size) - 20; - if (remaining > 0) - { - PaletteEntries = reader.ReadBytes(remaining); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(IhPal); - writer.Write(Start); - uint entryCount = NumberOfEntries == 0 ? (uint)(PaletteEntries.Length / 4) : NumberOfEntries; - writer.Write(entryCount); - writer.Write(PaletteEntries); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPIXELV.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPIXELV.cs deleted file mode 100644 index d5439639..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPIXELV.cs +++ /dev/null @@ -1,35 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_SETPIXELV : Record - { - public PointL Position; - - public ColorRef Color; - - public EMR_SETPIXELV() - { - Header = new RecordHeader { Type = RecordType.EMR_SETPIXELV }; - } - - public override void Read(BinaryReader reader) - { - Position = new PointL(); - Position.Read(reader); - Color.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Position.Write(writer); - Color.Write(writer); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPOLYFILLMODE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPOLYFILLMODE.cs deleted file mode 100644 index d9f8556e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETPOLYFILLMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETPOLYFILLMODE : Record - { - public Wmf.Enumerations.PolyFillMode PolyFillMode; - - public EMR_SETPOLYFILLMODE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETPOLYFILLMODE }; - } - - public override void Read(BinaryReader reader) - { - PolyFillMode = (Wmf.Enumerations.PolyFillMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)PolyFillMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETROP2.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETROP2.cs deleted file mode 100644 index 39f6d2f8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETROP2.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETROP2 : Record - { - public Metafile.Wmf.Enumerations.BinaryRasterOperation DrawMode; - - public EMR_SETROP2() - { - Header = new RecordHeader { Type = RecordType.EMR_SETROP2 }; - } - - public override void Read(BinaryReader reader) - { - DrawMode = (Metafile.Wmf.Enumerations.BinaryRasterOperation)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)DrawMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETSTRETCHBLTMODE.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETSTRETCHBLTMODE.cs deleted file mode 100644 index 797c99af..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETSTRETCHBLTMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETSTRETCHBLTMODE : Record - { - public Wmf.Enumerations.StretchMode StretchMode; - - public EMR_SETSTRETCHBLTMODE() - { - Header = new RecordHeader { Type = RecordType.EMR_SETSTRETCHBLTMODE }; - } - - public override void Read(BinaryReader reader) - { - StretchMode = (Wmf.Enumerations.StretchMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)StretchMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTALIGN.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTALIGN.cs deleted file mode 100644 index 0a0554c9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTALIGN.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETTEXTALIGN : Record - { - public Wmf.Flags.TextAlignmentMode TextAlignmentMode; - - public EMR_SETTEXTALIGN() - { - Header = new RecordHeader { Type = RecordType.EMR_SETTEXTALIGN }; - } - - public override void Read(BinaryReader reader) - { - TextAlignmentMode = (Wmf.Flags.TextAlignmentMode)reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write((uint)TextAlignmentMode); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTCOLOR.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTCOLOR.cs deleted file mode 100644 index b4ae7648..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTCOLOR.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_SETTEXTCOLOR : Record - { - public ColorRef Color; - - public EMR_SETTEXTCOLOR() - { - Header = new RecordHeader { Type = RecordType.EMR_SETTEXTCOLOR }; - } - - public override void Read(BinaryReader reader) - { - Color.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Color.Write(writer); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTJUSTIFICATION.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTJUSTIFICATION.cs deleted file mode 100644 index f797dbe0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETTEXTJUSTIFICATION.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETTEXTJUSTIFICATION : Record - { - public uint BreakExtra; - - public uint BreakCount; - - public EMR_SETTEXTJUSTIFICATION() - { - Header = new RecordHeader { Type = RecordType.EMR_SETTEXTJUSTIFICATION }; - } - - public override void Read(BinaryReader reader) - { - BreakExtra = reader.ReadUInt32(); - BreakCount = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(BreakExtra); - writer.Write(BreakCount); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTEXTEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTEXTEX.cs deleted file mode 100644 index 33731874..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTEXTEX.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETVIEWPORTEXTEX : Record - { - public int XExtent; - - public int YExtent; - - public EMR_SETVIEWPORTEXTEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SETVIEWPORTEXTEX }; - } - - public override void Read(BinaryReader reader) - { - XExtent = reader.ReadInt32(); - YExtent = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(XExtent); - writer.Write(YExtent); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTORGEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTORGEX.cs deleted file mode 100644 index 594d3c35..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETVIEWPORTORGEX.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETVIEWPORTORGEX : Record - { - public int X; - - public int Y; - - public EMR_SETVIEWPORTORGEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SETVIEWPORTORGEX }; - } - - public override void Read(BinaryReader reader) - { - X = reader.ReadInt32(); - Y = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWEXTEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWEXTEX.cs deleted file mode 100644 index 4e3c354c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWEXTEX.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETWINDOWEXTEX : Record - { - public int XExtent; - - public int YExtent; - - public EMR_SETWINDOWEXTEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SETWINDOWEXTEX }; - } - - public override void Read(BinaryReader reader) - { - XExtent = reader.ReadInt32(); - YExtent = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(XExtent); - writer.Write(YExtent); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWORGEX.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWORGEX.cs deleted file mode 100644 index 7f0ff87e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWINDOWORGEX.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETWINDOWORGEX : Record - { - public int X; - - public int Y; - - public EMR_SETWINDOWORGEX() - { - Header = new RecordHeader { Type = RecordType.EMR_SETWINDOWORGEX }; - } - - public override void Read(BinaryReader reader) - { - X = reader.ReadInt32(); - Y = reader.ReadInt32(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - } - } -} - diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWORLDTRANSFORM.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWORLDTRANSFORM.cs deleted file mode 100644 index caf459d4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SETWORLDTRANSFORM.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_SETWORLDTRANSFORM : Record - { - public float M11; - - public float M12; - - public float M21; - - public float M22; - - public float Dx; - - public float Dy; - - public EMR_SETWORLDTRANSFORM() - { - Header = new RecordHeader { Type = RecordType.EMR_SETWORLDTRANSFORM }; - } - - public override void Read(BinaryReader reader) - { - M11 = reader.ReadSingle(); - M12 = reader.ReadSingle(); - M21 = reader.ReadSingle(); - M22 = reader.ReadSingle(); - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(M11); - writer.Write(M12); - writer.Write(M21); - writer.Write(M22); - writer.Write(Dx); - writer.Write(Dy); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SMALLTEXTOUT.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SMALLTEXTOUT.cs deleted file mode 100644 index 824b4e62..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_SMALLTEXTOUT.cs +++ /dev/null @@ -1,56 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_SMALLTEXTOUT : Record - { - public PointL Reference; - - public uint Chars; - - public ExtTextOutOptions FuOptions; - - public RectL? Bounds; - - public byte[] TextBytes { get; set; } = []; - - public EMR_SMALLTEXTOUT() - { - Header = new RecordHeader { Type = RecordType.EMR_SMALLTEXTOUT }; - } - - public override void Read(BinaryReader reader) - { - Reference = new PointL(); - Reference.Read(reader); - Chars = reader.ReadUInt32(); - FuOptions = (ExtTextOutOptions)reader.ReadUInt32(); - - if ((FuOptions & (ExtTextOutOptions.ETO_OPAQUE | ExtTextOutOptions.ETO_CLIPPED)) != 0) - { - var bounds = new RectL(); - bounds.Read(reader); - Bounds = bounds; - } - - TextBytes = reader.ReadBytes((int)Chars); - } - - public override void Write(BinaryWriter writer) - { - uint chars = Chars == 0 ? (uint)TextBytes.Length : Chars; - Reference.Write(writer); - writer.Write(chars); - writer.Write((uint)FuOptions); - if (Bounds.HasValue) - { - Bounds.Value.Write(writer); - } - writer.Write(TextBytes); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEANDFILLPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEANDFILLPATH.cs deleted file mode 100644 index 624a0c9a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEANDFILLPATH.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_STROKEANDFILLPATH : Record - { - public RectL Bounds; - - public EMR_STROKEANDFILLPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_STROKEANDFILLPATH }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Bounds.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEPATH.cs deleted file mode 100644 index e50a79ad..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_STROKEPATH.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; -using MiniSoftware.Drawing.Metafile.Emf.Records; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class EMR_STROKEPATH : Record - { - public RectL Bounds; - - public EMR_STROKEPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_STROKEPATH }; - } - - public override void Read(BinaryReader reader) - { - Bounds = new RectL(); - Bounds.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - Bounds.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_WIDENPATH.cs b/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_WIDENPATH.cs deleted file mode 100644 index 34848d43..00000000 --- a/src/MiniPdf/Drawing/Metafile/Emf/Records/StateRecordTypes/EMR_WIDENPATH.cs +++ /dev/null @@ -1,23 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Emf; - -namespace MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using System.IO; - - internal class EMR_WIDENPATH : Record - { - public EMR_WIDENPATH() - { - Header = new RecordHeader { Type = RecordType.EMR_WIDENPATH }; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/EmfPlusReader.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/EmfPlusReader.cs deleted file mode 100644 index e4158801..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/EmfPlusReader.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - using MiniSoftware.Drawing.Metafile.EmfPlus.Records; - - internal class EmfPlusReader - { - public List Records { get; } = new(); - - public uint DataSize { get; private set; } - - public uint CommentIdentifier { get; private set; } - - //public MetaHeader Header { get; private set; } - - public void Read(Stream stream) - { - var reader = new BinaryReader(stream); - - DataSize = reader.ReadUInt32(); - CommentIdentifier = reader.ReadUInt32(); - - while (stream.Position < stream.Length) - { - - var header = new RecordHeader(); - header.Read(reader); - - //long expectedEndPosition = stream.Position + (header.Size) - 8; - var record = CreateRecord(header, reader); - if (record == null) - { - record = new Record { Header = header }; - record.Read(reader); - } - - this.Records.Add(record); - //stream.Position = expectedEndPosition; - } - } - - public static Record? CreateRecord(RecordHeader header, BinaryReader reader) - { - Record? record = header.Type switch - { - RecordType.EmfPlusHeader => new EmfPlusHeaderRecord(), - RecordType.EmfPlusEndOfFile => new EmfPlusEndOfFileRecord(), - RecordType.EmfPlusComment => new EmfPlusCommentRecord(), - RecordType.EmfPlusGetDC => new EmfPlusGetDCRecord(), - RecordType.EmfPlusMultiFormatStart => new EmfPlusMultiFormatStartRecord(), - RecordType.EmfPlusMultiFormatSection => new EmfPlusMultiFormatSectionRecord(), - RecordType.EmfPlusMultiFormatEnd => new EmfPlusMultiFormatEndRecord(), - RecordType.EmfPlusObject => new EmfPlusObjectRecord(), - RecordType.EmfPlusClear => new EmfPlusClearRecord(), - RecordType.EmfPlusFillRects => new EmfPlusFillRectsRecord(), - RecordType.EmfPlusDrawRects => new EmfPlusDrawRectsRecord(), - RecordType.EmfPlusFillPolygon => new EmfPlusFillPolygonRecord(), - RecordType.EmfPlusDrawLines => new EmfPlusDrawLinesRecord(), - RecordType.EmfPlusFillEllipse => new EmfPlusFillEllipseRecord(), - RecordType.EmfPlusDrawEllipse => new EmfPlusDrawEllipseRecord(), - RecordType.EmfPlusFillPie => new EmfPlusFillPieRecord(), - RecordType.EmfPlusDrawPie => new EmfPlusDrawPieRecord(), - RecordType.EmfPlusDrawArc => new EmfPlusDrawArcRecord(), - RecordType.EmfPlusFillRegion => new EmfPlusFillRegionRecord(), - RecordType.EmfPlusFillPath => new EmfPlusFillPathRecord(), - RecordType.EmfPlusDrawPath => new EmfPlusDrawPathRecord(), - RecordType.EmfPlusFillClosedCurve => new EmfPlusFillClosedCurveRecord(), - RecordType.EmfPlusDrawClosedCurve => new EmfPlusDrawClosedCurveRecord(), - RecordType.EmfPlusDrawCurve => new EmfPlusDrawCurveRecord(), - RecordType.EmfPlusDrawBeziers => new EmfPlusDrawBeziersRecord(), - RecordType.EmfPlusDrawImage => new EmfPlusDrawImageRecord(), - RecordType.EmfPlusDrawImagePoints => new EmfPlusDrawImagePointsRecord(), - RecordType.EmfPlusDrawString => new EmfPlusDrawStringRecord(), - RecordType.EmfPlusSetRenderingOrigin => new EmfPlusSetRenderingOriginRecord(), - RecordType.EmfPlusSetAntiAliasMode => new EmfPlusSetAntiAliasModeRecord(), - RecordType.EmfPlusSetTextRenderingHint => new EmfPlusSetTextRenderingHintRecord(), - RecordType.EmfPlusSetTextContrast => new EmfPlusSetTextContrastRecord(), - RecordType.EmfPlusSetInterpolationMode => new EmfPlusSetInterpolationModeRecord(), - RecordType.EmfPlusSetPixelOffsetMode => new EmfPlusSetPixelOffsetModeRecord(), - RecordType.EmfPlusSetCompositingMode => new EmfPlusSetCompositingModeRecord(), - RecordType.EmfPlusSetCompositingQuality => new EmfPlusSetCompositingQualityRecord(), - RecordType.EmfPlusSave => new EmfPlusSaveRecord(), - RecordType.EmfPlusRestore => new EmfPlusRestoreRecord(), - RecordType.EmfPlusBeginContainer => new EmfPlusBeginContainerRecord(), - RecordType.EmfPlusBeginContainerNoParams => new EmfPlusBeginContainerNoParamsRecord(), - RecordType.EmfPlusEndContainer => new EmfPlusEndContainerRecord(), - RecordType.EmfPlusSetWorldTransform => new EmfPlusSetWorldTransformRecord(), - RecordType.EmfPlusResetWorldTransform => new EmfPlusResetWorldTransformRecord(), - RecordType.EmfPlusMultiplyWorldTransform => new EmfPlusMultiplyWorldTransformRecord(), - RecordType.EmfPlusTranslateWorldTransform => new EmfPlusTranslateWorldTransformRecord(), - RecordType.EmfPlusScaleWorldTransform => new EmfPlusScaleWorldTransformRecord(), - RecordType.EmfPlusRotateWorldTransform => new EmfPlusRotateWorldTransformRecord(), - RecordType.EmfPlusSetPageTransform => new EmfPlusSetPageTransformRecord(), - RecordType.EmfPlusResetClip => new EmfPlusResetClipRecord(), - RecordType.EmfPlusSetClipRect => new EmfPlusSetClipRectRecord(), - RecordType.EmfPlusSetClipPath => new EmfPlusSetClipPathRecord(), - RecordType.EmfPlusSetClipRegion => new EmfPlusSetClipRegionRecord(), - RecordType.EmfPlusOffsetClip => new EmfPlusOffsetClipRecord(), - RecordType.EmfPlusDrawDriverstring => new EmfPlusDrawDriverstringRecord(), - RecordType.EmfPlusStrokeFillPath => new EmfPlusStrokeFillPathRecord(), - RecordType.EmfPlusSerializableObject => new EmfPlusSerializableObjectRecord(), - RecordType.EmfPlusSetTSGraphics => new EmfPlusSetTSGraphicsRecord(), - RecordType.EmfPlusSetTSClip => new EmfPlusSetTSClipRecord(), - _ => null, - }; - - if (record is not null) - { - record.Header = header; - record.Read(reader); - } - - return record; - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCombineMode.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCombineMode.cs deleted file mode 100644 index 989cbb30..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCombineMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusCombineMode : ushort - { - Replace = 0, - Intersect = 1, - Union = 2, - Xor = 3, - Exclude = 4, - Complement = 5 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingMode.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingMode.cs deleted file mode 100644 index 373dfa44..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingMode.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusCompositingMode : ushort - { - SourceOver = 0, - SourceCopy = 1 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingQuality.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingQuality.cs deleted file mode 100644 index 644352c1..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusCompositingQuality.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusCompositingQuality : ushort - { - Invalid = 0, - Default = 1, - HighSpeed = 2, - HighQuality = 3, - GammaCorrected = 4, - AssumeLinear = 5 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusHeaderFlags.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusHeaderFlags.cs deleted file mode 100644 index 5338ce65..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusHeaderFlags.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - using System; - - [Flags] - internal enum EmfPlusHeaderFlags : uint - { - None = 0x00000000, - Display = 0x00000001 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusInterpolationMode.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusInterpolationMode.cs deleted file mode 100644 index c51cfa05..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusInterpolationMode.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusInterpolationMode : ushort - { - Invalid = 0, - Default = 1, - LowQuality = 2, - HighQuality = 3, - Bilinear = 4, - Bicubic = 5, - NearestNeighbor = 6, - HighQualityBilinear = 7, - HighQualityBicubic = 8 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusMatrixOrder.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusMatrixOrder.cs deleted file mode 100644 index 2c2d02ca..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusMatrixOrder.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusMatrixOrder : ushort - { - Prepend = 0, - Append = 1 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusPixelOffsetMode.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusPixelOffsetMode.cs deleted file mode 100644 index c8f5dd44..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusPixelOffsetMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusPixelOffsetMode : ushort - { - Invalid = 0, - Default = 1, - HighSpeed = 2, - HighQuality = 3, - None = 4, - Half = 5 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusSmoothingMode.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusSmoothingMode.cs deleted file mode 100644 index 930d8828..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusSmoothingMode.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusSmoothingMode : ushort - { - Invalid = 0, - Default = 1, - HighSpeed = 2, - HighQuality = 3, - None = 4, - AntiAlias = 5 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusTextRenderingHint.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusTextRenderingHint.cs deleted file mode 100644 index 6684ca63..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusTextRenderingHint.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - /// - /// Specifies the text rendering hint for EMF+ text rendering. - /// - internal enum EmfPlusTextRenderingHint : ushort - { - /// - /// Use the system default text rendering hint. - /// - SystemDefault = 0, - - /// - /// Use single bit per pixel with grid fit. - /// - SingleBitPerPixelGridFit = 1, - - /// - /// Use single bit per pixel. - /// - SingleBitPerPixel = 2, - - /// - /// Use anti-alias with grid fit. - /// - AntiAliasGridFit = 3, - - /// - /// Use anti-alias. - /// - AntiAlias = 4, - - /// - /// Use ClearType with grid fit. - /// - ClearTypeGridFit = 5 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusUnitType.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusUnitType.cs deleted file mode 100644 index a3614c2a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/EmfPlusUnitType.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum EmfPlusUnitType : uint - { - UnitWorld = 0, - UnitDisplay = 1, - UnitPixel = 2, - UnitPoint = 3, - UnitInch = 4, - UnitDocument = 5, - UnitMillimeter = 6 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/ObjectType.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/ObjectType.cs deleted file mode 100644 index b45a0928..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/ObjectType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum ObjectType : ushort - { - ObjectTypeInvalid = 0x00000000, - ObjectTypeBrush = 0x00000001, - ObjectTypePen = 0x00000002, - ObjectTypePath = 0x00000003, - ObjectTypeRegion = 0x00000004, - ObjectTypeImage = 0x00000005, - ObjectTypeFont = 0x00000006, - ObjectTypeStringFormat = 0x00000007, - ObjectTypeImageAttributes = 0x00000008, - ObjectTypeCustomLineCap = 0x00000009 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RecordType.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RecordType.cs deleted file mode 100644 index 73ee9de6..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RecordType.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum RecordType : ushort - { - EmfPlusHeader = 0x4001, - EmfPlusEndOfFile = 0x4002, - EmfPlusComment = 0x4003, - EmfPlusGetDC = 0x4004, - EmfPlusMultiFormatStart = 0x4005, - EmfPlusMultiFormatSection = 0x4006, - EmfPlusMultiFormatEnd = 0x4007, - EmfPlusObject = 0x4008, - EmfPlusClear = 0x4009, - EmfPlusFillRects = 0x400A, - EmfPlusDrawRects = 0x400B, - EmfPlusFillPolygon = 0x400C, - EmfPlusDrawLines = 0x400D, - EmfPlusFillEllipse = 0x400E, - EmfPlusDrawEllipse = 0x400F, - EmfPlusFillPie = 0x4010, - EmfPlusDrawPie = 0x4011, - EmfPlusDrawArc = 0x4012, - EmfPlusFillRegion = 0x4013, - EmfPlusFillPath = 0x4014, - EmfPlusDrawPath = 0x4015, - EmfPlusFillClosedCurve = 0x4016, - EmfPlusDrawClosedCurve = 0x4017, - EmfPlusDrawCurve = 0x4018, - EmfPlusDrawBeziers = 0x4019, - EmfPlusDrawImage = 0x401A, - EmfPlusDrawImagePoints = 0x401B, - EmfPlusDrawString = 0x401C, - EmfPlusSetRenderingOrigin = 0x401D, - EmfPlusSetAntiAliasMode = 0x401E, - EmfPlusSetTextRenderingHint = 0x401F, - EmfPlusSetTextContrast = 0x4020, - EmfPlusSetInterpolationMode = 0x4021, - EmfPlusSetPixelOffsetMode = 0x4022, - EmfPlusSetCompositingMode = 0x4023, - EmfPlusSetCompositingQuality = 0x4024, - EmfPlusSave = 0x4025, - EmfPlusRestore = 0x4026, - EmfPlusBeginContainer = 0x4027, - EmfPlusBeginContainerNoParams = 0x4028, - EmfPlusEndContainer = 0x4029, - EmfPlusSetWorldTransform = 0x402A, - EmfPlusResetWorldTransform = 0x402B, - EmfPlusMultiplyWorldTransform = 0x402C, - EmfPlusTranslateWorldTransform = 0x402D, - EmfPlusScaleWorldTransform = 0x402E, - EmfPlusRotateWorldTransform = 0x402F, - EmfPlusSetPageTransform = 0x4030, - EmfPlusResetClip = 0x4031, - EmfPlusSetClipRect = 0x4032, - EmfPlusSetClipPath = 0x4033, - EmfPlusSetClipRegion = 0x4034, - EmfPlusOffsetClip = 0x4035, - EmfPlusDrawDriverstring = 0x4036, - EmfPlusStrokeFillPath = 0x4037, - EmfPlusSerializableObject = 0x4038, - EmfPlusSetTSGraphics = 0x4039, - EmfPlusSetTSClip = 0x403A - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RegionNodeDataType.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RegionNodeDataType.cs deleted file mode 100644 index d6eec771..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Enumerations/RegionNodeDataType.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations -{ - internal enum RegionNodeDataType - { - RegionNodeDataTypeAnd = 0x00000001, - RegionNodeDataTypeOr = 0x00000002, - RegionNodeDataTypeXor = 0x00000003, - RegionNodeDataTypeExclude = 0x00000004, - RegionNodeDataTypeComplement = 0x00000005, - RegionNodeDataTypeRect = 0x10000000, - RegionNodeDataTypePath = 0x10000001, - RegionNodeDataTypeEmpty = 0x10000002, - RegionNodeDataTypeInfinite = 0x10000003 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusGraphicsVersionObject.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusGraphicsVersionObject.cs deleted file mode 100644 index 570fe0d1..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusGraphicsVersionObject.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Objects -{ - internal class EmfPlusGraphicsVersionObject - { - //public uint - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRectFObject.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRectFObject.cs deleted file mode 100644 index 238ba9e7..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRectFObject.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Objects -{ - using System.IO; - - internal class EmfPlusRectFObject - { - public float X { get; set; } - - public float Y { get; set; } - - public float Width { get; set; } - - public float Height { get; set; } - - public void Read(BinaryReader reader) - { - X = reader.ReadSingle(); - Y = reader.ReadSingle(); - Width = reader.ReadSingle(); - Height = reader.ReadSingle(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - writer.Write(Width); - writer.Write(Height); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionNodeObject.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionNodeObject.cs deleted file mode 100644 index 59160ccf..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionNodeObject.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Objects -{ - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusRegionNodeObject - { - public RegionNodeDataType Type; - - - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionObject.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionObject.cs deleted file mode 100644 index 725d3a7c..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Objects/EmfPlusRegionObject.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Objects -{ - internal class EmfPlusRegionObject - { - public uint Version; - - public uint RegionNodeCount; - - - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerNoParamsRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerNoParamsRecord.cs deleted file mode 100644 index 02fb5695..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerNoParamsRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusBeginContainerNoParamsRecord : Record - { - public uint StackIndex; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - StackIndex = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(StackIndex); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerRecord.cs deleted file mode 100644 index ac53893c..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusBeginContainerRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusBeginContainerRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusClearRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusClearRecord.cs deleted file mode 100644 index 64179ec6..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusClearRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusClearRecord : Record - { - public uint Color; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - Color = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Color); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusCommentRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusCommentRecord.cs deleted file mode 100644 index f68b1fb8..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusCommentRecord.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusCommentRecord : Record - { - public override void Read(BinaryReader reader) - { - base.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawArcRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawArcRecord.cs deleted file mode 100644 index eea3c9ec..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawArcRecord.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawArcRecord : Record - { - public ushort PenId => Header.Flags; - - public EmfPlusRectFObject Rect { get; set; } = new(); - - public float StartAngle; - - public float SweepAngle; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 24) - { - Rect.Read(reader); - StartAngle = reader.ReadSingle(); - SweepAngle = reader.ReadSingle(); - - int remaining = (int)Header.DataSize - 24; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - Rect.Write(writer); - writer.Write(StartAngle); - writer.Write(SweepAngle); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawBeziersRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawBeziersRecord.cs deleted file mode 100644 index adb42583..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawBeziersRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawBeziersRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawClosedCurveRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawClosedCurveRecord.cs deleted file mode 100644 index 681d28ae..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawClosedCurveRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawClosedCurveRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawCurveRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawCurveRecord.cs deleted file mode 100644 index 2e3bfe21..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawCurveRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawCurveRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawDriverstringRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawDriverstringRecord.cs deleted file mode 100644 index e9e1132a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawDriverstringRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawDriverstringRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawEllipseRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawEllipseRecord.cs deleted file mode 100644 index 2585f061..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawEllipseRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawEllipseRecord : Record - { - public ushort PenId => Header.Flags; - - public EmfPlusRectFObject Rect { get; set; } = new(); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - Rect.Read(reader); - int remaining = (int)Header.DataSize - 16; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - Rect.Write(writer); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImagePointsRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImagePointsRecord.cs deleted file mode 100644 index ca6ea473..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImagePointsRecord.cs +++ /dev/null @@ -1,82 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusDrawImagePointsRecord : Record - { - public uint ImageAttributesId; - - public EmfPlusUnitType SourceUnit; - - public float SourceX; - - public float SourceY; - - public float SourceWidth; - - public float SourceHeight; - - public uint PointCount; - - public float[] Points { get; set; } = []; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 32) - { - ImageAttributesId = reader.ReadUInt32(); - SourceUnit = (EmfPlusUnitType)reader.ReadUInt32(); - SourceX = reader.ReadSingle(); - SourceY = reader.ReadSingle(); - SourceWidth = reader.ReadSingle(); - SourceHeight = reader.ReadSingle(); - PointCount = reader.ReadUInt32(); - - int pointsFloatCount = (int)(PointCount * 2); - int expectedPointBytes = pointsFloatCount * 4; - if (Header.DataSize >= 32 + expectedPointBytes) - { - Points = new float[pointsFloatCount]; - for (int i = 0; i < pointsFloatCount; i++) - { - Points[i] = reader.ReadSingle(); - } - - int remaining = (int)Header.DataSize - 32 - expectedPointBytes; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - uint pointCount = PointCount == 0 ? (uint)(Points.Length / 2) : PointCount; - writer.Write(ImageAttributesId); - writer.Write((uint)SourceUnit); - writer.Write(SourceX); - writer.Write(SourceY); - writer.Write(SourceWidth); - writer.Write(SourceHeight); - writer.Write(pointCount); - int pointFloatCount = (int)(pointCount * 2); - for (int i = 0; i < pointFloatCount; i++) - { - writer.Write(Points[i]); - } - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImageRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImageRecord.cs deleted file mode 100644 index 98aceb98..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawImageRecord.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawImageRecord : Record - { - public uint ImageAttributesId; - - public EmfPlusUnitType SourceUnit; - - public EmfPlusRectFObject SourceRect { get; set; } = new(); - - public EmfPlusRectFObject DestRect { get; set; } = new(); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 40) - { - ImageAttributesId = reader.ReadUInt32(); - SourceUnit = (EmfPlusUnitType)reader.ReadUInt32(); - SourceRect.Read(reader); - DestRect.Read(reader); - int remaining = (int)Header.DataSize - 40; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(ImageAttributesId); - writer.Write((uint)SourceUnit); - SourceRect.Write(writer); - DestRect.Write(writer); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawLinesRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawLinesRecord.cs deleted file mode 100644 index 67057c1a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawLinesRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawLinesRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPathRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPathRecord.cs deleted file mode 100644 index 256c7334..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPathRecord.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusDrawPathRecord : Record - { - public ushort PenId => Header.Flags; - - public uint PathId; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - PathId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(PathId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPieRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPieRecord.cs deleted file mode 100644 index 9957cc45..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawPieRecord.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawPieRecord : Record - { - public ushort PenId => Header.Flags; - - public EmfPlusRectFObject Rect { get; set; } = new(); - - public float StartAngle; - - public float SweepAngle; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 24) - { - Rect.Read(reader); - StartAngle = reader.ReadSingle(); - SweepAngle = reader.ReadSingle(); - - int remaining = (int)Header.DataSize - 24; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - Rect.Write(writer); - writer.Write(StartAngle); - writer.Write(SweepAngle); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawRectsRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawRectsRecord.cs deleted file mode 100644 index a3bcbb5d..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawRectsRecord.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawRectsRecord : Record - { - public ushort PenId => Header.Flags; - - public EmfPlusRectFObject[] Rects { get; set; } = []; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - int count = (int)(Header.DataSize / 16); - Rects = new EmfPlusRectFObject[count]; - for (int i = 0; i < count; i++) - { - var rect = new EmfPlusRectFObject(); - rect.Read(reader); - Rects[i] = rect; - } - - int remaining = (int)Header.DataSize - (count * 16); - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - foreach (var rect in Rects) - { - rect.Write(writer); - } - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawStringRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawStringRecord.cs deleted file mode 100644 index 1f818971..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusDrawStringRecord.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using System.Text; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusDrawStringRecord : Record - { - public uint BrushId { get; set; } - - public uint FormatId { get; set; } - - public uint Length { get; set; } - - public EmfPlusRectFObject LayoutRect { get; set; } = new(); - - public string StringData { get; set; } = string.Empty; - - public override void Read(BinaryReader reader) - { - BrushId = reader.ReadUInt32(); - FormatId = reader.ReadUInt32(); - Length = reader.ReadUInt32(); - LayoutRect.Read(reader); - StringData = Encoding.Unicode.GetString(reader.ReadBytes(Convert.ToInt32(Length * 2))); - - int bytesLeft = Convert.ToInt32(Header.DataSize - 28 - (Length * 2)); - if (bytesLeft > 0) - { - reader.ReadBytes(bytesLeft); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(BrushId); - writer.Write(FormatId); - - byte[] stringBytes = Encoding.Unicode.GetBytes(StringData); - Length = (uint)StringData.Length; - writer.Write(Length); - - LayoutRect.Write(writer); - writer.Write(stringBytes); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndContainerRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndContainerRecord.cs deleted file mode 100644 index 8e06867e..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndContainerRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusEndContainerRecord : Record - { - public uint StackIndex; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - StackIndex = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(StackIndex); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndOfFileRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndOfFileRecord.cs deleted file mode 100644 index 09dfcb32..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusEndOfFileRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusEndOfFileRecord : Record - { - public uint TotalObjectSize; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - TotalObjectSize = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(TotalObjectSize); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillClosedCurveRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillClosedCurveRecord.cs deleted file mode 100644 index d53b25d3..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillClosedCurveRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusFillClosedCurveRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillEllipseRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillEllipseRecord.cs deleted file mode 100644 index f9019ca8..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillEllipseRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusFillEllipseRecord : Record - { - public ushort BrushId => Header.Flags; - - public EmfPlusRectFObject Rect { get; set; } = new(); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - Rect.Read(reader); - int remaining = (int)Header.DataSize - 16; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - Rect.Write(writer); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPathRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPathRecord.cs deleted file mode 100644 index f287ae01..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPathRecord.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusFillPathRecord : Record - { - public ushort BrushId => Header.Flags; - - public uint PathId; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - PathId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(PathId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPieRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPieRecord.cs deleted file mode 100644 index 70a5f685..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPieRecord.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusFillPieRecord : Record - { - public ushort BrushId => Header.Flags; - - public EmfPlusRectFObject Rect { get; set; } = new(); - - public float StartAngle; - - public float SweepAngle; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 24) - { - Rect.Read(reader); - StartAngle = reader.ReadSingle(); - SweepAngle = reader.ReadSingle(); - - int remaining = (int)Header.DataSize - 24; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - Rect.Write(writer); - writer.Write(StartAngle); - writer.Write(SweepAngle); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPolygonRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPolygonRecord.cs deleted file mode 100644 index 83620440..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillPolygonRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusFillPolygonRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRectsRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRectsRecord.cs deleted file mode 100644 index 6d07196b..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRectsRecord.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusFillRectsRecord : Record - { - public ushort BrushId => Header.Flags; - - public EmfPlusRectFObject[] Rects { get; set; } = []; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - int count = (int)(Header.DataSize / 16); - Rects = new EmfPlusRectFObject[count]; - for (int i = 0; i < count; i++) - { - var rect = new EmfPlusRectFObject(); - rect.Read(reader); - Rects[i] = rect; - } - - int remaining = (int)Header.DataSize - (count * 16); - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - foreach (var rect in Rects) - { - rect.Write(writer); - } - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRegionRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRegionRecord.cs deleted file mode 100644 index 04625288..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusFillRegionRecord.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusFillRegionRecord : Record - { - public ushort BrushId => Header.Flags; - - public uint RegionId; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - RegionId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(RegionId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusGetDCRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusGetDCRecord.cs deleted file mode 100644 index bfa5bd71..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusGetDCRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusGetDCRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusHeaderRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusHeaderRecord.cs deleted file mode 100644 index d6ef8d43..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusHeaderRecord.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusHeaderRecord : Record - { - public uint Version; - public EmfPlusHeaderFlags EmfPlusFlags; - public uint LogicalDpiX; - public uint LogicalDpiY; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - Version = reader.ReadUInt32(); - EmfPlusFlags = (EmfPlusHeaderFlags)reader.ReadUInt32(); - LogicalDpiX = reader.ReadUInt32(); - LogicalDpiY = reader.ReadUInt32(); - - int remaining = Convert.ToInt32(Header.DataSize) - 16; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Version); - writer.Write((uint)EmfPlusFlags); - writer.Write(LogicalDpiX); - writer.Write(LogicalDpiY); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatEndRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatEndRecord.cs deleted file mode 100644 index 94fde234..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatEndRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusMultiFormatEndRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatSectionRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatSectionRecord.cs deleted file mode 100644 index c753251a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatSectionRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusMultiFormatSectionRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatStartRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatStartRecord.cs deleted file mode 100644 index 116eae0a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiFormatStartRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusMultiFormatStartRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiplyWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiplyWorldTransformRecord.cs deleted file mode 100644 index ab706d38..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusMultiplyWorldTransformRecord.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusMultiplyWorldTransformRecord : Record - { - public float M11; - public float M12; - public float M21; - public float M22; - public float Dx; - public float Dy; - - public EmfPlusMatrixOrder MatrixOrder => (EmfPlusMatrixOrder)(Header.Flags & 0x0001); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 24) - { - M11 = reader.ReadSingle(); - M12 = reader.ReadSingle(); - M21 = reader.ReadSingle(); - M22 = reader.ReadSingle(); - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 24; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(M11); - writer.Write(M12); - writer.Write(M21); - writer.Write(M22); - writer.Write(Dx); - writer.Write(Dy); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusObjectRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusObjectRecord.cs deleted file mode 100644 index 62386cc6..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusObjectRecord.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusObjectRecord : Record - { - public bool Continued - { - get - { - return Convert.ToBoolean(BitHelper.GetBits(this.Header.Flags, 0, 1, false)); - } - } - - public ObjectType ObjectType - { - get - { - return (ObjectType)BitHelper.GetBits(this.Header.Flags, 1, 7, false); - } - } - - public byte ObjectId - { - get - { - return Convert.ToByte(BitHelper.GetBits(this.Header.Flags, 8, 8, false)); - } - } - - public override string ToString() - { - return string.Format("{0} {1}",base.ToString(), this.ObjectType.ToString()); - } - - public override void Read(BinaryReader reader) - { - Data = reader.ReadBytes(Convert.ToInt32(Header.DataSize)); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusOffsetClipRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusOffsetClipRecord.cs deleted file mode 100644 index 20ca3658..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusOffsetClipRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusOffsetClipRecord : Record - { - public float Dx; - public float Dy; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 8) - { - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 8; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Dx); - writer.Write(Dy); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetClipRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetClipRecord.cs deleted file mode 100644 index 779c4646..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetClipRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusResetClipRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetWorldTransformRecord.cs deleted file mode 100644 index 50f85448..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusResetWorldTransformRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusResetWorldTransformRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRestoreRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRestoreRecord.cs deleted file mode 100644 index 0bba7917..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRestoreRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusRestoreRecord : Record - { - public uint StackIndex; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - StackIndex = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(StackIndex); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRotateWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRotateWorldTransformRecord.cs deleted file mode 100644 index 2f36530c..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusRotateWorldTransformRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusRotateWorldTransformRecord : Record - { - public float Angle; - - public EmfPlusMatrixOrder MatrixOrder => (EmfPlusMatrixOrder)(Header.Flags & 0x0001); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - Angle = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Angle); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSaveRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSaveRecord.cs deleted file mode 100644 index 6d99b0c5..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSaveRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSaveRecord : Record - { - public uint StackIndex; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - StackIndex = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(StackIndex); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusScaleWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusScaleWorldTransformRecord.cs deleted file mode 100644 index bd895434..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusScaleWorldTransformRecord.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusScaleWorldTransformRecord : Record - { - public float Sx; - public float Sy; - - public EmfPlusMatrixOrder MatrixOrder => (EmfPlusMatrixOrder)(Header.Flags & 0x0001); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 8) - { - Sx = reader.ReadSingle(); - Sy = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 8; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Sx); - writer.Write(Sy); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSerializableObjectRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSerializableObjectRecord.cs deleted file mode 100644 index 6d036451..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSerializableObjectRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSerializableObjectRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetAntiAliasModeRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetAntiAliasModeRecord.cs deleted file mode 100644 index 73b2611f..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetAntiAliasModeRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetAntiAliasModeRecord : Record - { - public EmfPlusSmoothingMode SmoothingMode => (EmfPlusSmoothingMode)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipPathRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipPathRecord.cs deleted file mode 100644 index 56aa4274..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipPathRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetClipPathRecord : Record - { - public uint PathId; - - public EmfPlusCombineMode CombineMode => (EmfPlusCombineMode)(Header.Flags & 0x000F); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - PathId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(PathId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRectRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRectRecord.cs deleted file mode 100644 index d37f4760..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRectRecord.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - using MiniSoftware.Drawing.Metafile.EmfPlus.Objects; - - internal class EmfPlusSetClipRectRecord : Record - { - public EmfPlusRectFObject ClipRect { get; set; } = new(); - - public EmfPlusCombineMode CombineMode => (EmfPlusCombineMode)(Header.Flags & 0x000F); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 16) - { - ClipRect.Read(reader); - int remaining = (int)Header.DataSize - 16; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - ClipRect.Write(writer); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRegionRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRegionRecord.cs deleted file mode 100644 index c19919a1..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetClipRegionRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetClipRegionRecord : Record - { - public uint RegionId; - - public EmfPlusCombineMode CombineMode => (EmfPlusCombineMode)(Header.Flags & 0x000F); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - RegionId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(RegionId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingModeRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingModeRecord.cs deleted file mode 100644 index ef345f93..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingModeRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetCompositingModeRecord : Record - { - public EmfPlusCompositingMode CompositingMode => (EmfPlusCompositingMode)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingQualityRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingQualityRecord.cs deleted file mode 100644 index da810291..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetCompositingQualityRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetCompositingQualityRecord : Record - { - public EmfPlusCompositingQuality CompositingQuality => (EmfPlusCompositingQuality)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetInterpolationModeRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetInterpolationModeRecord.cs deleted file mode 100644 index 242f08e5..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetInterpolationModeRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetInterpolationModeRecord : Record - { - public EmfPlusInterpolationMode InterpolationMode => (EmfPlusInterpolationMode)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPageTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPageTransformRecord.cs deleted file mode 100644 index 1aa37916..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPageTransformRecord.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetPageTransformRecord : Record - { - public float PageScale; - public EmfPlusUnitType PageUnit; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 8) - { - PageScale = reader.ReadSingle(); - PageUnit = (EmfPlusUnitType)reader.ReadUInt32(); - int remaining = (int)Header.DataSize - 8; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(PageScale); - writer.Write((uint)PageUnit); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPixelOffsetModeRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPixelOffsetModeRecord.cs deleted file mode 100644 index 241a7a34..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetPixelOffsetModeRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetPixelOffsetModeRecord : Record - { - public EmfPlusPixelOffsetMode PixelOffsetMode => (EmfPlusPixelOffsetMode)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetRenderingOriginRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetRenderingOriginRecord.cs deleted file mode 100644 index 229a56d8..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetRenderingOriginRecord.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSetRenderingOriginRecord : Record - { - public int X; - public int Y; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 8) - { - X = reader.ReadInt32(); - Y = reader.ReadInt32(); - int remaining = (int)Header.DataSize - 8; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(X); - writer.Write(Y); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSClipRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSClipRecord.cs deleted file mode 100644 index f87cd3df..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSClipRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSetTSClipRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSGraphicsRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSGraphicsRecord.cs deleted file mode 100644 index d06c0e00..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTSGraphicsRecord.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSetTSGraphicsRecord : Record - { - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextContrastRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextContrastRecord.cs deleted file mode 100644 index 5b7ac44a..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextContrastRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSetTextContrastRecord : Record - { - public uint TextContrast; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - TextContrast = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(TextContrast); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextRenderingHintRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextRenderingHintRecord.cs deleted file mode 100644 index beedb7a0..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetTextRenderingHintRecord.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusSetTextRenderingHintRecord : Record - { - public EmfPlusTextRenderingHint TextRenderingHint => (EmfPlusTextRenderingHint)(Header.Flags & 0x00FF); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize > 0) - { - Data = reader.ReadBytes((int)Header.DataSize); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetWorldTransformRecord.cs deleted file mode 100644 index 731f2d5d..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusSetWorldTransformRecord.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusSetWorldTransformRecord : Record - { - public float M11; - public float M12; - public float M21; - public float M22; - public float Dx; - public float Dy; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 24) - { - M11 = reader.ReadSingle(); - M12 = reader.ReadSingle(); - M21 = reader.ReadSingle(); - M22 = reader.ReadSingle(); - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 24; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(M11); - writer.Write(M12); - writer.Write(M21); - writer.Write(M22); - writer.Write(Dx); - writer.Write(Dy); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusStrokeFillPathRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusStrokeFillPathRecord.cs deleted file mode 100644 index cde898fc..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusStrokeFillPathRecord.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - internal class EmfPlusStrokeFillPathRecord : Record - { - public uint PathId; - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 4) - { - PathId = reader.ReadUInt32(); - var remaining = (int)Header.DataSize - 4; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(PathId); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusTranslateWorldTransformRecord.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusTranslateWorldTransformRecord.cs deleted file mode 100644 index adade81c..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/EmfPlusTranslateWorldTransformRecord.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal class EmfPlusTranslateWorldTransformRecord : Record - { - public float Dx; - public float Dy; - - public EmfPlusMatrixOrder MatrixOrder => (EmfPlusMatrixOrder)(Header.Flags & 0x0001); - - public override void Read(BinaryReader reader) - { - if (Header.DataSize >= 8) - { - Dx = reader.ReadSingle(); - Dy = reader.ReadSingle(); - int remaining = (int)Header.DataSize - 8; - if (remaining > 0) - { - Data = reader.ReadBytes(remaining); - } - } - else - { - base.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Dx); - writer.Write(Dy); - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/Record.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/Record.cs deleted file mode 100644 index a42137d6..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/Record.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System; - using System.IO; - - internal class Record - { - public RecordHeader Header { get; set; } - - public byte[] Data { get; set; } = Array.Empty(); - - public override string ToString() - { - return string.Format("{0} {1}", Header.Type.ToString(), Header.Size); - } - - public virtual void Read(BinaryReader reader) - { - Data = reader.ReadBytes(Convert.ToInt32(Header.DataSize)); - } - - public virtual void Write(BinaryWriter writer) - { - writer.Write(Data); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/RecordHeader.cs b/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/RecordHeader.cs deleted file mode 100644 index 605cf36c..00000000 --- a/src/MiniPdf/Drawing/Metafile/EmfPlus/Records/RecordHeader.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.EmfPlus.Records -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.EmfPlus.Enumerations; - - internal struct RecordHeader - { - - public RecordType Type; - - public ushort Flags; - - public uint Size; - - public uint DataSize; - - public void Read(BinaryReader reader) - { - this.Type = (RecordType)reader.ReadUInt16(); - this.Flags = reader.ReadUInt16(); - this.Size = reader.ReadUInt32(); - this.DataSize = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write((ushort)this.Type); - writer.Write(this.Flags); - writer.Write(this.Size); - writer.Write(this.DataSize); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/MetafileDocument.cs b/src/MiniPdf/Drawing/Metafile/MetafileDocument.cs deleted file mode 100644 index d58cdf4a..00000000 --- a/src/MiniPdf/Drawing/Metafile/MetafileDocument.cs +++ /dev/null @@ -1,56 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf.Records; -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Metafile -{ - /// - /// Represents a metafile document containing WMF, EMF, and EMF+ records. - /// - public class MetafileDocument - { - /// - /// Gets or sets the metafile format. - /// - public MetafileFormat Format { get; set; } - - /// - /// Gets or sets the WMF header. - /// - internal MetaHeader? WmfHeader { get; set; } - - /// - /// Gets or sets the WMF records. - /// - internal IReadOnlyList WmfRecords { get; set; } = new List(); - - /// - /// Gets or sets the EMF records. - /// - internal IReadOnlyList EmfRecords { get; set; } = new List(); - - /// - /// Gets or sets the EMF+ data size. - /// - public uint EmfPlusDataSize { get; set; } - - /// - /// Gets or sets the EMF+ comment identifier. - /// - public uint EmfPlusCommentIdentifier { get; set; } - - /// - /// Gets or sets the EMF+ records. - /// - internal IReadOnlyList EmfPlusRecords { get; set; } = new List(); - - /// - /// Gets or sets the embedded EMF+ records. - /// - internal IReadOnlyList> EmbeddedEmfPlusRecords { get; set; } = new List>(); - - /// - /// Gets or sets the placeable header. - /// - internal META_PLACEABLE? PlaceableHeader { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/MetafileFormat.cs b/src/MiniPdf/Drawing/Metafile/MetafileFormat.cs deleted file mode 100644 index 7ec75dbe..00000000 --- a/src/MiniPdf/Drawing/Metafile/MetafileFormat.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile -{ - /// - /// Specifies the format of a metafile. - /// - public enum MetafileFormat - { - /// - /// Unknown metafile format. - /// - Unknown, - - /// - /// Windows Metafile (WMF) format. - /// - Wmf, - - /// - /// Enhanced Metafile (EMF) format. - /// - Emf, - - /// - /// Enhanced Metafile Plus (EMF+) format. - /// - EmfPlus, - } -} diff --git a/src/MiniPdf/Drawing/Metafile/MetafileReader.cs b/src/MiniPdf/Drawing/Metafile/MetafileReader.cs deleted file mode 100644 index 50df55d7..00000000 --- a/src/MiniPdf/Drawing/Metafile/MetafileReader.cs +++ /dev/null @@ -1,368 +0,0 @@ -using MiniSoftware.Drawing.Metafile.EmfPlus; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Records; - -namespace MiniSoftware.Drawing.Metafile -{ - using MiniSoftware.Drawing.Metafile.Emf; - using System; - using System.Collections.Generic; - using System.IO; - - /// - /// Reads metafile formats (WMF, EMF, EMF+) from streams, byte arrays, or files. - /// - public class MetafileReader - { - private const uint WmfPlaceableKey = 0x9AC6CDD7; - - private const uint EmfSignature = 0x464D4520; - - private const uint EmfPlusCommentIdentifier = 0x2B464D45; - - /// - /// Reads a metafile from the specified stream. - /// - /// The stream containing metafile data. - /// The read from the stream. - /// Thrown when is null. - /// Thrown when the stream does not support seeking. - /// Thrown when the metafile format is unsupported or unknown. - public MetafileDocument Read(Stream stream) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanSeek) - { - throw new InvalidOperationException("The input stream must support seeking."); - } - - stream.Position = 0; - var format = DetectFormat(stream); - stream.Position = 0; - - return format switch - { - MetafileFormat.Wmf => ReadWmf(stream), - MetafileFormat.Emf => ReadEmf(stream), - MetafileFormat.EmfPlus => ReadEmfPlus(stream), - _ => throw new InvalidDataException("Unsupported or unknown metafile format."), - }; - } - - /// - /// Reads a metafile from the specified byte array. - /// - /// The byte array containing metafile data. - /// The read from the byte array. - public MetafileDocument Read(byte[] data) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var stream = new MemoryStream(data, writable: false); - return Read(stream); - } - - /// - /// Reads a metafile from the specified file path. - /// - /// The path to the metafile. - /// The read from the file. - public MetafileDocument Read(string filePath) - { - if (string.IsNullOrWhiteSpace(filePath)) - { - throw new ArgumentException("The file path cannot be null or whitespace.", nameof(filePath)); - } - - using var stream = File.OpenRead(filePath); - return Read(stream); - } - - /// - /// Attempts to read a metafile from the specified stream. - /// - /// The stream containing metafile data. - /// The resulting , or null if reading failed. - /// true if the metafile was read successfully; otherwise, false. - public bool TryRead(Stream stream, out MetafileDocument? document) - { - try - { - document = Read(stream); - return true; - } - catch (InvalidDataException) - { - document = null; - return false; - } - } - - /// - /// Detects the format of a metafile from the specified stream. - /// - /// The stream containing metafile data. - /// The detected . - public MetafileFormat DetectFormat(Stream stream) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanSeek) - { - throw new InvalidOperationException("The input stream must support seeking."); - } - - long originalPosition = stream.Position; - try - { - if (LooksLikePlaceableWmf(stream)) - { - return MetafileFormat.Wmf; - } - - if (LooksLikeEmf(stream)) - { - return MetafileFormat.Emf; - } - - if (LooksLikeStandardWmf(stream)) - { - return MetafileFormat.Wmf; - } - - if (LooksLikeEmfPlus(stream)) - { - return MetafileFormat.EmfPlus; - } - - return MetafileFormat.Unknown; - } - finally - { - stream.Position = originalPosition; - } - } - - /// - /// Detects the format of a metafile from the specified byte array. - /// - /// The byte array containing metafile data. - /// The detected . - public MetafileFormat DetectFormat(byte[] data) - { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - - using var stream = new MemoryStream(data, writable: false); - return DetectFormat(stream); - } - - private static MetafileDocument ReadWmf(Stream stream) - { - META_PLACEABLE? placeableHeader = null; - - if (LooksLikePlaceableWmf(stream)) - { - using var reader = new BinaryReader(stream, System.Text.Encoding.Default, leaveOpen: true); - placeableHeader = new META_PLACEABLE(); - placeableHeader.Read(reader); - } - - var wmfReader = new WmfReader(); - wmfReader.Read(stream); - - return new MetafileDocument - { - Format = MetafileFormat.Wmf, - WmfHeader = wmfReader.Header, - WmfRecords = wmfReader.Records, - PlaceableHeader = placeableHeader, - }; - } - - private static MetafileDocument ReadEmf(Stream stream) - { - var emfReader = new EmfReader(); - emfReader.Read(stream); - var embeddedEmfPlusRecords = ExtractEmbeddedEmfPlusRecords(emfReader); - - return new MetafileDocument - { - Format = MetafileFormat.Emf, - EmfRecords = emfReader.Records, - EmbeddedEmfPlusRecords = embeddedEmfPlusRecords, - }; - } - - private static MetafileDocument ReadEmfPlus(Stream stream) - { - var emfPlusReader = new EmfPlusReader(); - emfPlusReader.Read(stream); - - return new MetafileDocument - { - Format = MetafileFormat.EmfPlus, - EmfPlusDataSize = emfPlusReader.DataSize, - EmfPlusCommentIdentifier = emfPlusReader.CommentIdentifier, - EmfPlusRecords = emfPlusReader.Records, - }; - } - - private static bool LooksLikePlaceableWmf(Stream stream) - { - if (stream.Length < 22) - { - return false; - } - - long originalPosition = stream.Position; - try - { - stream.Position = 0; - using var reader = new BinaryReader(stream, System.Text.Encoding.Default, leaveOpen: true); - return reader.ReadUInt32() == WmfPlaceableKey; - } - finally - { - stream.Position = originalPosition; - } - } - - private static bool LooksLikeStandardWmf(Stream stream) - { - if (stream.Length < 18) - { - return false; - } - - long originalPosition = stream.Position; - try - { - stream.Position = 0; - using var reader = new BinaryReader(stream, System.Text.Encoding.Default, leaveOpen: true); - - var type = reader.ReadUInt16(); - var headerSize = reader.ReadUInt16(); - var version = reader.ReadUInt16(); - - return (type == 0x0001 || type == 0x0002) - && headerSize == 9 - && (version == 0x0100 || version == 0x0300); - } - finally - { - stream.Position = originalPosition; - } - } - - private static bool LooksLikeEmf(Stream stream) - { - if (stream.Length < 44) - { - return false; - } - - long originalPosition = stream.Position; - try - { - stream.Position = 0; - using var reader = new BinaryReader(stream, System.Text.Encoding.Default, leaveOpen: true); - - var type = reader.ReadUInt32(); - var size = reader.ReadUInt32(); - - if (type != (uint)Metafile.Emf.Enumerations.RecordType.EMR_HEADER || size < 80) - { - return false; - } - - stream.Position = 40; - var signature = reader.ReadUInt32(); - return signature == EmfSignature; - } - finally - { - stream.Position = originalPosition; - } - } - - private static bool LooksLikeEmfPlus(Stream stream) - { - if (stream.Length < 20) - { - return false; - } - - long originalPosition = stream.Position; - try - { - stream.Position = 0; - using var reader = new BinaryReader(stream, System.Text.Encoding.Default, leaveOpen: true); - - var dataSize = reader.ReadUInt32(); - var commentIdentifier = reader.ReadUInt32(); - - if (dataSize == 0 || commentIdentifier != EmfPlusCommentIdentifier) - { - return false; - } - - var recordType = reader.ReadUInt16(); - return recordType >= (ushort)Metafile.EmfPlus.Enumerations.RecordType.EmfPlusHeader - && recordType <= (ushort)Metafile.EmfPlus.Enumerations.RecordType.EmfPlusSetTSClip; - } - finally - { - stream.Position = originalPosition; - } - } - - private static IReadOnlyList> ExtractEmbeddedEmfPlusRecords(EmfReader emfReader) - { - var embeddedRecords = new List>(); - - foreach (var record in emfReader.Records) - { - if (record is not Metafile.Emf.Records.StateRecordTypes.EMR_COMMENT commentRecord) - { - continue; - } - - using var commentStream = new MemoryStream(commentRecord.CommentData, writable: false); - if (!LooksLikeEmfPlus(commentStream)) - { - continue; - } - - commentStream.Position = 0; - - try - { - var emfPlusReader = new EmfPlusReader(); - emfPlusReader.Read(commentStream); - embeddedRecords.Add(emfPlusReader.Records); - } - catch (IOException) - { - } - catch (ArgumentException) - { - } - } - - return embeddedRecords; - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/MetafileWriter.cs b/src/MiniPdf/Drawing/Metafile/MetafileWriter.cs deleted file mode 100644 index 9ac48099..00000000 --- a/src/MiniPdf/Drawing/Metafile/MetafileWriter.cs +++ /dev/null @@ -1,272 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Records; - -namespace MiniSoftware.Drawing.Metafile -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System; - using System.Collections.Generic; - using System.IO; - - /// - /// Writes metafile documents to streams or files in WMF, EMF, or EMF+ format. - /// - public class MetafileWriter - { - private const uint DefaultEmfPlusCommentIdentifier = 0x2B464D45; - - /// - /// Writes the specified metafile document to the specified stream. - /// - /// The metafile document to write. - /// The stream to write to. - /// Thrown when or is null. - /// Thrown when the stream does not support writing. - /// Thrown when the metafile format is unsupported. - public void Write(MetafileDocument document, Stream stream) - { - if (document == null) - { - throw new ArgumentNullException(nameof(document)); - } - - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (!stream.CanWrite) - { - throw new InvalidOperationException("The output stream must support writing."); - } - - stream.SetLength(0); - stream.Position = 0; - - switch (document.Format) - { - case MetafileFormat.Wmf: - WriteWmf(document, stream); - break; - case MetafileFormat.Emf: - WriteEmf(document, stream); - break; - case MetafileFormat.EmfPlus: - WriteEmfPlus(document, stream); - break; - default: - throw new InvalidDataException("Unsupported or unknown metafile format."); - } - } - - /// - /// Writes the specified metafile document to the specified file path. - /// - /// The metafile document to write. - /// The path to write the metafile to. - public void Write(MetafileDocument document, string filePath) - { - if (string.IsNullOrWhiteSpace(filePath)) - { - throw new ArgumentException("The file path cannot be null or whitespace.", nameof(filePath)); - } - - using var stream = File.Create(filePath); - Write(document, stream); - } - - /// - /// Writes the specified metafile document to a byte array. - /// - /// The metafile document to write. - /// A byte array containing the metafile data. - public byte[] WriteToBytes(MetafileDocument document) - { - using var stream = new MemoryStream(); - Write(document, stream); - return stream.ToArray(); - } - - private static void WriteWmf(MetafileDocument document, Stream stream) - { - using var writer = new BinaryWriter(stream, System.Text.Encoding.Default, leaveOpen: true); - - if (document.PlaceableHeader != null) - { - document.PlaceableHeader.Write(writer); - } - - var header = document.WmfHeader ?? CreateDefaultWmfHeader(document.WmfRecords); - header.Write(writer); - - foreach (var record in document.WmfRecords) - { - WriteWmfRecord(writer, record); - } - } - - private static void WriteEmf(MetafileDocument document, Stream stream) - { - using var writer = new BinaryWriter(stream, System.Text.Encoding.Default, leaveOpen: true); - - foreach (var record in document.EmfRecords) - { - var payload = SerializeEmfPayload(record); - var header = record.Header; - - if (header.Size == 0) - { - header.Size = checked((uint)(payload.Length + 8)); - } - - header.Write(writer); - writer.Write(payload); - - long expectedEndPosition = writer.BaseStream.Position - payload.Length + header.Size - 8; - writer.BaseStream.Position = expectedEndPosition; - } - } - - private static void WriteEmfPlus(MetafileDocument document, Stream stream) - { - using var writer = new BinaryWriter(stream, System.Text.Encoding.Default, leaveOpen: true); - - var dataSize = document.EmfPlusDataSize; - if (dataSize == 0) - { - dataSize = ComputeEmfPlusDataSize(document.EmfPlusRecords); - } - - var commentIdentifier = document.EmfPlusCommentIdentifier == 0 - ? DefaultEmfPlusCommentIdentifier - : document.EmfPlusCommentIdentifier; - - writer.Write(dataSize); - writer.Write(commentIdentifier); - - foreach (var record in document.EmfPlusRecords) - { - var payload = SerializeEmfPlusPayload(record); - var header = record.Header; - - if (header.DataSize == 0) - { - header.DataSize = checked((uint)payload.Length); - } - - if (header.Size == 0) - { - header.Size = checked(header.DataSize + 12); - } - - header.Write(writer); - writer.Write(payload); - } - } - - private static void WriteWmfRecord(BinaryWriter writer, Record record) - { - var payload = SerializeWmfPayload(record); - var paddedPayloadLength = payload.Length % 2 == 0 ? payload.Length : payload.Length + 1; - - var header = record.Header; - if (header.RecordSize == 0) - { - header.RecordSize = checked((uint)((6 + paddedPayloadLength) / 2)); - } - - header.Write(writer); - writer.Write(payload); - - if (paddedPayloadLength != payload.Length) - { - writer.Write((byte)0); - } - } - - private static MetaHeader CreateDefaultWmfHeader(IReadOnlyList records) - { - uint maxRecord = 0; - ulong totalWords = 9; - - foreach (var record in records) - { - uint recordSize = GetWmfRecordSizeWords(record); - totalWords += recordSize; - if (recordSize > maxRecord) - { - maxRecord = recordSize; - } - } - - var sizeLow = (ushort)(totalWords & 0xFFFF); - var sizeHigh = (ushort)((totalWords >> 16) & 0xFFFF); - - return new MetaHeader - { - Type = MetafileType.DISKMETAFILE, - HeaderSize = 9, - Version = MetafileVersion.METAVERSION300, - SizeLow = sizeLow, - SizeHigh = sizeHigh, - NumberOfObjects = 0, - MaxRecord = maxRecord, - NumberOfMembers = 0, - }; - } - - private static uint GetWmfRecordSizeWords(Record record) - { - if (record.Header.RecordSize > 0) - { - return record.Header.RecordSize; - } - - var payload = SerializeWmfPayload(record); - var paddedPayloadLength = payload.Length % 2 == 0 ? payload.Length : payload.Length + 1; - return checked((uint)((6 + paddedPayloadLength) / 2)); - } - - private static uint ComputeEmfPlusDataSize(IReadOnlyList records) - { - uint total = 0; - foreach (var record in records) - { - if (record.Header.Size > 0) - { - total = checked(total + record.Header.Size); - continue; - } - - var payload = SerializeEmfPlusPayload(record); - total = checked(total + (uint)(payload.Length + 12)); - } - - return total; - } - - private static byte[] SerializeWmfPayload(Record record) - { - using var ms = new MemoryStream(); - using var writer = new BinaryWriter(ms); - record.Write(writer); - return ms.ToArray(); - } - - private static byte[] SerializeEmfPayload(Metafile.Emf.Records.Record record) - { - using var ms = new MemoryStream(); - using var writer = new BinaryWriter(ms); - record.Write(writer); - return ms.ToArray(); - } - - private static byte[] SerializeEmfPlusPayload(Metafile.EmfPlus.Records.Record record) - { - using var ms = new MemoryStream(); - using var writer = new BinaryWriter(ms); - record.Write(writer); - return ms.ToArray(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BinaryRasterOperation.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BinaryRasterOperation.cs deleted file mode 100644 index 936d4078..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BinaryRasterOperation.cs +++ /dev/null @@ -1,88 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Lists the binary raster-operation codes. Raster-operation codes define how metafile processing combines the bits from the selected pen with the bits in the destination bitmap. - /// - internal enum BinaryRasterOperation - { - /// - /// 0, Pixel is always 0. - /// - R2_BLACK = 0x0001, - - /// - /// DPon, Pixel is the inverse of the R2_MERGEPEN color. - /// - R2_NOTMERGEPEN = 0x0002, - - /// - /// DPna, Pixel is a combination of the screen color and the inverse of the pen color. - /// - R2_MASKNOTPEN = 0x0003, - - /// - /// Pn, Pixel is the inverse of the pen color. - /// - R2_NOTCOPYPEN = 0x0004, - - /// - /// PDna, Pixel is a combination of the colors common to both the pen and the inverse of the screen. - /// - R2_MASKPENNOT = 0x0005, - - /// - /// Dn, Pixel is the inverse of the screen color. - /// - R2_NOT = 0x0006, - - /// - /// DPx, Pixel is a combination of the colors in the pen or in the screen, but not in both. - /// - R2_XORPEN = 0x0007, - - /// - /// DPan, Pixel is the inverse of the R2_MASKPEN color. - /// - R2_NOTMASKPEN = 0x0008, - - /// - /// DPa, Pixel is a combination of the colors common to both the pen and the screen. - /// - R2_MASKPEN = 0x0009, - - /// - /// DPxn, Pixel is the inverse of the R2_XORPEN color. - /// - R2_NOTXORPEN = 0x000A, - - /// - /// D, Pixel remains unchanged. - /// - R2_NOP = 0x000B, - - /// - /// PDno, Pixel is a combination of the pen color and the inverse of the screen color. - /// - R2_MERGENOTPEN = 0x000C, - - /// - /// P, Pixel is the pen color. - /// - R2_COPYPEN = 0x000D, - - /// - /// PDno, Pixel is a combination of the pen color and the inverse of the screen color. - /// - R2_MERGEPENNOT = 0x000E, - - /// - /// DPo, Pixel is a combination of the pen color and the screen color. - /// - R2_MERGEPEN = 0x000F, - - /// - /// 1, Pixel is always 1 - /// - R2_WHITE = 0x0010 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BitCount.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BitCount.cs deleted file mode 100644 index bde97a1b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BitCount.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the number of bits that define each pixel and the maximum number of colors in a device-independent bitmap (DIB). - /// - /// - /// 2.1.1.3 BitCount Enumeration - /// - internal enum BitCount - { - /// - /// The number of bits per pixel is undefined. - /// - BI_BITCOUNT_0 = 0x0000, - - /// - /// The image is specified with two colors. - /// - BI_BITCOUNT_1 = 0x0001, - BI_BITCOUNT_2 = 0x0004, - BI_BITCOUNT_3 = 0x0008, - BI_BITCOUNT_4 = 0x0010, - BI_BITCOUNT_5 = 0x0018, - - /// - /// The bitmap has a maximum of 2^24 colors. - /// - BI_BITCOUNT_6 = 0x0020 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BrushStyle.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BrushStyle.cs deleted file mode 100644 index bc10d285..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/BrushStyle.cs +++ /dev/null @@ -1,58 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the different possible brush types that can be used in graphics operations. - /// - internal enum BrushStyle : ushort - { - /// - /// A brush that paints a single, constant color, either solid or dithered. - /// - BS_SOLID = 0x0000, - - /// - /// A brush that does nothing. Using a BS_NULL brush in a graphics operation MUST have the same effect as using no brush at all. - /// - BS_NULL = 0x0001, - - /// - /// A brush that paints a predefined simple pattern, or "hatch", onto a solid background. - /// - BS_HATCHED = 0x0002, - - /// - /// A brush that paints a pattern defined by a bitmap, which MAY be a Bitmap16 Object or a DeviceIndependentBitmap (DIB) Object. - /// - BS_PATTERN = 0x0003, - - /// - /// Not supported. - /// - BS_INDEXED = 0x0004, - - /// - /// A pattern brush specified by a DIB. - /// - BS_DIBPATTERN = 0x0005, - - /// - /// A pattern brush specified by a DIB. - /// - BS_DIBPATTERNPT = 0x0006, - - /// - /// Not supported. - /// - BS_PATTERN8X8 = 0x0007, - - /// - /// Not supported. - /// - BS_DIBPATTERN8X8 = 0x0008, - - /// - /// Not supported. - /// - BS_MONOPATTERN = 0x0009 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/CharacterSet.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/CharacterSet.cs deleted file mode 100644 index 839343c3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/CharacterSet.cs +++ /dev/null @@ -1,54 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines the possible sets of character glyphs that are defined in fonts for graphics output. - /// - /// - /// 2.1.1.5 CharacterSet Enumeration - /// - internal enum CharacterSet - { - /// - /// Specifies the English character set. - /// - ANSI_CHARSET = 0x00000000, - - /// - /// Specifies a character set based on the current system locale; for example, when the system locale is United States English, the default character set is ANSI_CHARSET. - /// - DEFAULT_CHARSET = 0x00000001, - - /// - /// Specifies a character set of symbols. - /// - SYMBOL_CHARSET = 0x00000002, - - /// - /// Specifies the Apple Macintosh character set. - /// - MAC_CHARSET = 0x0000004D, - - /// - /// Specifies the Japanese character set. - /// - SHIFTJIS_CHARSET = 0x00000080, - - /// - /// Specifies the Hangul Korean character set. - /// - HANGUL_CHARSET = 0x00000081, - JOHAB_CHARSET = 0x00000082, - GB2312_CHARSET = 0x00000086, - CHINESEBIG5_CHARSET = 0x00000088, - GREEK_CHARSET = 0x000000A1, - TURKISH_CHARSET = 0x000000A2, - VIETNAMESE_CHARSET = 0x000000A3, - HEBREW_CHARSET = 0x000000B1, - ARABIC_CHARSET = 0x000000B2, - BALTIC_CHARSET = 0x000000BA, - RUSSIAN_CHARSET = 0x000000CC, - THAI_CHARSET = 0x000000DE, - EASTEUROPE_CHARSET = 0x000000EE, - OEM_CHARSET = 0x000000FF - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/ColorUsage.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/ColorUsage.cs deleted file mode 100644 index 9f09cf79..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/ColorUsage.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies whether a color table exists in a device-independent bitmap (DIB) and how to interpret its values. - /// - internal enum ColorUsage - { - /// - /// The color table contains RGB values specified by RGBQuad Objects (section 2.2.2.20). - /// - DIB_RGB_COLORS = 0x0000, - - /// - /// The color table contains 16-bit indices into the current logical palette in the playback device context. - /// - DIB_PAL_COLORS = 0x0001, - - /// - /// No color table exists. The pixels in the DIB are indices into the current logical palette in the playback device context. - /// - DIB_PAL_INDICES = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Compression.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Compression.cs deleted file mode 100644 index ac8f0754..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Compression.cs +++ /dev/null @@ -1,62 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the type of compression for a bitmap image. - /// - /// - /// 2.1.1.7 Compression Enumeration - /// - internal enum Compression - { - /// - /// The bitmap is in uncompressed red green blue (RGB) format that is not compressed and does not use color masks. - /// - BI_RGB = 0x0000, - - /// - /// An RGB format that uses run-length encoding (RLE) compression for bitmaps with 8 bits per pixel. - /// The compression uses a 2-byte format consisting of a count byte followed by a byte containing a color index. - /// - BI_RLE8 = 0x0001, - - /// - /// An RGB format that uses RLE compression for bitmaps with 4 bits per pixel. - /// The compression uses a 2-byte format consisting of a count byte followed by two word-length color indexes. - /// - BI_RLE4 = 0x0002, - - /// - /// The bitmap is not compressed and the color table consists of three DWORD color masks that specify the red, green, and blue components, respectively, of each pixel. - /// This is valid when used with 16 and 32-bits per pixel bitmaps. - /// - BI_BITFIELDS = 0x0003, - - /// - /// The image is a JPEG image, as specified in [JFIF]. This value SHOULD only be used in certain bitmap operations, such as JPEG pass-through. The application MUST query for the pass-through support, since not all devices support JPEG pass-through. Using non-RGB bitmaps MAY limit the portability of the metafile to other devices. - /// For instance, display device contexts generally do not support this pass-through. - /// - BI_JPEG = 0x0004, - - /// - /// The image is a PNG image, as specified in [RFC2083]. This value SHOULD only be used certain bitmap operations, such as JPEG/PNG pass-through. The application MUST query for the pass-through support, because not all devices support JPEG/PNG pass-through. Using non-RGB bitmaps MAY limit the portability of the metafile to other devices. - /// For instance, display device contexts generally do not support this pass-through. - /// - BI_PNG = 0x0005, - - /// - /// The image is an uncompressed CMYK format. - /// - BI_CMYK = 0x000B, - - /// - /// A CMYK format that uses RLE compression for bitmaps with 8 bits per pixel. - /// The compression uses a 2-byte format consisting of a count byte followed by a byte containing a color index. - /// - BI_CMYKRLE8 = 0x000C, - - /// - /// A CMYK format that uses RLE compression for bitmaps with 4 bits per pixel. The compression uses a 2-byte format consisting of a count byte followed by two word-length color indexes. - /// - BI_CMYKRLE4 = 0x000D - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FamilyFont.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FamilyFont.cs deleted file mode 100644 index ec87f493..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FamilyFont.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the font family. Font families describe the look of a font in a general way. - /// They are intended for specifying fonts when the exact typeface desired is not available. - /// - /// - /// 2.1.1.8 FamilyFont Enumeration - /// - internal enum FamilyFont - { - /// - /// The default font is specified, which is implementation-dependent. - /// - FF_DONTCARE = 0x00, - - /// - /// Fonts with variable stroke widths, which are proportional to the actual widths of the glyphs, and which have serifs. "MS Serif" is an example. - /// - FF_ROMAN = 0x01, - - /// - /// Fonts with variable stroke widths, which are proportional to the actual widths of the glyphs, and which do not have serifs. "MS Sans Serif" is an example. - /// - FF_SWISS = 0x02, - - /// - /// Fonts with constant stroke width, with or without serifs. Fixed-width fonts are usually modern. "Pica", "Elite", and "Courier New" are examples. - /// - FF_MODERN = 0x03, - - /// - /// Fonts designed to look like handwriting. "Script" and "Cursive" are examples. - /// - FF_SCRIPT = 0x04, - - /// - /// Novelty fonts. "Old English" is an example. - /// - FF_DECORATIVE = 0x05 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FloodFill.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FloodFill.cs deleted file mode 100644 index 3ddbe3a5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FloodFill.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the type of fill operation to be performed. - /// - /// - /// 2.1.1.9 FloodFill Enumeration - /// - internal enum FloodFill - { - /// - /// The fill area is bounded by the color specified by the Color member. - /// This style is identical to the filling performed by the META_FLOODFILL record. - /// - FLOODFILLBORDER = 0x0000, - - /// - /// The fill area is bounded by the color that is specified by the Color member. Filling continues outward in all directions as long as the color is encountered. This style is useful for filling areas with multicolored boundaries. - /// - FLOODFILLSURFACE = 0x0001 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FontQuality.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FontQuality.cs deleted file mode 100644 index 3dc190cb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/FontQuality.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies how closely the attributes of the logical font should match those of the physical font when rendering text. - /// - /// - /// 2.1.1.10 FontQuality Enumeration - /// - internal enum FontQuality - { - /// - /// Specifies that the character quality of the font does not matter, so DRAFT_QUALITY can be used. - /// - DEFAULT_QUALITY = 0x00, - - /// - /// Specifies that the character quality of the font is less important than the matching of logical attribuetes. - /// For rasterized fonts, scaling SHOULD be enabled, which means that more font sizes are available. - /// - DRAFT_QUALITY = 0x01, - - /// - /// Specifies that the character quality of the font is more important than the matching of logical attributes. - /// For rasterized fonts, scaling SHOULD be disabled, and the font closest in size SHOULD be chosen. - /// - PROOF_QUALITY = 0x02, - - /// - /// Specifies that anti-aliasing SHOULD NOT be used when rendering text. - /// - NONANTIALIASED_QUALITY = 0x03, - - /// - /// Specifies that anti-aliasing SHOULD be used when rendering text, if the font supports it. - /// - ANTIALIASED_QUALITY = 0x04, - - /// - /// Specifies that ClearType anti-aliasing SHOULD be used when rendering text, if the font supports it. - /// - CLEARTYPE_QUALITY = 0x05 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/GamutMappingIntent.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/GamutMappingIntent.cs deleted file mode 100644 index 067194a4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/GamutMappingIntent.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// The GamutMappingIntent Enumeration specifies the relationship between logical and physical colors. - /// - /// - /// 2.1.1.11 GamutMappingIntent Enumeration - /// - internal enum GamutMappingIntent - { - /// - /// Specifies that the white point SHOULD be maintained. Typically used when logical colors MUST be matched to their nearest physical color in the destination color gamut. - /// - LCS_GM_ABS_COLORIMETRIC = 0x00000008, - - /// - /// Specifies that saturation SHOULD be maintained. Typically used for business charts and other situations in which dithering is not required. - /// - LCS_GM_BUSINESS = 0x00000001, - - /// - /// Specifies that a colorimetric match SHOULD be maintained. Typically used for graphic designs and named colors. - /// - LCS_GM_GRAPHICS = 0x00000002, - - /// - /// Specifies that contrast SHOULD be maintained. Typically used for photographs and natural images. - /// - LCS_GM_IMAGES = 0x00000004 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/HatchStyle.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/HatchStyle.cs deleted file mode 100644 index 7da48f0d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/HatchStyle.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the hatch pattern. - /// - /// - /// 2.1.1.12 HatchStyle Enumeration - /// - internal enum HatchStyle - { - /// - /// A horizontal hatch. - /// - HS_HORIZONTAL = 0x0000, - - /// - /// A vertical hatch. - /// - HS_VERTICAL = 0x0001, - - /// - /// A 45-degree downward, left-to-right hatch. - /// - HS_FDIAGONAL = 0x0002, - - /// - /// A 45-degree upward, left-to-right hatch. - /// - HS_BDIAGONAL = 0x0003, - - /// - /// A horizontal and vertical cross-hatch. - /// - HS_CROSS = 0x0004, - - /// - /// A 45-degree crosshatch. - /// - HS_DIAGCROSS = 0x0005 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Layout.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Layout.cs deleted file mode 100644 index d3d55667..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/Layout.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines options for controlling the direction in which text and graphics are drawn. - /// - /// - /// 2.1.1.13 Layout Enumeration - /// - internal enum Layout - { - /// - /// Sets the default horizontal layout to be left-to-right. - /// - LAYOUT_LTR = 0x0000, - - /// - /// Sets the default horizontal layout to be right-to-left. Switching to this layout SHOULD cause the mapping mode in the playback device context to become MM_ISOTROPIC (section 2.1.1.16). - /// - LAYOUT_RTL = 0x0001, - - /// - /// Disables mirroring of bitmaps that are drawn by META_BITBLT and META_STRETCHBLT operations, when the layout is right-to-left. - /// - LAYOUT_BITMAPORIENTATIONPRESERVED = 0x0008 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpace.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpace.cs deleted file mode 100644 index fad456c7..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpace.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the type of color space. - /// - /// - /// 2.1.1.14 LogicalColorSpace Enumeration - /// - internal enum LogicalColorSpace - { - /// - /// Color values are calibrated red green blue (RGB) values. - /// - LCS_CALIBRATED_RGB = 0x00000000, - - /// - /// The value is an encoding of the ASCII characters "sRGB", and it indicates that the color values are sRGB values. - /// - LCS_sRGB = 0x73524742, - - /// - /// The value is an encoding of the ASCII characters "Win ", including the trailing space, and it indicates that the color values are Windows default color space values. - /// - LCS_WINDOWS_COLOR_SPACE = 0x57696E20 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpaceV5.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpaceV5.cs deleted file mode 100644 index cc14330a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/LogicalColorSpaceV5.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Used to specify where to find color profile information for a DeviceIndependentBitmap (DIB) Object (section 2.2.2.9) that has a header of type BitmapV5Header Object (section 2.2.2.5). - /// - /// - /// 2.1.1.15 LogicalColorSpaceV5 Enumeration - /// - internal enum LogicalColorSpaceV5 - { - /// - /// The value consists of the string "LINK" from the Windows character set (code page 1252). - /// It indicates that the color profile MUST be linked with the DIB Object. - /// - LCS_PROFILE_LINKED = 0x4C494E4B, - - /// - /// The value consists of the string "MBED" from the Windows character set (code page 1252). - /// It indicates that the color profile MUST be embedded in the DIB Object. - /// - LCS_PROFILE_EMBEDDED = 0x4D424544 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MapMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MapMode.cs deleted file mode 100644 index f1ea90e8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MapMode.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines how logical units are mapped to physical units; that is, assuming that the origins in both the logical and physical coordinate systems are at the same point on the drawing surface, what is the physical coordinate (x',y') that corresponds to logical coordinate (x,y). - /// - internal enum MapMode - { - /// - /// Each logical unit is mapped to one device pixel. Positive x is to the right; positive y is down. - /// - MM_TEXT = 0x0001, - - /// - /// Each logical unit is mapped to 0.1 millimeter. Positive x is to the right; positive y is up. - /// - MM_LOMETRIC = 0x0002, - - /// - /// Each logical unit is mapped to 0.01 millimeter. Positive x is to the right; positive y is up. - /// - MM_HIMETRIC = 0x0003, - - /// - /// Each logical unit is mapped to 0.01 inch. Positive x is to the right; positive y is up. - /// - MM_LOENGLISH = 0x0004, - - /// - /// Each logical unit is mapped to 0.001 inch. Positive x is to the right; positive y is up. - /// - MM_HIENGLISH = 0x0005, - - /// - /// Each logical unit is mapped to one twentieth (1/20) of a point. In printing, a point is 1/72 of an inch; therefore, 1/20 of a point is 1/1440 of an inch. This unit is also known as a "twip". - /// - MM_TWIPS = 0x0006, - - /// - /// Logical units are mapped to arbitrary device units with equally scaled axes; that is, one unit along the x-axis is equal to one unit along the y-axis. The META_SETWINDOWEXT and META_SETVIEWPORTEXT records specify the units and the orientation of the axes. - /// - MM_ISOTROPIC = 0x0007, - - /// - /// Logical units are mapped to arbitrary units with arbitrarily scaled axes. - /// - MM_ANISOTROPIC = 0x0008 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileEscapes.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileEscapes.cs deleted file mode 100644 index 62c97dcf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileEscapes.cs +++ /dev/null @@ -1,75 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies printer driver functionality that might not be directly accessible through WMF records defined in the RecordType Enumeration (section 2.1.1.1). - /// - /// - /// 2.1.1.17 MetafileEscapes Enumeration - /// - internal enum MetafileEscapes - { - /// - /// Notifies the printer driver that the application has finished writing to a page. - /// - NEWFRAME = 0x0001, - ABORTDOC = 0x0002, - NEXTBAND = 0x0003, - SETCOLORTABLE = 0x0004, - GETCOLORTABLE = 0x0005, - FLUSHOUT = 0x0006, - DRAFTMODE = 0x0007, - QUERYESCSUPPORT = 0x0008, - SETABORTPROC = 0x0009, - STARTDOC = 0x000A, - ENDDOC = 0x000B, - GETPHYSPAGESIZE = 0x000C, - GETPRINTINGOFFSET = 0x000D, - GETSCALINGFACTOR = 0x000E, - META_ESCAPE_ENHANCED_METAFILE = 0x000F, - SETPENWIDTH = 0x0010, - SETCOPYCOUNT = 0x0011, - SETPAPERSOURCE = 0x0012, - PASSTHROUGH = 0x0013, - GETTECHNOLOGY = 0x0014, - SETLINECAP = 0x0015, - SETLINEJOIN = 0x0016, - SETMITERLIMIT = 0x0017, - BANDINFO = 0x0018, - DRAWPATTERNRECT = 0x0019, - GETVECTORPENSIZE = 0x001A, - GETVECTORBRUSHSIZE = 0x001B, - ENABLEDUPLEX = 0x001C, - GETSETPAPERBINS = 0x001D, - GETSETPRINTORIENT = 0x001E, - ENUMPAPERBINS = 0x001F, - SETDIBSCALING = 0x0020, - EPSPRINTING = 0x0021, - ENUMPAPERMETRICS = 0x0022, - GETSETPAPERMETRICS = 0x0023, - POSTSCRIPT_DATA = 0x0025, - POSTSCRIPT_IGNORE = 0x0026, - GETDEVICEUNITS = 0x002A, - GETEXTENDEDTEXTMETRICS = 0x0100, - GETPAIRKERNTABLE = 0x0102, - EXTTEXTOUT = 0x0200, - GETFACENAME = 0x0201, - DOWNLOADFACE = 0x0202, - METAFILE_DRIVER = 0x0801, - QUERYDIBSUPPORT = 0x0C01, - BEGIN_PATH = 0x1000, - CLIP_TO_PATH = 0x1001, - END_PATH = 0x1002, - OPEN_CHANNEL = 0x100E, - DOWNLOADHEADER = 0x100F, - CLOSE_CHANNEL = 0x1010, - POSTSCRIPT_PASSTHROUGH = 0x1013, - ENCAPSULATED_POSTSCRIPT = 0x1014, - POSTSCRIPT_IDENTIFY = 0x1015, - POSTSCRIPT_INJECTION = 0x1016, - CHECKJPEGFORMAT = 0x1017, - CHECKPNGFORMAT = 0x1018, - GET_PS_FEATURESETTING = 0x1019, - MXDC_ESCAPE = 0x101A, - SPCLPASSTHROUGH2 = 0x11D8 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileType.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileType.cs deleted file mode 100644 index a6eaaec3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileType.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies where the metafile is stored. - /// - /// - /// 2.1.1.18 MetafileType Enumeration - /// - internal enum MetafileType - { - /// - /// Metafile is stored in memory. - /// - MEMORYMETAFILE = 0x0001, - - /// - /// Metafile is stored on disk. - /// - DISKMETAFILE = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileVersion.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileVersion.cs deleted file mode 100644 index 024d8dd5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MetafileVersion.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines values that specify support for device-independent bitmaps (DIBs) in metafiles. - /// - /// - /// 2.1.1.19 MetafileVersion Enumeration - /// - internal enum MetafileVersion - { - /// - /// DIBs are not supported. - /// - METAVERSION100 = 0x0100, - - /// - /// DIBs are supported. - /// - METAVERSION300 = 0x0300 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MixMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MixMode.cs deleted file mode 100644 index 6b92b68d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/MixMode.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the background mix mode for text, hatched brushes, and other nonsolid pen styles. - /// - /// - /// 2.1.1.20 MixMode Enumeration - /// - internal enum MixMode - { - /// - /// The background remains untouched. - /// - TRANSPARENT = 0x0001, - - /// - /// The background is filled with the background color that is currently defined in the playback device context before the text, hatched brush, or pen is drawn. - /// - OPAQUE = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/OutPrecision.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/OutPrecision.cs deleted file mode 100644 index c2a0f504..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/OutPrecision.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines values for output precision, which is the requirement for the font mapper to match specific font parameters, including height, width, character orientation, escapement, pitch, and font type. - /// - /// - /// 2.1.1.21 OutPrecision Enumeration - /// - internal enum OutPrecision - { - /// - /// A value that specifies default behavior. - /// - OUT_DEFAULT_PRECIS = 0x00000000, - - /// - /// A value that is returned when rasterized fonts are enumerated. - /// - OUT_STRING_PRECIS = 0x00000001, - - /// - /// A value that is returned when TrueType and other outline fonts, and vector fonts are enumerated. - /// - OUT_STROKE_PRECIS = 0x00000003, - - /// - /// A value that specifies the choice of a TrueType font when the system contains multiple fonts with the same name. - /// - OUT_TT_PRECIS = 0x00000004, - - /// - /// A value that specifies the choice of a device font when the system contains multiple fonts with the same name. - /// - OUT_DEVICE_PRECIS = 0x00000005, - - /// - /// A value that specifies the choice of a rasterized font when the system contains multiple fonts with the same name. - /// - OUT_RASTER_PRECIS = 0x00000006, - - /// - /// A value that specifies the requirement for only TrueType fonts. If there are no TrueType fonts installed in the system, default behavior is specified. - /// - OUT_TT_ONLY_PRECIS = 0x00000007, - - /// - /// A value that specifies the requirement for TrueType and other outline fonts. - /// - OUT_OUTLINE_PRECIS = 0x00000008, - - /// - /// A value that specifies a preference for TrueType and other outline fonts. - /// - OUT_SCREEN_OUTLINE_PRECIS = 0x00000009, - - /// - /// A value that specifies a requirement for only PostScript fonts. If there are no PostScript fonts installed in the system, default behavior is specified. - /// - OUT_PS_ONLY_PRECIS = 0x0000000A - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PaletteEntryFlag.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PaletteEntryFlag.cs deleted file mode 100644 index 157df5b5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PaletteEntryFlag.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies how the palette entry should be used. - /// - /// - /// 2.1.1.22 PaletteEntryFlag Enumeration - /// - internal enum PaletteEntryFlag - { - /// - /// Specifies that the logical palette entry be used for palette animation. This value prevents other windows from matching colors to the palette entry because the color frequently changes. If an unused system-palette entry is available, the color is placed in that entry. - /// Otherwise, the color is not available for animation. - /// - PC_RESERVED = 0x01, - - /// - /// Specifies that the low-order word of the logical palette entry designates a hardware palette index. - /// This value allows the application to show the contents of the display device palette. - /// - PC_EXPLICIT = 0x02, - - /// - /// Specifies that the color be placed in an unused entry in the system palette instead of being matched to an existing color in the system palette. - /// If there are no unused entries in the system palette, the color is matched normally. Once this color is in the system palette, colors in other logical palettes can be matched to this color. - /// - PC_NOCOLLAPSE = 0x04 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PenStyle.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PenStyle.cs deleted file mode 100644 index 41153c28..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PenStyle.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// The 16-bit PenStyle Enumeration is used to specify different types of pens that can be used in graphics operations. - /// - /// Various styles can be combined by using a logical OR statement, one from each subsection of Style, EndCap, Join, and Type (Cosmetic). - /// - /// - /// 2.1.1.23 PenStyle Enumeration - /// - internal enum PenStyle - { - PS_COSMETIC = 0x0000, - PS_ENDCAP_ROUND = 0x0000, - PS_JOIN_ROUND = 0x0000, - PS_SOLID = 0x0000, - PS_DASH = 0x0001, - PS_DOT = 0x0002, - PS_DASHDOT = 0x0003, - PS_DASHDOTDOT = 0x0004, - PS_NULL = 0x0005, - PS_INSIDEFRAME = 0x0006, - PS_USERSTYLE = 0x0007, - PS_ALTERNATE = 0x0008, - PS_ENDCAP_SQUARE = 0x0100, - PS_ENDCAP_FLAT = 0x0200, - PS_JOIN_BEVEL = 0x1000, - PS_JOIN_MITER = 0x2000 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PitchFont.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PitchFont.cs deleted file mode 100644 index 16ae8eaf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PitchFont.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines values that are used for specifying characteristics of a font. The values are used to indicate whether the characters in a font have a fixed or variable width, or pitch. - /// - /// - /// 2.1.1.24 PitchFont Enumeration - /// - internal enum PitchFont - { - /// - /// The default pitch, which is implementation-dependent. - /// - DEFAULT_PITCH = 0, - - /// - /// A fixed pitch, which means that all the characters in the font occupy the same width when output in a string. - /// - FIXED_PITCH = 1, - - /// - /// A variable pitch, which means that the characters in the font occupy widths that are proportional to the actual widths of the glyphs when output in a string. For example, the "i" and space characters usually have much smaller widths than a "W" or "O" character. - /// - VARIABLE_PITCH = 2 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PolyFillMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PolyFillMode.cs deleted file mode 100644 index f8d83734..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PolyFillMode.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the method used for filling a polygon. - /// - /// - /// 2.1.1.25 PolyFillMode Enumeration - /// - internal enum PolyFillMode - { - /// - /// Selects alternate mode (fills the area between odd-numbered and even-numbered polygon sides on each scan line). - /// - ALTERNATE = 0x0001, - - /// - /// Selects winding mode (fills any region with a nonzero winding value). - /// - WINDING = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptCap.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptCap.cs deleted file mode 100644 index fcd3148c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptCap.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines line-ending types for use with a PostScript printer driver. - /// - internal enum PostScriptCap - { - /// - /// Specifies that the line-ending style has not been set, and that a default style MAY <24> be used. - /// - PostScriptNotSet = -2, - - /// - /// Specifies that the line ends at the last point. The end is squared off. - /// - PostScriptFlatCap = 0, - - /// - /// Specifies a circular cap. The center of the circle is the last point in the line. The diameter of the circle is the same as the line width; that is, the thickness of the line. - /// - PostScriptRoundCap = 1, - - /// - /// Specifies a square cap. The center of the square is the last point in the line. - /// The height and width of the square are the same as the line width; that is, the thickness of the line. - /// - PostScriptSquareCap = 2 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptClipping.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptClipping.cs deleted file mode 100644 index 57794c5e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptClipping.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines functions that can be applied to the clipping path used for PostScript output. - /// - /// - /// 2.1.1.27 PostScriptClipping Enumeration - /// - internal enum PostScriptClipping - { - /// - /// Saves the current PostScript clipping path. - /// - CLIP_SAVE = 0x0000, - - /// - /// Restores the PostScript clipping path to the last clipping path that was saved by a previous CLIP_SAVE function applied by a CLIP_TO_PATH record (section 2.3.6.6). - /// - CLIP_RESTORE = 0x0001, - - /// - /// Intersects the current PostScript clipping path with the current clipping path and saves the result as the new PostScript clipping path. - /// - CLIP_INCLUSIVE = 0x0002 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptFeatureSetting.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptFeatureSetting.cs deleted file mode 100644 index caf3ed12..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptFeatureSetting.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines values that are used to retrieve information about specific features in a PostScript printer driver. - /// - internal enum PostScriptFeatureSetting - { - /// - /// Specifies the n-up printing (page layout) setting. - /// - FEATURESETTING_NUP = 0x00000000, - - /// - /// Specifies PostScript driver output options. - /// - FEATURESETTING_OUTPUT = 0x00000001, - - /// - /// Specifies the language level. - /// - FEATURESETTING_PSLEVEL = 0x00000002, - - /// - /// Specifies custom paper parameters. - /// - FEATURESETTING_CUSTPAPER = 0x00000003, - - /// - /// Specifies the mirrored output setting. - /// - FEATURESETTING_MIRROR = 0x00000004, - - /// - /// Specifies the negative output setting. - /// - FEATURESETTING_NEGATIVE = 0x00000005, - - /// - /// Specifies the output protocol setting. - /// - FEATURESETTING_PROTOCOL = 0x00000006, - - /// - /// Specifies the start of a range of values that a driver MAY use for retrieving data concerning proprietary features. - /// - FEATURESETTING_PRIVATE_BEGIN = 0x00001000, - - /// - /// Specifies the end of a range of values that a driver MAY use for retrieving data concerning proprietary features. - /// - FEATURESETTING_PRIVATE_END = 0x00001FFF - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptJoin.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptJoin.cs deleted file mode 100644 index 538bdff9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/PostScriptJoin.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines line-joining capabilities for use with a PostScript printer driver. - /// - internal enum PostScriptJoin - { - /// - /// Specifies that the line-joining style has not been set, and that a default style MAY <28> be used. - /// - PostScriptNotSet = -2, - - /// - /// Specifies a mitered join. This value MUST produce a sharp or clipped corner. - /// - PostScriptMiterJoin = 0, - - /// - /// Specifies a circular join. This value MUST produce a smooth, circular arc between the lines. - /// - PostScriptRoundJoin = 1, - - /// - /// Specifies a beveled join. This value MUST produce a diagonal corner. - /// - PostScriptBevelJoin = 2 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/RecordType.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/RecordType.cs deleted file mode 100644 index 8162b845..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/RecordType.cs +++ /dev/null @@ -1,102 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Defines the types of records that can be used in WMF metafiles. - /// - internal enum RecordType - { - /// - /// Specifies the end of the file, the last record in the metafile. - /// - META_EOF = 0x0000, - - /// - /// This record maps entries from the logical palette that is defined in the playback device context to the system palette. - /// - META_REALIZEPALETTE = 0x0035, - - /// - /// This record defines red green blue (RGB) color values in a range of entries in the logical palette that is defined in the playback device context. - /// - META_SETPALENTRIES = 0x0037, - - /// - /// This record defines the background raster operation mix mode in the playback device context. The background mix mode is the mode for combining pens, text, hatched brushes, and interiors of filled objects with background colors on the output surface. - /// - META_SETBKMODE = 0x0102, - - /// - /// This record defines the mapping mode in the playback device context. The mapping mode defines the unit of measure used to transform page-space coordinates into coordinates of the output device, and also defines the orientation of the device's x and y axes. - /// - META_SETMAPMODE = 0x0103, - - /// - /// This record defines the foreground raster operation mix mode in the playback device context. The foreground mix mode is the mode for combining pens and interiors of filled objects with foreground colors on the output surface. - /// - META_SETROP2 = 0x0104, - META_SETRELABS = 0x0105, - META_SETPOLYFILLMODE = 0x0106, - META_SETSTRETCHBLTMODE = 0x0107, - META_SETTEXTCHAREXTRA = 0x0108, - META_RESTOREDC = 0x0127, - META_RESIZEPALETTE = 0x0139, - META_DIBCREATEPATTERNBRUSH = 0x0142, - META_SETLAYOUT = 0x0149, - META_SETBKCOLOR = 0x0201, - META_SETTEXTCOLOR = 0x0209, - META_OFFSETVIEWPORTORG = 0x0211, - META_LINETO = 0x0213, - META_MOVETO = 0x0214, - META_OFFSETCLIPRGN = 0x0220, - META_FILLREGION = 0x0228, - META_SETMAPPERFLAGS = 0x0231, - META_SELECTPALETTE = 0x0234, - META_POLYGON = 0x0324, - META_POLYLINE = 0x0325, - META_SETTEXTJUSTIFICATION = 0x020A, - META_SETWINDOWORG = 0x020B, - META_SETWINDOWEXT = 0x020C, - META_SETVIEWPORTORG = 0x020D, - META_SETVIEWPORTEXT = 0x020E, - META_OFFSETWINDOWORG = 0x020F, - META_SCALEWINDOWEXT = 0x0410, - META_SCALEVIEWPORTEXT = 0x0412, - META_EXCLUDECLIPRECT = 0x0415, - META_INTERSECTCLIPRECT = 0x0416, - META_ELLIPSE = 0x0418, - META_FLOODFILL = 0x0419, - META_FRAMEREGION = 0x0429, - META_ANIMATEPALETTE = 0x0436, - META_TEXTOUT = 0x0521, - META_POLYPOLYGON = 0x0538, - META_EXTFLOODFILL = 0x0548, - META_RECTANGLE = 0x041B, - META_SETPIXEL = 0x041F, - META_ROUNDRECT = 0x061C, - META_PATBLT = 0x061D, - META_SAVEDC = 0x001E, - META_PIE = 0x081A, - META_STRETCHBLT = 0x0B23, - META_ESCAPE = 0x0626, - META_INVERTREGION = 0x012A, - META_PAINTREGION = 0x012B, - META_SELECTCLIPREGION = 0x012C, - META_SELECTOBJECT = 0x012D, - META_SETTEXTALIGN = 0x012E, - META_ARC = 0x0817, - META_CHORD = 0x0830, - META_BITBLT = 0x0922, - META_EXTTEXTOUT = 0x0a32, - META_SETDIBTODEV = 0x0d33, - META_DIBBITBLT = 0x0940, - META_DIBSTRETCHBLT = 0x0b41, - META_STRETCHDIB = 0x0f43, - META_DELETEOBJECT = 0x01f0, - META_CREATEPALETTE = 0x00f7, - META_CREATEPATTERNBRUSH = 0x01F9, - META_CREATEPENINDIRECT = 0x02FA, - META_CREATEFONTINDIRECT = 0x02FB, - META_CREATEBRUSHINDIRECT = 0x02FC, - META_CREATEREGION = 0x06FF - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/StretchMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/StretchMode.cs deleted file mode 100644 index fb0083ec..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/StretchMode.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - /// - /// Specifies the bitmap stretching mode, which defines how the system combines rows or columns of a bitmap with existing pixels. - /// - /// - /// 2.1.1.30 StretchMode Enumeration - /// - internal enum StretchMode - { - /// - /// Performs a Boolean AND operation by using the color values for the eliminated and existing pixels. - /// If the bitmap is a monochrome bitmap, this mode preserves black pixels at the expense of white pixels. - /// - BLACKONWHITE = 0x0001, - - /// - /// Performs a Boolean OR operation by using the color values for the eliminated and existing pixels. - /// If the bitmap is a monochrome bitmap, this mode preserves white pixels at the expense of black pixels. - /// - WHITEONBLACK = 0x0002, - - /// - /// Deletes the pixels. This mode deletes all eliminated lines of pixels without trying to preserve their information. - /// - COLORONCOLOR = 0x0003, - - /// - /// Maps pixels from the source rectangle into blocks of pixels in the destination rectangle. The average color over the destination block of pixels approximates the color of the source pixels. - /// - HALFTONE = 0x0004 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/TernaryRasterOperation.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/TernaryRasterOperation.cs deleted file mode 100644 index e6cfd8cc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Enumerations/TernaryRasterOperation.cs +++ /dev/null @@ -1,269 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Enumerations -{ - - /// - /// Specifies ternary raster operation codes, which define how to combine the bits in a source bitmap with the bits in a destination bitmap. - /// - /// - /// 2.1.1.31 TernaryRasterOperation Enumeration - /// - internal enum TernaryRasterOperation - { - BLACKNESS = 0x00, - DPSOON = 0x01, - DPSONA = 0x02, - PSON = 0x03, - SDPONA = 0x04, - DPON = 0x05, - PDSXNON = 0x06, - PDSAON = 0x07, - SDPNAA = 0x08, - PDSXON = 0x09, - DPNA = 0x0A, - PSDNAON = 0x0B, - SPNA = 0x0C, - PDSNAON = 0x0D, - PDSONON = 0x0E, - PN = 0x0F, - PDSONA = 0x10, - NOTSRCERASE = 0x11, - SDPXNON = 0x12, - SDPAON = 0x13, - DPSXNON = 0x14, - DPSAON = 0x15, - PSDPSANAXX = 0x16, - SSPXDSXAXN = 0x17, - SPXPDXA = 0x18, - SDPSANAXN = 0x19, - PDSPAOX = 0x1A, - SDPSXAXN = 0x1B, - PSDPAOX = 0x1C, - DSPDXAXN = 0x1D, - PDSOX = 0x1E, - PDSOAN = 0x1F, - DPSNAA = 0x20, - SDPXON = 0x21, - DSNA = 0x22, - SPDNAON = 0x23, - SPXDSXA = 0x24, - PDSPANAXN = 0x25, - SDPSAOX = 0x26, - SDPSXNOX = 0x27, - DPSXA = 0x28, - PSDPSAOXXN = 0x29, - DPSANA = 0x2A, - SSPXPDXAXN = 0x2B, - SPDSOAX = 0x2C, - PSDNOX = 0x2D, - PSDPXOX = 0x2E, - PSDNOAN = 0x2F, - PSNA = 0x30, - SDPNAON = 0x31, - SDPSOOX = 0x32, - NOTSRCCOPY = 0x33, - SPDSAOX = 0x34, - SPDSXNOX = 0x35, - SDPOX = 0x36, - SDPOAN = 0x37, - PSDPOAX = 0x38, - SPDNOX = 0x39, - SPDSXOX = 0x3A, - SPDNOAN = 0x3B, - PSX = 0x3C, - SPDSONOX = 0x3D, - SPDSNAOX = 0x3E, - PSAN = 0x3F, - PSDNAA = 0x40, - DPSXON = 0x41, - SDXPDXA = 0x42, - SPDSANAXN = 0x43, - SRCERASE = 0x44, - DPSNAON = 0x45, - DSPDAOX = 0x46, - PSDPXAXN = 0x47, - SDPXA = 0x48, - PDSPDAOXXN = 0x49, - DPSDOAX = 0x4A, - PDSNOX = 0x4B, - SDPANA = 0x4C, - SSPXDSXOXN = 0x4D, - PDSPXOX = 0x4E, - PDSNOAN = 0x4F, - PDNA = 0x50, - DSPNAON = 0x51, - DPSDAOX = 0x52, - SPDSXAXN = 0x53, - DPSONON = 0x54, - DSTINVERT = 0x55, - DPSOX = 0x56, - DPSOAN = 0x57, - PDSPOAX = 0x58, - DPSNOX = 0x59, - PATINVERT = 0x5A, - DPSDONOX = 0x5B, - DPSDXOX = 0x5C, - DPSNOAN = 0x5D, - DPSDNAOX = 0x5E, - DPAN = 0x5F, - PDSXA = 0x60, - DSPDSAOXXN = 0x61, - DSPDOAX = 0x62, - SDPNOX = 0x63, - SDPSOAX = 0x64, - DSPNOX = 0x65, - SRCINVERT = 0x66, - SDPSONOX = 0x67, - DSPDSONOXXN = 0x68, - PDSXXN = 0x69, - DPSAX = 0x6A, - PSDPSOAXXN = 0x6B, - SDPAX = 0x6C, - PDSPDOAXXN = 0x6D, - SDPSNOAX = 0x6E, - PDXNAN = 0x6F, - PDSANA = 0x70, - SSDXPDXAXN = 0x71, - SDPSXOX = 0x72, - SDPNOAN = 0x73, - DSPDXOX = 0x74, - DSPNOAN = 0x75, - SDPSNAOX = 0x76, - DSAN = 0x77, - PDSAX = 0x78, - DSPDSOAXXN = 0x79, - DPSDNOAX = 0x7A, - SDPXNAN = 0x7B, - SPDSNOAX = 0x7C, - DPSXNAN = 0x7D, - SPXDSXO = 0x7E, - DPSAAN = 0x7F, - DPSAA = 0x80, - SPXDSXON = 0x81, - DPSXNA = 0x82, - SPDSNOAXN = 0x83, - SDPXNA = 0x84, - PDSPNOAXN = 0x85, - DSPDSOAXX = 0x86, - PDSAXN = 0x87, - SRCAND = 0x88, - SDPSNAOXN = 0x89, - DSPNOA = 0x8A, - DSPDXOXN = 0x8B, - SDPNOA = 0x8C, - SDPSXOXN = 0x8D, - SSDXPDXAX = 0x8E, - PDSANAN = 0x8F, - PDSXNA = 0x90, - SDPSNOAXN = 0x91, - DPSDPOAXX = 0x92, - SPDAXN = 0x93, - PSDPSOAXX = 0x94, - DPSAXN = 0x95, - DPSXX = 0x96, - PSDPSONOXX = 0x97, - SDPSONOXN = 0x98, - DSXN = 0x99, - DPSNAX = 0x9A, - SDPSOAXN = 0x9B, - SPDNAX = 0x9C, - DSPDOAXN = 0x9D, - DSPDSAOXX = 0x9E, - PDSXAN = 0x9F, - DPA = 0xA0, - PDSPNAOXN = 0xA1, - DPSNOA = 0xA2, - DPSDXOXN = 0xA3, - PDSPONOXN = 0xA4, - PDXN = 0xA5, - DSPNAX = 0xA6, - PDSPOAXN = 0xA7, - DPSOA = 0xA8, - DPSOXN = 0xA9, - D = 0xAA, - DPSONO = 0xAB, - SPDSXAX = 0xAC, - DPSDAOXN = 0xAD, - DSPNAO = 0xAE, - DPNO = 0xAF, - PDSNOA = 0xB0, - PDSPXOXN = 0xB1, - SSPXDSXOX = 0xB2, - SDPANAN = 0xB3, - PSDNAX = 0xB4, - DPSDOAXN = 0xB5, - DPSDPAOXX = 0xB6, - SDPXAN = 0xB7, - PSDPXAX = 0xB8, - DSPDAOXN = 0xB9, - DPSNAO = 0xBA, - MERGEPAINT = 0xBB, - SPDSANAX = 0xBC, - SDXPDXAN = 0xBD, - DPSXO = 0xBE, - DPSANO = 0xBF, - MERGECOPY = 0xC0, - SPDSNAOXN = 0xC1, - SPDSONOXN = 0xC2, - PSXN = 0xC3, - SPDNOA = 0xC4, - SPDSXOXN = 0xC5, - SDPNAX = 0xC6, - PSDPOAXN = 0xC7, - SDPOA = 0xC8, - SPDOXN = 0xC9, - DPSDXAX = 0xCA, - SPDSAOXN = 0xCB, - SRCCOPY = 0xCC, - SDPONO = 0xCD, - SDPNAO = 0xCE, - SPNO = 0xCF, - PSDNOA = 0xD0, - PSDPXOXN = 0xD1, - PDSNAX = 0xD2, - SPDSOAXN = 0xD3, - SSPXPDXAX = 0xD4, - DPSANAN = 0xD5, - PSDPSAOXX = 0xD6, - DPSXAN = 0xD7, - PDSPXAX = 0xD8, - SDPSAOXN = 0xD9, - DPSDANAX = 0xDA, - SPXDSXAN = 0xDB, - SPDNAO = 0xDC, - SDNO = 0xDD, - SDPXO = 0xDE, - SDPANO = 0xDF, - PDSOA = 0xE0, - PDSOXN = 0xE1, - DSPDXAX = 0xE2, - PSDPAOXN = 0xE3, - SDPSXAX = 0xE4, - PDSPAOXN = 0xE5, - SDPSANAX = 0xE6, - SPXPDXAN = 0xE7, - SSPXDSXAX = 0xE8, - DSPDSANAXXN = 0xE9, - DPSAO = 0xEA, - DPSXNO = 0xEB, - SDPAO = 0xEC, - SDPXNO = 0xED, - SRCPAINT = 0xEE, - SDPNOO = 0xEF, - PATCOPY = 0xF0, - PDSONO = 0xF1, - PDSNAO = 0xF2, - PSNO = 0xF3, - PSDNAO = 0xF4, - PDNO = 0xF5, - PDSXO = 0xF6, - PDSANO = 0xF7, - PDSAO = 0xF8, - PDSXNO = 0xF9, - DPO = 0xFA, - PATPAINT = 0xFB, - PSO = 0xFC, - PSDNOO = 0xFD, - DPSOO = 0xFE, - WHITENESS = 0xFF - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ClipPrecision.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ClipPrecision.cs deleted file mode 100644 index b57fdf54..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ClipPrecision.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Flags -{ - using System; - - /// - /// Specify clipping precision, which defines how to clip characters that are partially outside a clipping region. - /// - [Flags] - internal enum ClipPrecision - { - /// - /// Specifies that default clipping MUST be used. - /// - CLIP_DEFAULT_PRECIS = 0x00000000, - - /// - /// This value SHOULD NOT be used. - /// - CLIP_CHARACTER_PRECIS = 0x00000001, - - /// - /// This value MAY be returned when enumerating rasterized, TrueType and vector fonts. - /// - CLIP_STROKE_PRECIS = 0x00000002, - - /// - /// This value is used to control font rotation. - /// - CLIP_LH_ANGLES = 0x00000010, - - /// - /// This value should not be used. - /// - CLIP_TT_ALWAYS = 0x00000020, - - /// - /// This value specifies that font association should be turned off. - /// - CLIP_DFA_DISABLE = 0x00000040, - - /// - /// This value specifies that font embedding MUST be used to render document content; embedded fonts are read-only. - /// - CLIP_EMBEDDED = 0x00000080 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ExtTextOutOptions.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ExtTextOutOptions.cs deleted file mode 100644 index c483f7f6..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/ExtTextOutOptions.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Flags -{ - /// - /// Specify various characteristics of the output of text. These flags can be combined to specify multiple options. - /// - /// - /// 2.1.2.2 ExtTextOutOptions Flags - /// - [Flags] - internal enum ExtTextOutOptions - { - /// - /// Indicates that the background color that is defined in the playback device context SHOULD be used to fill the rectangle. - /// - ETO_OPAQUE = 0x0002, - - /// - /// Indicates that the text SHOULD be clipped to the rectangle. - /// - ETO_CLIPPED = 0x0004, - - /// - /// Indicates that the string to be output SHOULD NOT require further processing with respect to the placement of the characters, - /// and an array of character placement values SHOULD be provided. This character placement process is - /// useful for fonts in which diacritical characters affect character spacing. - /// - ETO_GLYPH_INDEX = 0x0010, - - /// - /// Indicates that the text MUST be laid out in right-to-left reading order, instead of the default left-to-right order. - /// This SHOULD be applied only when the font that is defined in the playback device context is either Hebrew or Arabic. - /// - ETO_RTLREADING = 0x0080, - - /// - /// Indicates that to display numbers, digits appropriate to the locale SHOULD be used. - /// - ETO_NUMERICSLOCAL = 0x0400, - - /// - /// Indicates that to display numbers, European digits SHOULD be used. - /// - ETO_NUMERICSLATIN = 0x0800, - - /// - /// Indicates that both horizontal and vertical character displacement values SHOULD be provided. - /// - ETO_PDY = 0x2000 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/TextAlignmentMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Flags/TextAlignmentMode.cs deleted file mode 100644 index 6c9df2be..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/TextAlignmentMode.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Flags -{ - using System; - - /// - /// Specify the relationship between a reference point and a bounding rectangle, for text alignment. - /// These flags can be combined to specify multiple options, with the restriction that only one flag can be chosen that alters the drawing position in the playback device context. - /// - /// - /// 2.1.2.3 TextAlignmentMode Flags - /// - [Flags] - internal enum TextAlignmentMode - { - /// - /// The drawing position in the playback device context MUST NOT be updated after each text output call. - /// The reference point MUST be passed to the text output function. - /// - TA_NOUPDATECP = 0x0000, - - /// - /// The drawing position in the playback device context MUST be updated after each text output call. - /// It MUST be used as the reference point. - /// - TA_UPDATECP = 0x0001, - - /// - /// The reference point MUST be on the right edge of the bounding rectangle. - /// - TA_RIGHT = 0x0002, - - /// - /// The reference point MUST be aligned horizontally with the center of the bounding rectangle. - /// - TA_CENTER = 0x0006, - - /// - /// The reference point MUST be on the bottom edge of the bounding rectangle. - /// - TA_BOTTOM = 0x0008, - - /// - /// The reference point MUST be on the baseline of the text. - /// - TA_BASELINE = 0x0018, - - /// - /// The text MUST be laid out in right-to-left reading order, instead of the default left-to-right order. This SHOULD be applied only when the font that is defined in the playback device context is either Hebrew or Arabic. - /// - TA_RTLREADING = 0x0100 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/VerticalTextAlignmentMode.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Flags/VerticalTextAlignmentMode.cs deleted file mode 100644 index ca6b77c5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Flags/VerticalTextAlignmentMode.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Flags -{ - using System; - - /// - /// Specify the relationship between a reference point and a bounding rectangle, for text alignment. These flags can be combined to specify multiple options, with the restriction that only one flag can be chosen that alters the drawing position in the playback device context. - /// - /// - /// Vertical text alignment is performed when the font has a vertical default baseline, such as Kanji. - /// - /// 2.1.2.4 VerticalTextAlignmentMode Flags - /// - [Flags] - internal enum VerticalTextAlignmentMode - { - /// - /// The reference point MUST be on the top edge of the bounding rectangle. - /// - VTA_TOP = 0x0000, - - /// - /// The reference point MUST be on the bottom edge of the bounding rectangle. - /// - VTA_BOTTOM = 0x0002, - - /// - /// The reference point MUST be aligned vertically with the center of the bounding rectangle. - /// - VTA_CENTER = 0x0006, - - /// - /// The reference point MUST be on the left edge of the bounding rectangle. - /// - VTA_LEFT = 0x0008, - - /// - /// The reference point MUST be on the baseline of the text. - /// - VTA_BASELINE = 0x0018 - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Bitmap16.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Bitmap16.cs deleted file mode 100644 index 1b712289..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Bitmap16.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The Bitmap16 Object specifies information about the dimensions and color format of a bitmap. - /// - /// - /// 2.2.2.1 Bitmap16 Object - /// - internal struct Bitmap16 - { - /// - /// A 16-bit signed integer that defines the bitmap type. - /// - public short Type; - - /// - /// A 16-bit signed integer that defines the width of the bitmap in pixels. - /// - public short Width; - - /// - /// A 16-bit signed integer that defines the height of the bitmap in scan lines. - /// - public short Height; - - /// - /// A 16-bit signed integer that defines the number of bytes per scan line. - /// - public short WidthBytes; - - /// - /// An 8-bit unsigned integer that defines the number of color planes in the bitmap. The value of this field MUST be 0x01. - /// - public byte Planes; - - /// - /// An 8-bit unsigned integer that defines the number of adjacent color bits on each plane. - /// - public byte BitsPixel; - - public byte[] Bits; - - public int Length - { - get - { - return (((Width * BitsPixel + 15) >> 4) << 1) * Height; - } - } - public void Read(BinaryReader reader) - { - this.Type = reader.ReadInt16(); - this.Width = reader.ReadInt16(); - this.Height = reader.ReadInt16(); - this.WidthBytes = reader.ReadInt16(); - this.Planes = reader.ReadByte(); - this.BitsPixel = reader.ReadByte(); - this.Bits = reader.ReadBytes(this.Length); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.Type); - writer.Write(this.Width); - writer.Write(this.Height); - writer.Write(this.WidthBytes); - writer.Write(this.Planes); - writer.Write(this.BitsPixel); - if (this.Bits == null || this.Bits.Length != this.Length) - { - throw new InvalidOperationException("Bits array is null or does not match the expected length."); - } - writer.Write(this.Bits); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapCoreHeader.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapCoreHeader.cs deleted file mode 100644 index c3ce4324..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapCoreHeader.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The BitmapCoreHeader Object contains information about the dimensions and color format of a device-independent bitmap (DIB). - /// - /// - /// 2.2.2.2 BitmapCoreHeader Object - /// - internal struct BitmapCoreHeader - { - /// - /// A 32-bit unsigned integer that defines the size of this object, in bytes. - /// - public uint HeaderSize; - - /// - /// A 16-bit unsigned integer that defines the width of the DIB, in pixels. - /// - public ushort Width; - - /// - /// A 16-bit unsigned integer that defines the height of the DIB, in pixels. - /// - public ushort Height; - - /// - /// A 16-bit unsigned integer that defines the number of planes for the target device. This value MUST be 0x0001. - /// - public ushort Planes; - - /// - /// A 16-bit unsigned integer that defines the format of each pixel, and the maximum number of colors in the DIB. - /// - public BitCount BitCount; - - public void Read(BinaryReader reader) - { - this.HeaderSize = reader.ReadUInt32(); - this.Width = reader.ReadUInt16(); - this.Height = reader.ReadUInt16(); - this.Planes = reader.ReadUInt16(); - this.BitCount = (BitCount)reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.HeaderSize); - writer.Write(this.Width); - writer.Write(this.Height); - writer.Write(this.Planes); - writer.Write((ushort)this.BitCount); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapInfoHeader.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapInfoHeader.cs deleted file mode 100644 index d6a8f41f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapInfoHeader.cs +++ /dev/null @@ -1,101 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The BitmapInfoHeader Object contains information about the dimensions and color format of a device-independent bitmap (DIB). - /// - /// - /// 2.2.2.3 BitmapInfoHeader Object - /// - internal struct BitmapInfoHeader - { - /// - /// A 32-bit unsigned integer that defines the size of this object, in bytes. - /// - public uint HeaderSize; - - /// - /// A 32-bit signed integer that defines the width of the DIB, in pixels. This value MUST be positive. - /// - public int Width; - - /// - /// A 32-bit signed integer that defines the height of the DIB, in pixels. This value MUST NOT be zero. - /// - public int Height; - - /// - /// A 16-bit unsigned integer that defines the number of planes for the target device. This value MUST be 0x0001. - /// - public ushort Planes; - - /// - /// A 16-bit unsigned integer that defines the number of bits that define each pixel and the maximum number of colors in the DIB. - /// - public BitCount BitCount; - - /// - /// A 32-bit unsigned integer that defines the compression mode of the DIB. - /// - public Compression Compression; - - /// - /// A 32-bit unsigned integer that defines the size, in bytes, of the image. - /// - public uint ImageSize; - - /// - /// A 32-bit signed integer that defines the horizontal resolution, in pixels-per-meter, of the target device for the DIB. - /// - public int XPelsPerMeter; - - /// - /// A 32-bit signed integer that defines the vertical resolution, in pixels-per-meter, of the target device for the DIB. - /// - public int YPelsPerMeter; - - /// - /// 32-bit unsigned integer that specifies the number of indexes in the color table used by the DIB, as follows: - /// - public uint ColorUsed; - - /// - /// A 32-bit unsigned integer that defines the number of color indexes that are required for displaying the DIB. If this value is zero, all color indexes are required. - /// - public uint ColorImportant; - - public void Write(BinaryWriter writer) - { - writer.Write(this.HeaderSize); - writer.Write(this.Width); - writer.Write(this.Height); - writer.Write(this.Planes); - writer.Write((ushort)this.BitCount); - writer.Write((uint)this.Compression); - writer.Write(this.ImageSize); - writer.Write(this.XPelsPerMeter); - writer.Write(this.YPelsPerMeter); - writer.Write(this.ColorUsed); - writer.Write(this.ColorImportant); - } - - public void Read(BinaryReader reader) - { - this.HeaderSize = reader.ReadUInt32(); - this.Width = reader.ReadInt32(); - this.Height = reader.ReadInt32(); - this.Planes = reader.ReadUInt16(); - this.BitCount = (BitCount)reader.ReadUInt16(); - this.Compression = (Compression)reader.ReadUInt32(); - this.ImageSize = reader.ReadUInt32(); - this.XPelsPerMeter = reader.ReadInt32(); - this.YPelsPerMeter = reader.ReadInt32(); - this.ColorUsed = reader.ReadUInt32(); - this.ColorImportant = reader.ReadUInt32(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV4Header.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV4Header.cs deleted file mode 100644 index 784b7236..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV4Header.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The BitmapV4Header Object contains information about the dimensions and color format of a device-independent bitmap (DIB). - /// It is an extension of the BitmapInfoHeader object. - /// - /// - /// 2.2.2.4 BitmapV4Header Object - /// - internal class BitmapV4Header - { - /// - /// A BitmapInfoHeader object, which defines properties of the DIB. - /// - public BitmapInfoHeader BitmapInfoHeader; - - /// - /// A 32-bit unsigned integer that defines the color mask that specifies the red component of each pixel. - /// If the Compression value in the BitmapInfoHeader object is not BI_BITFIELDS, this value MUST be ignored. - /// - public uint RedMask; - - /// - /// A 32-bit unsigned integer that defines the color mask that specifies the green component of each pixel. - /// If the Compression value in the BitmapInfoHeader object is not BI_BITFIELDS, this value MUST be ignored. - /// - public uint GreenMask; - - /// - /// A 32-bit unsigned integer that defines the color mask that specifies the blue component of each pixel. - /// If the Compression value in the BitmapInfoHeader object is not BI_BITFIELDS, this value MUST be ignored. - /// - public uint BlueMask; - - /// - /// A 32-bit unsigned integer that defines the color mask that specifies the alpha component of each pixel. - /// - public uint AlphaMask; - - /// - /// A 32-bit unsigned integer that defines the color space of the Device Independent Bitmap object (section 2.2.2.9). - /// If this value is LCS_CALIBRATED_RGB from the LogicalColorSpace enumeration (section 2.1.1.14), the color values in the DIB are calibrated RGB values, and the endpoints and gamma values in this structure SHOULD be used to translate the color values before they are passed to the device. - /// - public uint ColorSpaceType; - - /// - /// A CIEXYZTriple object (section 2.2.2.7) that defines the CIE chromaticity x, y, and z coordinates of the three colors that correspond to the red, green, and blue endpoints for the logical color space associated with the DIB. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public CIEXYZTriple Endpoints; - - //TODO Fixed point - /// - /// A 32-bit fixed point value that defines the toned response curve for red. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaRed; - - /// - /// A 32-bit fixed point value that defines the toned response curve for green. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaGreen; - - /// - /// A 32-bit fixed point value that defines the toned response curve for blue. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaBlue; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV5Header.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV5Header.cs deleted file mode 100644 index 5788cf4b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/BitmapV5Header.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The BitmapV5Header Object contains information about the dimensions and color format of a device-independent bitmap (DIB). - /// It is an extension of the BitmapV4Header object (section 2.2.2.4). - /// - /// - /// 2.2.2.5 BitmapV5Header Object - /// - internal class BitmapV5Header - { - /// - /// A BitmapV4Header object, which defines properties of the DIB. - /// - public BitmapV4Header BitmapV4Header { get; set; } = new(); - - /// - /// A 32-bit unsigned integer that defines the rendering intent for the DIB. - /// This MUST be defined in the LogicalColorSpace enumeration (section 2.1.1.14). - /// - public uint Intent { get; set; } - - /// - /// A 32-bit unsigned integer that defines the offset, in bytes, from the beginning of this structure to the start of the color profile data. - /// - public uint ProfileData { get; set; } - - /// - /// A 32-bit unsigned integer that defines the size, in bytes, of embedded color profile data. - /// - public uint ProfileSize { get; set; } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Brush.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Brush.cs deleted file mode 100644 index 89be750c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Brush.cs +++ /dev/null @@ -1,27 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The Brush Object defines the style, color, and pattern of a brush. Brush Objects are created by the META_CREATEBRUSHINDIRECT, META_CREATEPATTERNBRUSH and META_DIBCREATEPATTERNBRUSH records. - /// - /// - /// 2.2.1.1 Brush Object - /// - internal class Brush - { - /// - /// A 16-bit unsigned integer that defines the brush style. The value MUST be an enumeration from the BrushStyle Enumeration table. For the meanings of the different values, see the following table. - /// - public BrushStyle BrushStyle; - - /// - /// A 32-bit field that specifies how to interpret color values in the object defined in the BrushHatch field. - /// Its interpretation depends on the value of BrushStyle, as explained in the following table. - /// - public uint ColorRef; - - //TODO BrushStyle specific reading - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZ.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZ.cs deleted file mode 100644 index a5c65295..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZ.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The CIEXYZ Object defines information about the CIEXYZ chromaticity object. - /// - /// - /// 2.2.2.6 CIEXYZ Object - /// - internal struct CIEXYZ - { - /// - /// A 32-bit 2.30 fixed point type that defines the x chromaticity value. - /// - public uint ciexyzX; - - /// - /// A 32-bit 2.30 fixed point type that defines the y chromaticity value. - /// - public uint ciexyzY; - - /// - /// A 32-bit 2.30 fixed point type that defines the z chromaticity value. - /// - public uint ciexyzZ; - - public void Read(BinaryReader reader) - { - this.ciexyzX = reader.ReadUInt32(); - this.ciexyzY = reader.ReadUInt32(); - this.ciexyzZ = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.ciexyzX); - writer.Write(this.ciexyzY); - writer.Write(this.ciexyzZ); - } - //TODO Read 2.30 decimal https://msdn.microsoft.com/en-us/library/t1de0ya1(v=vs.110).aspx - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZTriple.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZTriple.cs deleted file mode 100644 index 07d0306c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/CIEXYZTriple.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The CIEXYZTriple Object defines information about the CIEXYZTriple color object. - /// - /// - /// 2.2.2.7 CIEXYZTriple Object - /// - internal struct CIEXYZTriple - { - /// - /// A 96-bit CIEXYZ Object that defines the red chromaticity values. - /// - public CIEXYZ ciexyzRed; - - /// - /// A 96-bit CIEXYZ Object that defines the green chromaticity values. - /// - public CIEXYZ ciexyzGreen; - - /// - /// A 96-bit CIEXYZ Object that defines the blue chromaticity values. - /// - public CIEXYZ ciexyzBlue; - - public void Read(BinaryReader reader) - { - this.ciexyzRed.Read(reader); - this.ciexyzGreen.Read(reader); - this.ciexyzBlue.Read(reader); - } - - public void Write(BinaryWriter writer) - { - this.ciexyzRed.Write(writer); - this.ciexyzGreen.Write(writer); - this.ciexyzBlue.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/ColorRef.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/ColorRef.cs deleted file mode 100644 index 35d4e290..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/ColorRef.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The ColorRef Object defines the RGB color. - /// - /// - /// 2.2.2.8 ColorRef Object - /// - internal struct ColorRef - { - /// - /// An 8-bit unsigned integer that defines the relative intensity of red. - /// - public byte Red; - - /// - /// An 8-bit unsigned integer that defines the relative intensity of green. - /// - public byte Green; - - /// - /// An 8-bit unsigned integer that defines the relative intensity of blue. - /// - public byte Blue; - - /// - /// This byte MUST be 0x00. - /// - public byte Reserved; - - public void Read(BinaryReader reader) - { - this.Red = reader.ReadByte(); - this.Green = reader.ReadByte(); - this.Blue = reader.ReadByte(); - this.Reserved = reader.ReadByte(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.Red); - writer.Write(this.Green); - writer.Write(this.Blue); - writer.Write(this.Reserved); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/DeviceIndependentBitmap.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/DeviceIndependentBitmap.cs deleted file mode 100644 index 4ffe2d5a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/DeviceIndependentBitmap.cs +++ /dev/null @@ -1,116 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The DeviceIndependentBitmap Object defines an image in device-independent bitmap (DIB) format. - /// - /// - /// 2.2.2.9 DeviceIndependentBitmap Object - /// - internal class DeviceIndependentBitmap - { - public BitmapCoreHeader? BitmapCoreHeader { get; set; } - - public BitmapInfoHeader? BitmapInfoHeader { get; set; } - - public RGBQuad[]? Colors { get; set; } - - public byte[]? aData { get; set; } - - public void Read(BinaryReader reader) - { - long initialPosition = reader.BaseStream.Position; - uint headerSize = reader.ReadUInt32(); - reader.BaseStream.Position = initialPosition; - - int colorCount = 0; - if (headerSize == 12) // BitmapCoreHeader - { - var header = new BitmapCoreHeader(); - header.Read(reader); - this.BitmapCoreHeader = header; - if ((int)header.BitCount <= 8) - colorCount = 1 << (int)header.BitCount; - } - else - { - var header = new BitmapInfoHeader(); - header.Read(reader); - this.BitmapInfoHeader = header; - if (header.ColorUsed != 0) - { - colorCount = (int)header.ColorUsed; - } - else if ((int)header.BitCount <= 8) - { - colorCount = 1 << (int)header.BitCount; - } - } - - if (colorCount > 0) - { - this.Colors = new RGBQuad[colorCount]; - for (int i = 0; i < colorCount; i++) - { - this.Colors[i] = new RGBQuad(); - this.Colors[i].Read(reader); - } - } - - uint imageSize = this.BitmapInfoHeader?.ImageSize ?? 0; - if (imageSize > 0) - { - this.aData = reader.ReadBytes((int)imageSize); - } - else - { - // If ImageSize is not set, we need to calculate it based on dimensions and BitCount - int width = this.BitmapInfoHeader?.Width ?? this.BitmapCoreHeader?.Width ?? 0; - int height = this.BitmapInfoHeader?.Height ?? this.BitmapCoreHeader?.Height ?? 0; - BitCount bitCount = this.BitmapInfoHeader?.BitCount ?? this.BitmapCoreHeader?.BitCount ?? 0; - - if (width > 0 && height > 0 && bitCount > 0) - { - // Calculate row size (stride), rounded up to the nearest 4-byte boundary - int stride = (((width * (int)bitCount) + 31) & ~31) / 8; - imageSize = (uint)(stride * Math.Abs(height)); - this.aData = reader.ReadBytes((int)imageSize); - } - } - } - - public void Write(BinaryWriter writer) - { - if (BitmapCoreHeader.HasValue) - { - BitmapCoreHeader.Value.Write(writer); - } - else if (BitmapInfoHeader.HasValue) - { - BitmapInfoHeader.Value.Write(writer); - } - - if (Colors != null) - { - foreach (var color in Colors) - { - color.Write(writer); - } - } - - if (aData != null) - { - writer.Write(aData); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Font.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Font.cs deleted file mode 100644 index c82b728b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Font.cs +++ /dev/null @@ -1,130 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System; - using System.IO; - using System.Text; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Flags; - - /// - /// The Font object specifies the attributes of a logical font. - /// - /// - /// 2.2.1.2 Font Object - /// - internal class Font - { - /// - /// A 16-bit signed integer that specifies the height, in logical units, of the font's character cell. The character height is computed as the character cell height minus the internal leading. The font mapper SHOULD interpret the height as follows. - /// - public short Height { get; set; } - - /// - /// A 16-bit signed integer that defines the average width, in logical units, of characters in the font. - /// If Width is 0x0000, the aspect ratio of the device SHOULD be matched against the digitization aspect ratio of the available fonts to find the closest match, determined by the absolute value of the difference. - /// - public short Width { get; set; } - - /// - /// A 16-bit signed integer that defines the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. - /// The escapement vector is parallel to the base line of a row of text. - /// - public short Escapement { get; set; } - - /// - /// A 16-bit signed integer that defines the angle, in tenths of degrees, between each character's base line and the x-axis of the device. - /// - public short Orientation { get; set; } - - /// - /// A 16-bit signed integer that defines the weight of the font in the range 0 through 1000. - /// For example, 400 is normal and 700 is bold. If this value is 0x0000, a default weight SHOULD be used. - /// - public short Weight { get; set; } - - /// - /// A 8-bit Boolean value that specifies the italic attribute of the font. - /// - public byte Italic { get; set; } - - /// - /// An 8-bit Boolean value that specifies the underline attribute of the font. - /// - public byte Underline { get; set; } - - /// - /// An 8-bit Boolean value that specifies the strikeout attribute of the font. - /// - public byte StrikeOut { get; set; } - - /// - /// An 8-bit unsigned integer that defines the character set. It SHOULD be set to a value in the CharacterSet Enumeration (section 2.1.1.5). - /// - public CharacterSet CharSet { get; set; } - - /// - /// An 8-bit unsigned integer that defines the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. It MUST be one of the values from the OutPrecision Enumeration (section 2.1.1.21). - /// - public OutPrecision OutPrecision { get; set; } - - /// - /// An 8-bit unsigned integer that defines the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. - /// It MUST be a combination of one or more of the bit settings in the ClipPrecision Flags. - /// - public ClipPrecision ClipPrecision { get; set; } - - /// - /// A PitchAndFamily object (section 2.2.2.14) that defines the pitch and the family of the font. Font families specify the look of fonts in a general way and are intended for specifying fonts when the exact typeface wanted is not available. - /// - public byte PitchAndFamily { get; set; } - - public string Facename { get; set; } = string.Empty; - - public void Write(BinaryWriter writer) - { - writer.Write(Height); - writer.Write(Width); - writer.Write(Escapement); - writer.Write(Orientation); - writer.Write(Weight); - writer.Write(Italic); - writer.Write(Underline); - writer.Write(StrikeOut); - writer.Write((byte)CharSet); - writer.Write((byte)OutPrecision); - writer.Write((byte)ClipPrecision); - writer.Write(PitchAndFamily); - // Facename is a null-terminated ANSI string, max 32 bytes - var facenameBytes = new byte[32]; - if (!string.IsNullOrEmpty(Facename)) - { - var nameBytes = Encoding.ASCII.GetBytes(Facename); - int len = nameBytes.Length > 31 ? 31 : nameBytes.Length; - Array.Copy(nameBytes, facenameBytes, len); - } - writer.Write(facenameBytes); - } - - public void Read(BinaryReader reader) - { - Height = reader.ReadInt16(); - Width = reader.ReadInt16(); - Escapement = reader.ReadInt16(); - Orientation = reader.ReadInt16(); - Weight = reader.ReadInt16(); - Italic = reader.ReadByte(); - Underline = reader.ReadByte(); - StrikeOut = reader.ReadByte(); - CharSet = (CharacterSet)reader.ReadByte(); - OutPrecision = (OutPrecision)reader.ReadByte(); - ClipPrecision = (ClipPrecision)reader.ReadByte(); - PitchAndFamily = reader.ReadByte(); - var facenameBytes = reader.ReadBytes(32); - int facenameLen = Array.IndexOf(facenameBytes, (byte)0); - if (facenameLen < 0) facenameLen = 32; - Facename = Encoding.ASCII.GetString(facenameBytes, 0, facenameLen); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogBrush.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogBrush.cs deleted file mode 100644 index 2538516f..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogBrush.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The LogBrush Object defines the style, color, and pattern of a brush. This object is used only in the META_CREATEBRUSHINDIRECT Record (section 2.3.4.1) to create a Brush Object (section 2.2.1.1). - /// - /// - /// 2.2.2.10 LogBrush Object - /// - internal class LogBrush - { - /// - /// A 16-bit unsigned integer that defines the brush style. This MUST be a value from the BrushStyle Enumeration (section 2.1.1.4). For the meanings of different values, see the following table. The BS_NULL style specifies a brush that has no effect. - /// - public BrushStyle BrushStyle; - - /// - /// A 32-bit ColorRef Object (section 2.2.2.8) that specifies a color. - /// Its interpretation depends on the value of BrushStyle, as explained in the following. - /// - public ColorRef ColorRef; - - /// - /// A 16-bit field that specifies the brush hatch type. Its interpretation depends on the value of BrushStyle, as explained in the following. - /// - public HatchStyle? BrushHatch; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpace.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpace.cs deleted file mode 100644 index 8313d22e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpace.cs +++ /dev/null @@ -1,182 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.Collections.Generic; - using System.IO; - using System.Text; - - /// - /// The LogColorSpace object specifies a logical color space for the playback device context, which can be the name of a color profile in ASCII characters. - /// - /// - /// 2.2.2.11 LogColorSpace Object - /// - internal class LogColorSpace - { - /// - /// A 32-bit unsigned integer that specifies the signature of color space objects. - /// This MUST be set to the value 0x50534F43, which is the ASCII encoding of the string "PSOC". - /// - public uint Signature; - - /// - /// A 32-bit unsigned integer that defines a version number; it MUST be 0x00000400. - /// - public uint Version; - - /// - /// A 32-bit unsigned integer that defines the size of this object, in bytes. - /// - public uint Size; - - /// - /// A 32-bit signed integer that specifies the color space type. It MUST be defined in the LogicalColorSpace enumeration (section 2.1.1.14). - /// If this value is LCS_sRGB or LCS_WINDOWS_COLOR_SPACE, the sRGB color space MUST be used. - /// - public LogicalColorSpace ColorSpaceType; - - /// - /// A 32-bit signed integer that defines the gamut mapping intent. It MUST be defined in the GamutMappingIntent enumeration (section 2.1.1.11). - /// - public GamutMappingIntent Intent; - - /// - /// A CIEXYZTriple object (section 2.2.2.7) that defines the CIE chromaticity x, y, and z coordinates of the three colors that correspond to the RGB endpoints for the logical color space associated with the bitmap. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public CIEXYZTriple Endpoints; - - /// - /// A 32-bit fixed point value that defines the toned response curve for red. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public decimal GammaRed; - - /// - /// A 32-bit fixed point value that defines the toned response curve for green. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public decimal GammaGreen; - - /// - /// A 32-bit fixed point value that defines the toned response curve for blue. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public decimal GammaBlue; - - /// - /// An optional, ASCII charactger string that specifies the name of a file that contains a color profile. If a file name is specified, and the ColorSpaceType field is set to LCS_CALIBRATED_RGB, the other fields of this structure SHOULD be ignored. - /// - public string? Filename; - - /// - /// Reads the LogColorSpace fields from a BinaryReader in the correct order. - /// - public void ReadFrom(BinaryReader reader) - { - this.Signature = reader.ReadUInt32(); - this.Version = reader.ReadUInt32(); - this.Size = reader.ReadUInt32(); - this.ColorSpaceType = (LogicalColorSpace)reader.ReadInt32(); - this.Intent = (GamutMappingIntent)reader.ReadInt32(); - - if (this.ColorSpaceType == LogicalColorSpace.LCS_CALIBRATED_RGB) - { - this.Endpoints = new CIEXYZTriple(); - this.Endpoints.Read(reader); - this.GammaRed = ReadFixedPoint2_30(reader); - this.GammaGreen = ReadFixedPoint2_30(reader); - this.GammaBlue = ReadFixedPoint2_30(reader); - - if (reader.BaseStream.Position < reader.BaseStream.Length) - { - this.Filename = ReadAsciiString(reader); - } - else - { - this.Filename = null; - } - } - else - { - this.Endpoints = default(CIEXYZTriple); - this.GammaRed = 0; - this.GammaGreen = 0; - this.GammaBlue = 0; - this.Filename = ReadAsciiString(reader); - } - } - - /// - /// Writes the LogColorSpace fields to a BinaryWriter in the correct order. - /// - public void Write(BinaryWriter writer) - { - writer.Write(this.Signature); - writer.Write(this.Version); - writer.Write(this.Size); - writer.Write((int)this.ColorSpaceType); - writer.Write((int)this.Intent); - - if (this.ColorSpaceType == LogicalColorSpace.LCS_CALIBRATED_RGB) - { - this.Endpoints.Write(writer); - WriteFixedPoint2_30(writer, this.GammaRed); - WriteFixedPoint2_30(writer, this.GammaGreen); - WriteFixedPoint2_30(writer, this.GammaBlue); - if (!string.IsNullOrEmpty(this.Filename)) - WriteAsciiString(writer, this.Filename); - } - else - { - WriteAsciiString(writer, this.Filename ?? string.Empty); - } - } - - /// - /// Reads a 32-bit 2.30 fixed-point value from the reader and converts to decimal. - /// - private static decimal ReadFixedPoint2_30(BinaryReader reader) - { - uint raw = reader.ReadUInt32(); - // 2 bits integer, 30 bits fraction - return raw / (decimal)(1 << 30); - } - - /// - /// Reads an ASCII string up to a null terminator or end of stream. - /// - private static string ReadAsciiString(BinaryReader reader) - { - var bytes = new List(); - while (reader.BaseStream.Position < reader.BaseStream.Length) - { - byte b = reader.ReadByte(); - if (b == 0) break; - bytes.Add(b); - } - return Encoding.ASCII.GetString(bytes.ToArray()); - } - - /// - /// Writes a decimal as a 32-bit 2.30 fixed-point value to the writer. - /// - private static void WriteFixedPoint2_30(BinaryWriter writer, decimal value) - { - uint raw = (uint)(value * (1 << 30)); - writer.Write(raw); - } - - /// - /// Writes an ASCII string with a null terminator. - /// - private static void WriteAsciiString(BinaryWriter writer, string value) - { - byte[] bytes = Encoding.ASCII.GetBytes(value); - writer.Write(bytes); - writer.Write((byte)0); // Null terminator - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpaceW.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpaceW.cs deleted file mode 100644 index 99373fda..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/LogColorSpaceW.cs +++ /dev/null @@ -1,119 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - using System.Text; - - /// - /// The LogColorSpaceW object specifies a logical color space, which can be defined by a color profile file with a name consisting of Unicode 16-bit characters. - /// - /// - /// 2.2.2.12 LogColorSpaceW Object - /// - internal class LogColorSpaceW - { - private const int FixedSize = 68; - - /// - /// A 32-bit unsigned integer that specifies the signature of color space objects. - /// This MUST be set to the value 0x50534F43, which is the ASCII encoding of the string "PSOC". - /// - public uint Signature { get; set; } - - /// - /// A 32-bit unsigned integer that defines a version number; it MUST be 0x00000400. - /// - public uint Version { get; set; } - - /// - /// A 32-bit unsigned integer that defines the size of this object, in bytes. - /// - public uint Size { get; set; } - - /// - /// A 32-bit signed integer that specifies the color space type. It MUST be defined in the LogicalColorSpace enumeration (section 2.1.1.14). - /// If this value is LCS_sRGB or LCS_WINDOWS_COLOR_SPACE, the sRGB color space MUST be used. - /// - public LogicalColorSpace ColorSpaceType { get; set; } - - /// - /// A 32-bit signed integer that defines the gamut mapping intent. It MUST be defined in the GamutMappingIntent enumeration (section 2.1.1.11). - /// - public GamutMappingIntent Intent { get; set; } - - /// - /// A CIEXYZTriple object (section 2.2.2.7) that defines the CIE chromaticity x, y, and z coordinates of the three colors that correspond to the RGB endpoints for the logical color space associated with the bitmap. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public CIEXYZTriple Endpoints { get; set; } = new(); - - /// - /// A 32-bit fixed point value that defines the toned response curve for red. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaRed { get; set; } - - /// - /// A 32-bit fixed point value that defines the toned response curve for green. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaGreen { get; set; } - - /// - /// A 32-bit fixed point value that defines the toned response curve for blue. - /// If the ColorSpaceType field does not specify LCS_CALIBRATED_RGB, this field MUST be ignored. - /// - public uint GammaBlue { get; set; } - - /// - /// An optional, null-terminated Unicode UTF16-LE character string, which specifies the name of a file that contains a color profile. If a file name is specified, and the ColorSpaceType field is set to LCS_CALIBRATED_RGB, the other fields of this structure SHOULD be ignored. - /// - public string Filename { get; set; } = string.Empty; - - public LogColorSpaceW() - { - Signature = 0x50534F43; - Version = 0x00000400; - } - - public void Read(BinaryReader reader) - { - Signature = reader.ReadUInt32(); - Version = reader.ReadUInt32(); - Size = reader.ReadUInt32(); - ColorSpaceType = (LogicalColorSpace)reader.ReadInt32(); - Intent = (GamutMappingIntent)reader.ReadInt32(); - var endpoints = Endpoints; - endpoints.Read(reader); - Endpoints = endpoints; - GammaRed = reader.ReadUInt32(); - GammaGreen = reader.ReadUInt32(); - GammaBlue = reader.ReadUInt32(); - - if (Size > FixedSize) - { - byte[] filenameBytes = reader.ReadBytes((int)(Size - FixedSize)); - Filename = Encoding.Unicode.GetString(filenameBytes).TrimEnd('\0'); - } - } - - public void Write(BinaryWriter writer) - { - byte[] filenameBytes = Encoding.Unicode.GetBytes(Filename + "\0"); - Size = (uint)(FixedSize + filenameBytes.Length); - - writer.Write(Signature); - writer.Write(Version); - writer.Write(Size); - writer.Write((int)ColorSpaceType); - writer.Write((int)Intent); - Endpoints.Write(writer); - writer.Write(GammaRed); - writer.Write(GammaGreen); - writer.Write(GammaBlue); - writer.Write(filenameBytes); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Palette.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Palette.cs deleted file mode 100644 index 704fd92b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Palette.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The Palette Object specifies the colors in a logical palette. - /// - /// - /// 2.2.1.3 Palette Object - /// - internal class Palette - { - /// - /// A 16-bit unsigned integer that defines the offset into the Palette Object when used with the META_SETPALENTRIES and META_ANIMATEPALETTE record types. When used with META_CREATEPALETTE, it MUST be 0x0300. - /// - public ushort Start; - - /// - /// A 16-bit unsigned integer that defines the number of objects in aPaletteEntries. - /// - public ushort NumberOfEntries; - - public List PaletteEntries { get; set; } = new List(); - - public void Write(System.IO.BinaryWriter writer) - { - writer.Write(this.Start); - writer.Write((ushort)PaletteEntries.Count); - foreach (var entry in PaletteEntries) - { - entry.Write(writer); - } - } - - public void Read(System.IO.BinaryReader reader) - { - this.Start = reader.ReadUInt16(); - this.NumberOfEntries = reader.ReadUInt16(); - for (int i = 0; i < NumberOfEntries; i++) - { - var entry = new PaletteEntry(); - entry.Read(reader); - PaletteEntries.Add(entry); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PaletteEntry.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PaletteEntry.cs deleted file mode 100644 index 31959214..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PaletteEntry.cs +++ /dev/null @@ -1,52 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - /// - /// The PaletteEntry Object defines the color and usage of an entry in a palette. - /// - /// - /// 2.2.2.13 PaletteEntry Object - /// - internal class PaletteEntry - { - /// - /// An 8-bit unsigned integer that defines how the palette entry is to be used. - /// The Values field MUST be 0x00 or one of the values in the PaletteEntryFlag Enumeration table. - /// - public PaletteEntryFlag Values; - - /// - /// An 8-bit unsigned integer that defines the blue intensity value for the palette entry. - /// - public byte Blue; - - /// - /// An 8-bit unsigned integer that defines the green intensity value for the palette entry. - /// - public byte Green; - - /// - /// An 8-bit unsigned integer that defines the red intensity value for the palette entry. - /// - public byte Red; - - public void Read(BinaryReader reader) - { - Values = (PaletteEntryFlag)reader.ReadByte(); - Blue = reader.ReadByte(); - Green = reader.ReadByte(); - Red = reader.ReadByte(); - } - - public void Write(BinaryWriter writer) - { - writer.Write((byte)Values); - writer.Write(Blue); - writer.Write(Green); - writer.Write(Red); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Pen.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Pen.cs deleted file mode 100644 index 2c5cc6fc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Pen.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The Pen Object specifies the style, width, and color of a pen. - /// - /// - /// 2.2.1.4 Pen Object - /// - internal class Pen - { - /// - /// A 16-bit unsigned integer that specifies the pen style. The value MUST be defined from the PenStyle Enumeration table. - /// - public PenStyle PenStyle; - - /// - /// A 32-bit PointS Object that specifies a point for the object dimensions. The x-coordinate is the pen width. The y-coordinate is ignored. - /// - public PointS Width; - - /// - /// A 32-bit ColorRef Object that specifies the pen color value. - /// - public ColorRef ColorRef; - - public void Read(BinaryReader reader) - { - this.PenStyle = (PenStyle)reader.ReadUInt16(); - this.Width.Read(reader); - this.ColorRef.Read(reader); - } - - public void Write(System.IO.BinaryWriter writer) - { - writer.Write((ushort)this.PenStyle); - this.Width.Write(writer); - this.ColorRef.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PitchAndFamily.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PitchAndFamily.cs deleted file mode 100644 index 705c8d41..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PitchAndFamily.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - using MiniSoftware.Drawing.Metafile; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - - /// - /// The PitchAndFamily object specifies the pitch and family properties of a Font object (section 2.2.1.2). - /// Pitch refers to the width of the characters, and family refers to the general appearance of a font. - /// - /// - /// 2.2.2.14 PitchAndFamily Object - /// - internal struct PitchAndFamily - { - /// - /// A property of a font that describes its general appearance. This MUST be a value in the FamilyFont enumeration (section 2.1.1.8). - /// - public FamilyFont Family; - - /// - /// A property of a font that describes the pitch, of the characters. This MUST be a value in the PitchFont enumeration (section 2.1.1.24). - /// - public PitchFont Pitch; - - public void Read(BinaryReader reader) - { - var value = reader.ReadByte(); - this.Family = (FamilyFont)BitManipulation.GetBits(value, 0, 4); - this.Pitch = (PitchFont)BitManipulation.GetBits(value, 6, 2); - } - - public void Write(BinaryWriter writer) - { - byte value = (byte)((byte)this.Family | ((byte)this.Pitch << 6)); - writer.Write(value); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointL.cs deleted file mode 100644 index 24674077..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointL.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The PointL Object defines the coordinates of a point. - /// - /// - /// 2.2.2.15 PointL Object - /// - internal struct PointL - { - /// - /// A 32-bit signed integer that defines the horizontal (x) coordinate of the point. - /// - public int x; - - /// - /// A 32-bit signed integer that defines the vertical (y) coordinate of the point. - /// - public int y; - - public void Read(BinaryReader reader) - { - this.x = reader.ReadInt32(); - this.y = reader.ReadInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.x); - writer.Write(this.y); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointS.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointS.cs deleted file mode 100644 index f6cc241d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PointS.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The PointS Object defines the x- and y-coordinates of a point. - /// - /// - /// 2.2.2.16 PointS Object - /// - internal struct PointS - { - /// - /// A 16-bit signed integer that defines the horizontal (x) coordinate of the point. - /// - public int x; - - /// - /// A 16-bit signed integer that defines the vertical (y) coordinate of the point. - /// - public int y; - - public void Read(BinaryReader reader) - { - this.x = reader.ReadInt16(); - this.y = reader.ReadInt16(); - } - - public void Write(System.IO.BinaryWriter writer) - { - writer.Write((short)this.x); - writer.Write((short)this.y); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PolyPolygon.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PolyPolygon.cs deleted file mode 100644 index 2b68fb68..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/PolyPolygon.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - /// - /// The PolyPolygon Object defines a series of closed polygons. - /// - /// - /// 2.2.2.17 PolyPolygon Object - /// - internal struct PolyPolygon - { - /// - /// A 16-bit unsigned integer that defines the number of polygons in the object. - /// - public ushort NumberOfPolygons; - - /// - /// A NumberOfPolygons array of 16-bit unsigned integers that define the number of points for each polygon in the object. - /// - public uint[] aPointsPerPolygon; - - /// - /// An array of 16-bit unsigned integers that define the coordinates of the polygons. - /// - public uint[] aPoints; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RGBQuad.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RGBQuad.cs deleted file mode 100644 index c6407af8..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RGBQuad.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The RGBQuad Object defines the pixel color values in an uncompressed DIB. - /// - /// - /// 2.2.2.20 RGBQuad Object - /// - internal struct RGBQuad - { - /// - /// An 8-bit unsigned integer that defines the relative intensity of blue. - /// - public byte Blue; - - /// - /// An 8-bit unsigned integer that defines the relative intensity of green. - /// - public byte Green; - - /// - /// An 8-bit unsigned integer that defines the relative intensity of red. - /// - public byte Red; - - public void Write(BinaryWriter writer) - { - writer.Write(this.Blue); - writer.Write(this.Green); - writer.Write(this.Red); - writer.Write((byte)0); // Reserved - } - - public void Read(BinaryReader reader) - { - this.Blue = reader.ReadByte(); - this.Green = reader.ReadByte(); - this.Red = reader.ReadByte(); - reader.ReadByte(); - } - - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Rect.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Rect.cs deleted file mode 100644 index 9866e287..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Rect.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The Rect Object defines a rectangle. - /// - /// - /// 2.2.2.18 Rect Object - /// - internal struct Rect - { - /// - /// A 16-bit signed integer that defines the x-coordinate, in logical coordinates, of the upper-left corner of the rectangle - /// - public short Left; - - /// - /// A 16-bit signed integer that defines the y-coordinate, in logical coordinates, of the upper-left corner of the rectangle. - /// - public short Top; - - /// - /// A 16-bit signed integer that defines the x-coordinate, in logical coordinates, of the lower-right corner of the rectangle. - /// - public short Right; - - /// - /// A 16-bit signed integer that defines the y-coordinate, in logical coordinates, of the lower-right corner of the rectangle. - /// - public short Bottom; - - public void Read(BinaryReader reader) - { - this.Left = reader.ReadInt16(); - this.Top = reader.ReadInt16(); - this.Right = reader.ReadInt16(); - this.Bottom = reader.ReadInt16(); - } - - public void Write(System.IO.BinaryWriter writer) - { - writer.Write(this.Left); - writer.Write(this.Top); - writer.Write(this.Right); - writer.Write(this.Bottom); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RectL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RectL.cs deleted file mode 100644 index 0749281b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/RectL.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The RectL Object defines a rectangle. - /// - /// - /// 2.2.2.19 RectL Object - /// - internal struct RectL - { - /// - /// A 32-bit signed integer that defines the x-coordinate, in logical coordinates, of the upper-left corner of the rectangle - /// - public int Left; - - /// - /// A 32-bit signed integer that defines the y-coordinate, in logical coordinates, of the upper-left corner of the rectangle. - /// - public int Top; - - /// - /// A 32-bit signed integer that defines the x-coordinate, in logical coordinates, of the lower-right corner of the rectangle. - /// - public int Right; - - /// - /// A 32-bit signed integer that defines the y-coordinate, in logical coordinates, of the lower-right corner of the rectangle. - /// - public int Bottom; - - public void Read(BinaryReader reader) - { - this.Left = reader.ReadInt32(); - this.Top = reader.ReadInt32(); - this.Right = reader.ReadInt32(); - this.Bottom = reader.ReadInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.Left); - writer.Write(this.Top); - writer.Write(this.Right); - writer.Write(this.Bottom); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Region.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Region.cs deleted file mode 100644 index 23282668..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Region.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System; - using System.IO; - - /// - /// The Region Object defines a potentially non-rectilinear shape defined by an array of scanlines. - /// - /// - /// 2.2.1.5 Region Object - /// - internal class Region - { - /// - /// A value that MUST be ignored. - /// - public short nextInChain { get; set; } - - /// - /// A 16-bit signed integer that specifies the region identifier. It MUST be 0x0006. - /// - public short ObjectType { get; set; } - - /// - /// A value that MUST be ignored. - /// - public int ObjectCount { get; set; } - - /// - /// A 16-bit signed integer that defines the size of the region in bytes plus the size of aScans in bytes. - /// - public short RegionSize { get; set; } - - /// - /// A 16-bit signed integer that defines the number of scanlines composing the region. - /// - public short ScanCount { get; set; } - - /// - /// A 16-bit signed integer that defines the maximum number of points in any one scan in this region. - /// - internal short maxScan { get; set; } - - /// - /// A Rect object (section 2.2.2.18) that defines the bounding rectangle. - /// - public Rect BoundingRectangle { get; set; } - - /// - /// An array of Scan objects (section 2.2.2.21) that define the scanlines in the region. - /// - public Scan[] aScans { get; set; } = Array.Empty(); - - public void Read(BinaryReader reader) - { - nextInChain = reader.ReadInt16(); - ObjectType = reader.ReadInt16(); - ObjectCount = reader.ReadInt32(); - RegionSize = reader.ReadInt16(); - ScanCount = reader.ReadInt16(); - maxScan = reader.ReadInt16(); - var boundingBox = new Rect(); - boundingBox.Read(reader); - BoundingRectangle = boundingBox; - aScans = new Scan[ScanCount]; - for (int i = 0; i < ScanCount; i++) - { - aScans[i] = new Scan(); - aScans[i].Read(reader); - } - } - - public void Write(BinaryWriter writer) - { - writer.Write(nextInChain); - writer.Write(ObjectType); - writer.Write(ObjectCount); - writer.Write(RegionSize); - writer.Write(ScanCount); - writer.Write(maxScan); - var boundingBox = BoundingRectangle; - boundingBox.Write(writer); - if (aScans != null) - { - foreach (var scan in aScans) - { - scan.Write(writer); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Scan.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Scan.cs deleted file mode 100644 index 4cfc2d8c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/Scan.cs +++ /dev/null @@ -1,83 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System; - using System.IO; - - /// - /// The Scan Object specifies a collection of scanlines. - /// - /// - /// 2.2.2.21 Scan Object - /// - internal class Scan - { - public struct ScanLine - { - /// - /// A 16-bit unsigned integer that defines the horizontal (x-axis) coordinate, in logical units, of the left endpoint of the scanline. - /// - public ushort Left; - - /// - /// A 16-bit unsigned integer that defines the horizontal (x-axis) coordinate, in logical units, of the right endpoint of the scanline. - /// - public ushort Right; - } - - /// - /// A 16-bit unsigned integer that specifies the number of horizontal (x-axis) coordinates in the ScanLines array. - /// This value MUST be a multiple of 2, since left and right endpoints are required to specify each scanline. - /// - public ushort Count { get; set; } - - /// - /// A 16-bit unsigned integer that defines the vertical (y-axis) coordinate, in logical units, of the top scanline. - /// - public ushort Top { get; set; } - - /// - /// A 16-bit unsigned integer that defines the vertical (y-axis) coordinate, in logical units, of the bottom scanline. - /// - public ushort Bottom { get; set; } - - /// - /// An array of scanlines, each specified by left and right horizontal (x-axis) coordinates of its endpoints. - /// - public ScanLine[] ScanLines { get; set; } = Array.Empty(); - - /// - /// A 16-bit unsigned integer that MUST be the same as the value of the Count field; it is present to allow upward travel in the structure. - /// - public ushort Count2 { get; set; } - - public void Read(BinaryReader reader) - { - Count = reader.ReadUInt16(); - Top = reader.ReadUInt16(); - Bottom = reader.ReadUInt16(); - ScanLines = new ScanLine[Count]; - for (int i = 0; i < ScanLines.Length; i++) - { - ScanLines[i].Left = reader.ReadUInt16(); - ScanLines[i].Right = reader.ReadUInt16(); - } - Count2 = reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(Count); - writer.Write(Top); - writer.Write(Bottom); - if (ScanLines != null) - { - foreach (var scanLine in ScanLines) - { - writer.Write(scanLine.Left); - writer.Write(scanLine.Right); - } - } - writer.Write(Count2); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/SizeL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Objects/SizeL.cs deleted file mode 100644 index b46a7519..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Objects/SizeL.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Objects -{ - using System.IO; - - /// - /// The SizeL Object defines the x- and y-extents of a rectangle. - /// - /// - /// 2.2.2.22 SizeL Object - /// - internal struct SizeL - { - /// - /// A 32-bit unsigned integer that defines the x-coordinate of the point. - /// - public uint cx; - - /// - /// A 32-bit unsigned integer that defines the y-coordinate of the point. - /// - public uint cy; - - public void Read(BinaryReader reader) - { - this.cx = reader.ReadUInt32(); - this.cy = reader.ReadUInt32(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.cx); - writer.Write(this.cy); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/AbstractBitmapRecord.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/AbstractBitmapRecord.cs deleted file mode 100644 index 695ebe0c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/AbstractBitmapRecord.cs +++ /dev/null @@ -1,65 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal abstract class AbstractBitmapRecord - { - public RecordHeader Header; - - /// - /// Defines how the source pixels, the current brush in the playback device context, and the destination pixels are to be combined to form the new image. - /// - public TernaryRasterOperation RasterOperation; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short YSrc; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short XSrc; - - /// - /// Defines the height, in logical units, of the source and destination rectangles. - /// - public short Height; - - /// - /// Defines the width, in logical units, of the source and destination rectangles. - /// - public short Width; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short YDest; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short XDest; - - /// - /// Defines source image content. This object MUST be specified, even if the raster operation does not require a source. - /// - public Bitmap16? Target; - - public bool HasBitmap - { - get - { - return this.Header.RecordSize == (((int)this.Header.RecordFunction >> 8) + 3); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/EscapeRecordTypes/MetaEscape.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/EscapeRecordTypes/MetaEscape.cs deleted file mode 100644 index c5cebf0b..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/EscapeRecordTypes/MetaEscape.cs +++ /dev/null @@ -1,50 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.EscapeRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - - /// - /// The META_ESCAPE record specifies extensions to WMF functionality that are not directly available through other records defined in the RecordType enumeration (section 2.1.1.1). - /// The MetafileEscapes enumeration (section 2.1.1.17) lists these extensions. - /// - internal class MetaEscape : Record - { - /// - /// Defines the escape function. The value MUST be from the MetafileEscapes enumeration. - /// - public MetafileEscapes EscapeFunction { get; set; } - - /// - /// Specifies the size, in bytes, of the EscapeData field. - /// - public ushort ByteCount { get; set; } - - /// - /// An array of bytes of size ByteCount. - /// - public byte[] EscapeData { get; set; } = Array.Empty(); - - public MetaEscape() - { - Header.RecordFunction = RecordType.META_ESCAPE; - } - - public override void Read(BinaryReader reader) - { - EscapeFunction = (MetafileEscapes)reader.ReadUInt16(); - ByteCount = reader.ReadUInt16(); - EscapeData = reader.ReadBytes(ByteCount); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)EscapeFunction); - writer.Write(ByteCount); - writer.Write(EscapeData); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ARC.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ARC.cs deleted file mode 100644 index a3ae05af..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ARC.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_ARC : Record - { - public short YEnd { get; set; } - public short XEnd { get; set; } - public short YStart { get; set; } - public short XStart { get; set; } - public short BottomRect { get; set; } - public short RightRect { get; set; } - public short TopRect { get; set; } - public short LeftRect { get; set; } - - public META_ARC() - { - Header.RecordFunction = RecordType.META_ARC; - } - - public override void Read(BinaryReader reader) - { - YEnd = reader.ReadInt16(); - XEnd = reader.ReadInt16(); - YStart = reader.ReadInt16(); - XStart = reader.ReadInt16(); - BottomRect = reader.ReadInt16(); - RightRect = reader.ReadInt16(); - TopRect = reader.ReadInt16(); - LeftRect = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(YEnd); - writer.Write(XEnd); - writer.Write(YStart); - writer.Write(XStart); - writer.Write(BottomRect); - writer.Write(RightRect); - writer.Write(TopRect); - writer.Write(LeftRect); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_BITBLT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_BITBLT.cs deleted file mode 100644 index c8779a6d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_BITBLT.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; -using MiniSoftware.Drawing.Metafile.Wmf.Objects; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_BITBLT : Record - { - public TernaryRasterOperation RasterOperation { get; set; } - public short YSrc { get; set; } - public short XSrc { get; set; } - public short Height { get; set; } - public short Width { get; set; } - public short YDest { get; set; } - public short XDest { get; set; } - public DeviceIndependentBitmap? Bitmap { get; set; } - - public META_BITBLT() - { - Header.RecordFunction = RecordType.META_BITBLT; - } - - public override void Read(BinaryReader reader) - { - RasterOperation = (TernaryRasterOperation)reader.ReadUInt32(); - YSrc = reader.ReadInt16(); - XSrc = reader.ReadInt16(); - Height = reader.ReadInt16(); - Width = reader.ReadInt16(); - YDest = reader.ReadInt16(); - XDest = reader.ReadInt16(); - - if (Header.RecordSize > 11) // 11 words for the record, excluding the bitmap - { - Bitmap = new DeviceIndependentBitmap(); - Bitmap.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((uint)RasterOperation); - writer.Write(YSrc); - writer.Write(XSrc); - writer.Write(Height); - writer.Write(Width); - writer.Write(YDest); - writer.Write(XDest); - - if (Bitmap != null) - { - Bitmap.Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_CHORD.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_CHORD.cs deleted file mode 100644 index fdf4a493..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_CHORD.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_CHORD : Record - { - public short YEndRadial { get; set; } - public short XEndRadial { get; set; } - public short YStartRadial { get; set; } - public short XStartRadial { get; set; } - public short BottomRect { get; set; } - public short RightRect { get; set; } - public short TopRect { get; set; } - public short LeftRect { get; set; } - - public META_CHORD() - { - Header.RecordFunction = RecordType.META_CHORD; - } - - public override void Read(BinaryReader reader) - { - YEndRadial = reader.ReadInt16(); - XEndRadial = reader.ReadInt16(); - YStartRadial = reader.ReadInt16(); - XStartRadial = reader.ReadInt16(); - BottomRect = reader.ReadInt16(); - RightRect = reader.ReadInt16(); - TopRect = reader.ReadInt16(); - LeftRect = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(YEndRadial); - writer.Write(XEndRadial); - writer.Write(YStartRadial); - writer.Write(XStartRadial); - writer.Write(BottomRect); - writer.Write(RightRect); - writer.Write(TopRect); - writer.Write(LeftRect); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBBITBLT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBBITBLT.cs deleted file mode 100644 index 95cfbec5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBBITBLT.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - /// - /// Specifies the transfer of a block of pixels in device-independent format according to a raster operation. - /// - /// - /// 2.3.1.2 META_DIBBITBLT Record - /// - internal class META_DIBBITBLT : AbstractBitmapRecord - { - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBSTRETCHBLT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBSTRETCHBLT.cs deleted file mode 100644 index a0c23dc3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_DIBSTRETCHBLT.cs +++ /dev/null @@ -1,81 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// Specifies the transfer of a block of pixels in device-independent format according to a raster operation, with possible expansion or contraction. - /// - /// - /// 2.3.1.3 META_DIBSTRETCHBLT Record - /// - internal class META_DIBSTRETCHBLT - { - public RecordHeader Header; - - /// - /// Defines how the source pixels, the current brush in the playback device context, and the destination pixels are to be combined to form the new image. - /// - public TernaryRasterOperation RasterOperation; - - /// - /// Defines the height, in logical units, of the source rectangle. - /// - public short SrcHeight; - - /// - /// Defines the width, in logical units, of the source rectangle. - /// - public short SrcWidth; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short YSrc; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short XSrc; - - /// - /// Defines the height, in logical units, of the destination rectangle. - /// - public short DestHeight; - - /// - /// Defines the width, in logical units, of the destination rectangle. - /// - public short DestWidth; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short YDest; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short XDest; - - /// - /// Defines source image content. This object MUST be specified, even if the raster operation does not require a source. - /// - public Bitmap16? Target; - - public bool HasBitmap - { - get - { - return this.Header.RecordSize == (((int)this.Header.RecordFunction >> 8) + 3); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ELLIPSE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ELLIPSE.cs deleted file mode 100644 index e087252e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ELLIPSE.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_ELLIPSE : Record - { - public short BottomRect { get; set; } - public short RightRect { get; set; } - public short TopRect { get; set; } - public short LeftRect { get; set; } - - public META_ELLIPSE() - { - Header.RecordFunction = RecordType.META_ELLIPSE; - } - - public override void Read(BinaryReader reader) - { - BottomRect = reader.ReadInt16(); - RightRect = reader.ReadInt16(); - TopRect = reader.ReadInt16(); - LeftRect = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(BottomRect); - writer.Write(RightRect); - writer.Write(TopRect); - writer.Write(LeftRect); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EOF.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EOF.cs deleted file mode 100644 index 0554f371..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EOF.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.IO; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_EOF : Record - { - public META_EOF() - { - Header.RecordFunction = RecordType.META_EOF; - } - - public override void Read(BinaryReader reader) - { - // no parameters - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTFLOODFILL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTFLOODFILL.cs deleted file mode 100644 index af2a1035..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTFLOODFILL.cs +++ /dev/null @@ -1,36 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_EXTFLOODFILL record fills an area with the brush that is defined in the playback device context. - /// - /// - /// 2.3.3.4 META_EXTFLOODFILL Record - /// - internal class META_EXTFLOODFILL : Record - { - /// - /// Defines the fill operation to be performed. - /// - public FloodFill Mode; - - /// - /// A 32-bit ColorRef Object that defines the color value. - /// - public ColorRef ColorRef; - - /// - /// Defines the y-coordinate, in logical units, of the point to be set. - /// - public short Y; - - /// - /// Defines the x-coordinate, in logical units, of the point to be set. - /// - public short X; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTTEXTOUT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTTEXTOUT.cs deleted file mode 100644 index 13ce96e4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_EXTTEXTOUT.cs +++ /dev/null @@ -1,124 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System; - using System.IO; - using System.Text; - using MiniSoftware.Drawing.Metafile.Emf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_EXTTEXTOUT record outputs text by using the font, background color, and text color that are defined in the playback device context. Optionally, dimensions can be provided for clipping, opaquing, or both. - /// - /// - /// 2.3.3.5 META_EXTTEXTOUT Record - /// - internal class META_EXTTEXTOUT : Record - { - /// - /// Defines the y-coordinate, in logical units, where the text string is to be located. - /// - public short Y { get; set; } - - /// - /// Defines the x-coordinate, in logical units, where the text string is to be located. - /// - public short X { get; set; } - - /// - /// Defines the length of the string. - /// - public short StringLength { get; set; } - - /// - /// Defines the use of the application-defined rectangle. - /// - public ExtTextOutOptions fwOpts { get; set; } - - /// - /// An optional 8-byte Rect Object (section 2.2.2.18) that defines the dimensions, in logical coordinates, of a rectangle that is used for clipping, opaquing, or both. - /// - public Rect Rectangle { get; set; } - - /// - /// A variable-length string that specifies the text to be drawn. The string does not need to be null-terminated, because StringLength specifies the length of the string. If the length is odd, an extra byte is placed after it so that the following member (optional Dx) is aligned on a 16-bit boundary. - /// - public string String { get; set; } = string.Empty; - - /// - /// An optional array of 16-bit signed integers that indicate the distance between origins of adjacent character cells. For example, Dx[i] logical units separate the origins of character cell i and character cell i + 1. - /// If this field is present, there MUST be the same number of values as there are characters in the string. - /// - public short[] Dx { get; set; } = Array.Empty(); - - public META_EXTTEXTOUT() - { - Header.RecordFunction = Enumerations.RecordType.META_EXTTEXTOUT; - } - - public override void Read(BinaryReader reader) - { - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - StringLength = reader.ReadInt16(); - fwOpts = (ExtTextOutOptions)reader.ReadUInt16(); - - if ((fwOpts & (ExtTextOutOptions.ETO_CLIPPED | ExtTextOutOptions.ETO_OPAQUE)) != 0) - { - var rect = new Rect(); - rect.Read(reader); - Rectangle = rect; - } - - byte[] stringBytes = reader.ReadBytes(StringLength); - String = Encoding.Default.GetString(stringBytes); - - if (StringLength > 0 && StringLength % 2 != 0) - { - reader.ReadByte(); // consume padding byte - } - - if ((fwOpts & ExtTextOutOptions.ETO_PDY) != 0) - { - Dx = new short[StringLength]; - for (int i = 0; i < StringLength; i++) - { - Dx[i] = reader.ReadInt16(); - } - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - - writer.Write(Y); - writer.Write(X); - writer.Write(StringLength); - writer.Write((ushort)fwOpts); - - if ((fwOpts & (ExtTextOutOptions.ETO_CLIPPED | ExtTextOutOptions.ETO_OPAQUE)) != 0) - { - Rectangle.Write(writer); - } - - byte[] stringBytes = Encoding.Default.GetBytes(String); - writer.Write(stringBytes); - - if (StringLength > 0 && StringLength % 2 != 0) - { - writer.Write((byte)0); - } - - if ((fwOpts & ExtTextOutOptions.ETO_PDY) != 0) - { - foreach (short val in Dx) - { - writer.Write(val); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FILLREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FILLREGION.cs deleted file mode 100644 index 44d04468..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FILLREGION.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_FILLREGION record fills a region using a specified brush. - /// - /// - /// 2.3.3.6 META_FILLREGION Record - /// - internal class META_FILLREGION : Record - { - /// - /// Used to index into the WMF Object Table to get the region to be filled. - /// - public ushort Region { get; set; } - - /// - /// Used to index into the WMF Object Table to get the brush to use for filling the region. - /// - public ushort Brush { get; set; } - - public META_FILLREGION() - { - Header.RecordFunction = RecordType.META_FILLREGION; - } - - public override void Read(BinaryReader reader) - { - Region = reader.ReadUInt16(); - Brush = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Region); - writer.Write(Brush); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FLOODFILL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FLOODFILL.cs deleted file mode 100644 index d342b9be..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FLOODFILL.cs +++ /dev/null @@ -1,54 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_FLOODFILL record fills an area of the output surface with the brush that is defined in the playback device context. - /// - /// - /// 2.3.3.7 META_FLOODFILL Record - /// - internal class META_FLOODFILL : Record - { - /// - /// A 32-bit ColorRef Object that defines the color value. - /// - public ColorRef ColorRef { get; set; } = new(); - - /// - /// Defines the y-coordinate, in logical units, of the point where filling is to start. - /// - public short YStart { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the point where filling is to start. - /// - public short XStart { get; set; } - - public META_FLOODFILL() - { - Header.RecordFunction = RecordType.META_FLOODFILL; - } - - public override void Read(BinaryReader reader) - { - var colorRef = ColorRef; - colorRef.Read(reader); - ColorRef = colorRef; - YStart = reader.ReadInt16(); - XStart = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - ColorRef.Write(writer); - writer.Write(YStart); - writer.Write(XStart); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FRAMEREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FRAMEREGION.cs deleted file mode 100644 index ab8831ac..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_FRAMEREGION.cs +++ /dev/null @@ -1,58 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_FRAMEREGION record draws a border around a specified region using a specified brush. - /// - /// - /// 2.3.3.8 META_FRAMEREGION Record - /// - internal class META_FRAMEREGION : Record - { - /// - /// Used to index into the WMF Object Table to get the region to be framed. - /// - public ushort Region { get; set; } - - /// - /// Used to index into the WMF Object Table to get the Brush to use for filling the region. - /// - public ushort Brush { get; set; } - - /// - /// Defines the height, in logical units, of the region frame. - /// - public ushort Height { get; set; } - - /// - /// Defines the width, in logical units, of the region frame. - /// - public ushort Width { get; set; } - - public META_FRAMEREGION() - { - Header.RecordFunction = RecordType.META_FRAMEREGION; - } - - public override void Read(BinaryReader reader) - { - Region = reader.ReadUInt16(); - Brush = reader.ReadUInt16(); - Height = reader.ReadUInt16(); - Width = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Region); - writer.Write(Brush); - writer.Write(Height); - writer.Write(Width); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_INVERTREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_INVERTREGION.cs deleted file mode 100644 index 72601a93..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_INVERTREGION.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - /// - /// The META_INVERTREGION record draws a region in which the colors are inverted. - /// - /// - /// 2.3.3.9 META_INVERTREGION Record - /// - internal class META_INVERTREGION : Record - { - /// - /// Used to index into the WMF Object Table to get the region to be inverted. - /// - public ushort Region; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_LINETO.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_LINETO.cs deleted file mode 100644 index 537831d5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_LINETO.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - /// - /// The META_LINETO record draws a line from the drawing position that is defined in the playback device context up to, but not including, the specified point. - /// - /// - /// 2.3.3.10 META_LINETO Record - /// - internal class META_LINETO : Record - { - /// - /// Defines the vertical component of the drawing destination position, in logical units. - /// - public short Y; - - /// - /// Defines the horizontal component of the drawing destination position, in logical units. - /// - public short X; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PAINTREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PAINTREGION.cs deleted file mode 100644 index 1984bc19..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PAINTREGION.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.IO; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - /// - /// The META_PAINTREGION record paints the specified region by using the brush that is defined in the playback device context. - /// - /// - /// 2.3.3.11 META_PAINTREGION Record - /// - internal class META_PAINTREGION : Record - { - /// - /// Used to index into the WMF Object Table to get the region to be painted. - /// - public ushort Region; - - public override void Read(BinaryReader reader) - { - Region = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(Region); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PATBLT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PATBLT.cs deleted file mode 100644 index db7bb36c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PATBLT.cs +++ /dev/null @@ -1,63 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_PATBLT record paints a specified rectangle using the brush that is defined in the playback device context. - /// The brush color and the surface color or colors are combined using the specified raster operation. - /// - internal class META_PATBLT : Record - { - /// - /// Defines the raster operation code. - /// - public TernaryRasterOperation RasterOperation { get; set; } - - /// - /// Defines the height, in logical units, of the rectangle. - /// - public short Height { get; set; } - - /// - /// Defines the width, in logical units, of the rectangle. - /// - public short Width { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the rectangle to be filled. - /// - public short YLeft { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the rectangle to be filled. - /// - public short XLeft { get; set; } - - public META_PATBLT() - { - Header.RecordFunction = RecordType.META_PATBLT; - } - - public override void Read(BinaryReader reader) - { - RasterOperation = (TernaryRasterOperation)reader.ReadUInt32(); - Height = reader.ReadInt16(); - Width = reader.ReadInt16(); - YLeft = reader.ReadInt16(); - XLeft = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((uint)RasterOperation); - writer.Write(Height); - writer.Write(Width); - writer.Write(YLeft); - writer.Write(XLeft); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PIE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PIE.cs deleted file mode 100644 index 3c9f6c77..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PIE.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - /// - /// The META_PIE record draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. - /// The pie is outlined by using the pen and filled by using the brush that are defined in the playback device context. - /// - /// - /// 2.3.3.13 META_PIE Record - /// - internal class META_PIE : Record - { - /// - /// Defines the y-coordinate, in logical coordinates, of the endpoint of the second radial. - /// - public short YRadial2; - - /// - /// Defines the x-coordinate, in logical coordinates, of the endpoint of the second radial. - /// - public short XRadial2; - - /// - /// Defines the y-coordinate, in logical coordinates, of the endpoint of the first radial. - /// - public short YRadial1; - - /// - /// Defines the x-coordinate, in logical coordinates, of the endpoint of the first radial. - /// - public short XRadial1; - - /// - /// Defines the y-coordinate, in logical units, of the lower-right corner of the bounding rectangle. - /// - public short BottomRect; - - /// - /// Defines the x-coordinate, in logical units, of the lower-right corner of the bounding rectangle. - /// - public short RightRect; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the bounding rectangle. - /// - public short TopRect; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the bounding rectangle. - /// - public short LeftRect; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PLACEABLE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PLACEABLE.cs deleted file mode 100644 index a0de5a78..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_PLACEABLE.cs +++ /dev/null @@ -1,85 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_PLACEABLE record is the first record in a placeable WMF metafile, which is an extension to the WMF metafile format. The information in this extension allows the specification of the placement and size of the target image, which makes it adaptable to different output devices. - /// - internal class META_PLACEABLE - { - /// - /// Identification value that indicates the presence of a placeable metafile header. This value MUST be 0x9AC6CDD7. - /// - public uint Key { get; set; } - - /// - /// The resource handle to the metafile, when the metafile is in memory. When the metafile is on disk, this field MUST contain 0x0000. - /// This attribute of the metafile is specified in the Type field of the META_HEADER record. - /// - public ushort HWmf { get; set; } - - /// - /// The destination rectangle, measured in logical units, for displaying the metafile. The size of a logical unit is specified by the Inch field. - /// - public Rect BoundingBox { get; set; } = new(); - - /// - /// The number of logical units per inch used to represent the image. This value can be used to scale an image. - /// - public ushort Inch { get; set; } - - /// - /// A 32-bit unsigned integer that is reserved and MUST be 0x00000000. - /// - public uint Reserved { get; set; } - - /// - /// A checksum for the previous 10 16-bit values in the header. This value can be used to determine whether the metafile has become corrupted. - /// - public ushort Checksum { get; set; } - - public META_PLACEABLE() - { - Key = 0x9AC6CDD7; - } - - public void Read(BinaryReader reader) - { - Key = reader.ReadUInt32(); - HWmf = reader.ReadUInt16(); - var boundingBox = BoundingBox; - boundingBox.Read(reader); - BoundingBox = boundingBox; - Inch = reader.ReadUInt16(); - Reserved = reader.ReadUInt32(); - Checksum = reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(Key); - writer.Write(HWmf); - BoundingBox.Write(writer); - writer.Write(Inch); - writer.Write(Reserved); - writer.Write(CalculateChecksum()); - } - - private ushort CalculateChecksum() - { - ushort checksum = 0; - checksum ^= (ushort)(Key & 0xFFFF); - checksum ^= (ushort)(Key >> 16); - checksum ^= HWmf; - checksum ^= (ushort)BoundingBox.Left; - checksum ^= (ushort)BoundingBox.Top; - checksum ^= (ushort)BoundingBox.Right; - checksum ^= (ushort)BoundingBox.Bottom; - checksum ^= Inch; - checksum ^= (ushort)(Reserved & 0xFFFF); - checksum ^= (ushort)(Reserved >> 16); - return checksum; - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYGON.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYGON.cs deleted file mode 100644 index 25aad11e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYGON.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.IO; -using System.Collections.Generic; - -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_POLYGON : Record - { - public short NumberOfPoints => (short)Points.Count; - public List Points { get; } = new List(); - - public META_POLYGON() - { - Header.RecordFunction = RecordType.META_POLYGON; - } - - public override void Read(BinaryReader reader) - { - short numberOfPoints = reader.ReadInt16(); - for (int i = 0; i < numberOfPoints; i++) - { - short x = reader.ReadInt16(); - short y = reader.ReadInt16(); - Points.Add(new Point(x, y)); - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(NumberOfPoints); - foreach (Point point in Points) - { - writer.Write((short)point.X); - writer.Write((short)point.Y); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYLINE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYLINE.cs deleted file mode 100644 index f60381bf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYLINE.cs +++ /dev/null @@ -1,55 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_POLYLINE record draws a series of line segments by connecting the points in the specified array. - /// - /// - /// 2.3.3.14 META_POLYLINE Record - /// - internal class META_POLYLINE : Record - { - /// - /// Defines the number of points in the array. - /// - public short NumberOfPoints { get; set; } - - /// - /// A NumberOfPoints array of 32-bit PointS Objects, in logical units. - /// - public PointS[] aPoints { get; set; } = Array.Empty(); - - public META_POLYLINE() - { - Header.RecordFunction = RecordType.META_POLYLINE; - } - - public override void Read(BinaryReader reader) - { - NumberOfPoints = reader.ReadInt16(); - aPoints = new PointS[NumberOfPoints]; - for (int i = 0; i < NumberOfPoints; i++) - { - var point = new PointS(); - point.Read(reader); - aPoints[i] = point; - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(NumberOfPoints); - foreach (var point in aPoints) - { - point.Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYPOLYGON.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYPOLYGON.cs deleted file mode 100644 index 3dc25cb1..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_POLYPOLYGON.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.IO; -using System.Collections.Generic; -using System.Drawing; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class META_POLYPOLYGON : Record - { - public short NumberOfPolygons => (short)Polygons.Count; - public List> Polygons { get; } = new List>(); - - public META_POLYPOLYGON() - { - Header.RecordFunction = RecordType.META_POLYPOLYGON; - } - - public override void Read(BinaryReader reader) - { - short numberOfPolygons = reader.ReadInt16(); - - var pointsPerPolygon = new int[numberOfPolygons]; - for (int i = 0; i < numberOfPolygons; i++) - { - pointsPerPolygon[i] = reader.ReadInt16(); - } - - for (int i = 0; i < numberOfPolygons; i++) - { - var polygon = new List(); - for (int j = 0; j < pointsPerPolygon[i]; j++) - { - short x = reader.ReadInt16(); - short y = reader.ReadInt16(); - polygon.Add(new Point(x, y)); - } - Polygons.Add(polygon); - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(NumberOfPolygons); - - foreach (var polygon in Polygons) - { - writer.Write((short)polygon.Count); - } - - foreach (var polygon in Polygons) - { - foreach (Point point in polygon) - { - writer.Write((short)point.X); - writer.Write((short)point.Y); - } - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_RECTANGLE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_RECTANGLE.cs deleted file mode 100644 index a8a154df..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_RECTANGLE.cs +++ /dev/null @@ -1,58 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_RECTANGLE record paints a rectangle. The rectangle is outlined by using the pen and filled by using the brush that are defined in the playback device context. - /// - /// - /// 2.3.3.17 META_RECTANGLE Record - /// - internal class META_RECTANGLE : Record - { - /// - /// Defines the y-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public short BottomRect { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public short RightRect { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public short TopRect { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public short LeftRect { get; set; } - - public META_RECTANGLE() - { - Header.RecordFunction = RecordType.META_RECTANGLE; - } - - public override void Read(BinaryReader reader) - { - BottomRect = reader.ReadInt16(); - RightRect = reader.ReadInt16(); - TopRect = reader.ReadInt16(); - LeftRect = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(BottomRect); - writer.Write(RightRect); - writer.Write(TopRect); - writer.Write(LeftRect); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ROUNDRECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ROUNDRECT.cs deleted file mode 100644 index 3233aa90..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_ROUNDRECT.cs +++ /dev/null @@ -1,73 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_ROUNDRECT record paints a rectangle with rounded corners. - /// The rectangle is outlined using the pen and filled using the brush, as defined in the playback device context. - /// - /// - /// 2.3.3.18 META_ROUNDRECT Record - /// - internal class META_ROUNDRECT : Record - { - /// - /// Defines the height, in logical coordinates, of the ellipse used to draw the rounded corners. - /// - public short Height { get; set; } - - /// - /// Defines the width, in logical coordinates, of the ellipse used to draw the rounded corners. - /// - public short Width { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public short BottomRect { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public short RightRect { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public short TopRect { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public short LeftRect { get; set; } - - public META_ROUNDRECT() - { - Header.RecordFunction = RecordType.META_ROUNDRECT; - } - - public override void Read(BinaryReader reader) - { - Height = reader.ReadInt16(); - Width = reader.ReadInt16(); - BottomRect = reader.ReadInt16(); - RightRect = reader.ReadInt16(); - TopRect = reader.ReadInt16(); - LeftRect = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Height); - writer.Write(Width); - writer.Write(BottomRect); - writer.Write(RightRect); - writer.Write(TopRect); - writer.Write(LeftRect); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETDIBTODEV.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETDIBTODEV.cs deleted file mode 100644 index 3f58ffcc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETDIBTODEV.cs +++ /dev/null @@ -1,101 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_SETDIBTODEV record sets a block of pixels in the playback device context using device-independent color data. - /// - /// - /// 2.3.1.4 META_SETDIBTODEV Record - /// - internal class META_SETDIBTODEV : Record - { - /// - /// Defines whether the Colors field of the DIB contains explicit RGB values or indexes into a palette. - /// - public ColorUsage ColorUsage { get; set; } - - /// - /// Defines the number of scan lines in the source. - /// - public ushort ScanCount { get; set; } - - /// - /// Defines the starting scan line in the source. - /// - public ushort StartScan { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the source rectangle. - /// - public ushort yDib { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the source rectangle. - /// - public ushort xDib { get; set; } - - /// - /// Defines the height, in logical units, of the source and destination rectangles. - /// - public ushort Height { get; set; } - - /// - /// Defines the width, in logical units, of the source and destination rectangles. - /// - public ushort Width { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public ushort yDest { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public ushort xDest { get; set; } - - /// - /// A variable-sized DeviceIndependentBitmap Object (section 2.2.2.9) that is the source of the color data. - /// - public DeviceIndependentBitmap DIB { get; set; } = new DeviceIndependentBitmap(); - - public META_SETDIBTODEV() - { - Header.RecordFunction = RecordType.META_SETDIBTODEV; - } - - public override void Read(BinaryReader reader) - { - ColorUsage = (ColorUsage)reader.ReadUInt16(); - ScanCount = reader.ReadUInt16(); - StartScan = reader.ReadUInt16(); - yDib = reader.ReadUInt16(); - xDib = reader.ReadUInt16(); - Height = reader.ReadUInt16(); - Width = reader.ReadUInt16(); - yDest = reader.ReadUInt16(); - xDest = reader.ReadUInt16(); - DIB.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)ColorUsage); - writer.Write(ScanCount); - writer.Write(StartScan); - writer.Write(yDib); - writer.Write(xDib); - writer.Write(Height); - writer.Write(Width); - writer.Write(yDest); - writer.Write(xDest); - DIB.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETPIXEL.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETPIXEL.cs deleted file mode 100644 index 6fbeda7c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_SETPIXEL.cs +++ /dev/null @@ -1,54 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_SETPIXEL record sets the pixel at the specified coordinates to the specified color. - /// - /// - /// 2.3.3.19 META_SETPIXEL Record - /// - internal class META_SETPIXEL : Record - { - /// - /// A ColorRef Object (section 2.2.2.8) that defines the color value. - /// - public ColorRef ColorRef { get; set; } = new(); - - /// - /// Defines the y-coordinate, in logical units, of the point to be set. - /// - public short Y { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the point to be set. - /// - public short X { get; set; } - - public META_SETPIXEL() - { - Header.RecordFunction = RecordType.META_SETPIXEL; - } - - public override void Read(BinaryReader reader) - { - var colorRef = ColorRef; - colorRef.Read(reader); - ColorRef = colorRef; - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - ColorRef.Write(writer); - writer.Write(Y); - writer.Write(X); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHBLT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHBLT.cs deleted file mode 100644 index 2e1a1213..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHBLT.cs +++ /dev/null @@ -1,113 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// specifies the transfer of a block of pixels according to a raster operation, with possible expansion or contraction. - /// - /// - /// 2.3.1.5 META_STRETCHBLT Record - /// - internal class META_STRETCHBLT : Record - { - /// - /// Defines how the source pixels, the current brush in the playback device context, and the destination pixels are to be combined to form the new image. - /// - public TernaryRasterOperation RasterOperation { get; set; } - - /// - /// Defines the height, in logical units, of the source rectangle. - /// - public short SrcHeight { get; set; } - - /// - /// Defines the width, in logical units, of the source rectangle. - /// - public short SrcWidth { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short YSrc { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short XSrc { get; set; } - - /// - /// Defines the height, in logical units, of the destination rectangle. - /// - public short DestHeight { get; set; } - - /// - /// Defines the width, in logical units, of the destination rectangle. - /// - public short DestWidth { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short YDest { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short XDest { get; set; } - - /// - /// Defines source image content. This object MUST be specified, even if the raster operation does not require a source. - /// - public Bitmap16? Target { get; set; } - - public META_STRETCHBLT() - { - Header.RecordFunction = RecordType.META_STRETCHBLT; - } - - public override void Read(BinaryReader reader) - { - long endPosition = reader.BaseStream.Position + (Header.RecordSize * 2) - 6; - - RasterOperation = (TernaryRasterOperation)reader.ReadUInt32(); - SrcHeight = reader.ReadInt16(); - SrcWidth = reader.ReadInt16(); - YSrc = reader.ReadInt16(); - XSrc = reader.ReadInt16(); - DestHeight = reader.ReadInt16(); - DestWidth = reader.ReadInt16(); - YDest = reader.ReadInt16(); - XDest = reader.ReadInt16(); - - if (reader.BaseStream.Position < endPosition) - { - var target = new Bitmap16(); - target.Read(reader); - Target = target; - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((uint)RasterOperation); - writer.Write(SrcHeight); - writer.Write(SrcWidth); - writer.Write(YSrc); - writer.Write(XSrc); - writer.Write(DestHeight); - writer.Write(DestWidth); - writer.Write(YDest); - writer.Write(XDest); - - if (Target.HasValue) - { - Target.Value.Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHDIB.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHDIB.cs deleted file mode 100644 index 4b531737..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_STRETCHDIB.cs +++ /dev/null @@ -1,114 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// Specifies the transfer of color data from a block of pixels in device-independent format according to a raster operation, with possible expansion or contraction. - /// - /// - /// 2.3.1.6 META_STRETCHDIB Record - /// - internal class META_STRETCHDIB : Record - { - /// - /// Defines how the source pixels, the current brush in the playback device context, and the destination pixels are to be combined to form the new image. - /// - public TernaryRasterOperation RasterOperation { get; set; } - - /// - /// Defines the height, in logical units, of the source rectangle. - /// - public short SrcHeight { get; set; } - - /// - /// Defines the width, in logical units, of the source rectangle. - /// - public short SrcWidth { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short YSrc { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the source rectangle. - /// - public short XSrc { get; set; } - - /// - /// Defines the height, in logical units, of the destination rectangle. - /// - public short DestHeight { get; set; } - - /// - /// Defines the width, in logical units, of the destination rectangle. - /// - public short DestWidth { get; set; } - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short YDest { get; set; } - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the destination rectangle. - /// - public short XDest { get; set; } - - /// - /// Defines source image content. This object MUST be specified, even if the raster operation does not require a source. - /// - public DeviceIndependentBitmap Target { get; set; } - - public META_STRETCHDIB() - { - Header.RecordFunction = RecordType.META_STRETCHDIB; - Target = new DeviceIndependentBitmap(); - } - - public override void Read(BinaryReader reader) - { - long endPosition = reader.BaseStream.Position + (Header.RecordSize * 2) - 6; - - RasterOperation = (TernaryRasterOperation)reader.ReadUInt32(); - SrcHeight = reader.ReadInt16(); - SrcWidth = reader.ReadInt16(); - YSrc = reader.ReadInt16(); - XSrc = reader.ReadInt16(); - DestHeight = reader.ReadInt16(); - DestWidth = reader.ReadInt16(); - YDest = reader.ReadInt16(); - XDest = reader.ReadInt16(); - - if (reader.BaseStream.Position < endPosition) - { - Target.Read(reader); - } - } - - public override void Write(BinaryWriter writer) - { - using var payloadStream = new MemoryStream(); - using var payloadWriter = new BinaryWriter(payloadStream); - - payloadWriter.Write((uint)RasterOperation); - payloadWriter.Write(SrcHeight); - payloadWriter.Write(SrcWidth); - payloadWriter.Write(YSrc); - payloadWriter.Write(XSrc); - payloadWriter.Write(DestHeight); - payloadWriter.Write(DestWidth); - payloadWriter.Write(YDest); - payloadWriter.Write(XDest); - Target.Write(payloadWriter); - - Header.RecordSize = (uint)((payloadStream.Length + 6) / 2); - Header.Write(writer); - writer.Write(payloadStream.ToArray()); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_TEXTOUT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_TEXTOUT.cs deleted file mode 100644 index 3de24697..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/META_TEXTOUT.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using System.IO; - - /// - /// The META_TEXTOUT record outputs a character string at the specified location by using the font, background color, and text color that are defined in the playback device context. - /// - /// - /// 2.3.3.20 META_TEXTOUT Record - /// - internal class META_TEXTOUT : Record - { - /// - /// Defines the length of the string, in bytes, pointed to by String. - /// - public short StringLength; - - /// - /// The size of this field MUST be a multiple of two. If StringLength is an odd number, - /// then this field MUST be of a size greater than or equal to StringLength + 1. - /// A variable-length string that specifies the text to be drawn. - /// The string does not need to be null-terminated, because StringLength specifies the length of the string. - /// The string is written at the location specified by the XStart and YStart fields. - /// - public string String = string.Empty; - - public META_TEXTOUT() - { - Header.RecordFunction = RecordType.META_TEXTOUT; - } - - /// - /// Defines the vertical (y-axis) coordinate, in logical units, of the point where drawing is to start. - /// - public short YStart; - - /// - /// Defines the horizontal (x-axis) coordinate, in logical units, of the point where drawing is to start. - /// - public short XStart; - - public override void Read(BinaryReader reader) - { - this.StringLength = reader.ReadInt16(); - this.String = Encoding.ASCII.GetString(reader.ReadBytes(this.StringLength)); - this.YStart = reader.ReadInt16(); - this.XStart = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(this.StringLength); - writer.Write(Encoding.ASCII.GetBytes(this.String)); - writer.Write(this.YStart); - writer.Write(this.XStart); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/MetaHeader.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/MetaHeader.cs deleted file mode 100644 index c269558a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/MetaHeader.cs +++ /dev/null @@ -1,80 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_HEADER record is the first record in a standard (nonplaceable) WMF metafile. - /// - /// - /// 2.3.2.2 META_HEADER Record - /// - internal class MetaHeader - { - /// - /// Defines the type of metafile. - /// - public MetafileType Type; - - /// - /// Defines the number of 16-bit words in the header. - /// - public ushort HeaderSize; - - /// - /// Defines the metafile version. - /// - public MetafileVersion Version; - - /// - /// Defines the low-order word of the number of 16-bit words in the entire metafile. - /// - public ushort SizeLow; - - /// - /// Defines the high-order word of the number of 16-bit words in the entire metafile. - /// - public ushort SizeHigh; - - /// - /// Specifies the number of graphics objects that are defined in the entire metafile. These objects include brushes, pens, and the other objects specified in section 2.2.1. - /// - public ushort NumberOfObjects; - - /// - /// Specifies the size of the largest record used in the metafile (in 16-bit elements). - /// - public uint MaxRecord; - - /// - /// A 16-bit unsigned integer that is not used. It SHOULD be 0x0000. - /// - public ushort NumberOfMembers; - - public void Read(BinaryReader reader) - { - this.Type = (MetafileType)reader.ReadUInt16(); - this.HeaderSize = reader.ReadUInt16(); - this.Version = (MetafileVersion)reader.ReadUInt16(); - this.SizeLow = reader.ReadUInt16(); - this.SizeHigh = reader.ReadUInt16(); - this.NumberOfObjects = reader.ReadUInt16(); - this.MaxRecord = reader.ReadUInt32(); - this.NumberOfMembers = reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write((ushort)this.Type); - writer.Write(this.HeaderSize); - writer.Write((ushort)this.Version); - writer.Write(this.SizeLow); - writer.Write(this.SizeHigh); - writer.Write(this.NumberOfObjects); - writer.Write(this.MaxRecord); - writer.Write(this.NumberOfMembers); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEFONTINDIRECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEFONTINDIRECT.cs deleted file mode 100644 index 5dce82e9..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEFONTINDIRECT.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; -using MiniSoftware.Drawing.Metafile.Wmf.Objects; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - - /// - /// The META_CREATEFONTINDIRECT record creates a Font Object (section 2.2.1.2). - /// - /// - /// 2.3.4.2 META_CREATEFONTINDIRECT Record - /// - internal class META_CREATEFONTINDIRECT : Record - { - /// - /// Font Object data that defines the font to create. - /// - public Objects.Font Font = new Objects.Font(); - - public META_CREATEFONTINDIRECT() - { - Header.RecordFunction = RecordType.META_CREATEFONTINDIRECT; - } - - public override void Read(System.IO.BinaryReader reader) - { - Font.Read(reader); - } - - public override void Write(System.IO.BinaryWriter writer) - { - base.Write(writer); - Font.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPALETTE.cs deleted file mode 100644 index cf63ef68..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPALETTE.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_CREATEPALETTE record creates a Palette Object (section 2.2.1.3). - /// - /// - /// 2.3.4.3 META_CREATEPALETTE Record - /// - internal class META_CREATEPALETTE : Record - { - /// - /// Palette Object data that defines the palette to create. The Start field in the Palette Object MUST be set to 0x0300. - /// - public Palette Palette = new Palette(); - - public META_CREATEPALETTE() - { - Header.RecordFunction = RecordType.META_CREATEPALETTE; - } - - public override void Read(System.IO.BinaryReader reader) - { - Palette.Read(reader); - } - - public override void Write(System.IO.BinaryWriter writer) - { - base.Write(writer); - Palette.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPATTERNBRUSH.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPATTERNBRUSH.cs deleted file mode 100644 index 7d9e1902..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPATTERNBRUSH.cs +++ /dev/null @@ -1,58 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_CREATEPATTERNBRUSH record creates a brush object with a pattern specified by a bitmap. - /// - /// - /// 2.3.4.4 META_CREATEPATTERNBRUSH Record - /// - internal class META_CREATEPATTERNBRUSH : Record - { - /// - /// A partial Bitmap16 object (section 2.2.2.1), which defines parameters for the bitmap that specifies the pattern for the brush. - /// Fields not described below are specified in section 2.2.2.1. - /// - public Bitmap16 Bitmap16 = new Bitmap16(); - - public int PatternLength - { - get - { - return (((this.Bitmap16.Width * this.Bitmap16.BitsPixel + 15) >> 4) << 1) * this.Bitmap16.Height; - } - } - - /// - /// A variable-length array of bytes that defines the bitmap pixel data that composes the brush pattern. - /// The length of this field, in bytes, can be computed from bitmap parameters as follows. - /// - public byte[] Pattern = System.Array.Empty(); - - public META_CREATEPATTERNBRUSH() - { - Header.RecordFunction = RecordType.META_CREATEPATTERNBRUSH; - } - - public override void Read(BinaryReader reader) - { - this.Bitmap16.Read(reader); - reader.ReadBytes(18); - this.Pattern = reader.ReadBytes(this.PatternLength); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - this.Bitmap16.Write(writer); - writer.Write(new byte[18]); // Write 18 reserved bytes - writer.Write(this.Pattern); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPENINDIRECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPENINDIRECT.cs deleted file mode 100644 index 296c724e..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEPENINDIRECT.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_CREATEPENINDIRECT record creates a Pen Object (section 2.2.1.4). - /// - /// - /// 2.3.4.5 META_CREATEPENINDIRECT Record - /// - internal class META_CREATEPENINDIRECT : Record - { - /// - /// Pen Object data that defines the pen to create. - /// - public Pen Pen = new Pen(); - - public META_CREATEPENINDIRECT() - { - Header.RecordFunction = RecordType.META_CREATEPENINDIRECT; - } - - public override void Read(System.IO.BinaryReader reader) - { - Pen.Read(reader); - } - - public override void Write(System.IO.BinaryWriter writer) - { - base.Write(writer); - Pen.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEREGION.cs deleted file mode 100644 index ad4f3951..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_CREATEREGION.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_CREATEREGION record creates a Region Object (section 2.2.1.5). - /// - /// - /// 2.3.4.6 META_CREATEREGION Record - /// - internal class META_CREATEREGION : Record - { - /// - /// Region Object data that defines the region to create. - /// - public Region Region = new Region(); - - public META_CREATEREGION() - { - Header.RecordFunction = RecordType.META_CREATEREGION; - } - - public override void Read(System.IO.BinaryReader reader) - { - Region.Read(reader); - } - - public override void Write(System.IO.BinaryWriter writer) - { - base.Write(writer); - Region.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DELETEOBJECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DELETEOBJECT.cs deleted file mode 100644 index 54850bd4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DELETEOBJECT.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - /// - /// The META_DELETEOBJECT record deletes an object, including Bitmap16, Brush, DeviceIndependentBitmap, Font, Palette, Pen, and Region. - /// After the object is deleted, its index in the WMF Object Table is no longer valid but is available to be reused. - /// - /// - /// 2.3.4.7 META_DELETEOBJECT Record - /// - internal class META_DELETEOBJECT : Record - { - /// - /// A 16-bit unsigned integer used to index into the WMF Object Table to get the object to be deleted. - /// - public ushort ObjectIndex; - - public override void Read(BinaryReader reader) - { - this.ObjectIndex = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(this.ObjectIndex); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DIBCREATEPATTERNBRUSH.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DIBCREATEPATTERNBRUSH.cs deleted file mode 100644 index 03184d00..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_DIBCREATEPATTERNBRUSH.cs +++ /dev/null @@ -1,50 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System; - using System.IO; - - /// - /// The META_DIBCREATEPATTERNBRUSH record creates a Brush Object (section 2.2.1.1) with a pattern specified by a DeviceIndependentBitmap (DIB) Object (section 2.2.2.9). - /// - /// - /// 2.3.4.8 META_DIBCREATEPATTERNBRUSH Record - /// - internal class META_DIBCREATEPATTERNBRUSH : Record - { - /// - /// Defines the brush style. The legal values for this field are defined as follows: if the value is not BS_PATTERN, BS_DIBPATTERNPT MUST be assumed. - /// - public BrushStyle Style; - - /// - /// Defines whether the Colors field of a DIB Object contains explicit RGB values, or indexes into a palette. - /// - public ColorUsage ColorUsage; - - public byte[] Target = Array.Empty(); - - public META_DIBCREATEPATTERNBRUSH() - { - Header.RecordFunction = RecordType.META_DIBCREATEPATTERNBRUSH; - } - - public override void Read(BinaryReader reader) - { - this.Style = (BrushStyle)reader.ReadUInt16(); - this.ColorUsage = (ColorUsage)reader.ReadUInt16(); - - this.Target = reader.ReadBytes(Convert.ToInt32(this.Header.RecordSize * 2) - 10); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)this.Style); - writer.Write((ushort)this.ColorUsage); - writer.Write(this.Target); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTCLIPREGION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTCLIPREGION.cs deleted file mode 100644 index 515ba0e1..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTCLIPREGION.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - /// - /// The META_SELECTCLIPREGION record specifies a Region Object (section 2.2.1.5) to be the current clipping region. - /// - /// - /// 2.3.4.9 META_SELECTCLIPREGION Record - /// - internal class META_SELECTCLIPREGION : Record - { - /// - /// A 16-bit unsigned integer used to index into the WMF Object Table to get the region to be inverted. - /// - public ushort Region; - - public override void Read(BinaryReader reader) - { - this.Region = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(this.Region); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTOBJECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTOBJECT.cs deleted file mode 100644 index 5bb738e5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTOBJECT.cs +++ /dev/null @@ -1,34 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - /// - /// The META_SELECTOBJECT record specifies a graphics object for the playback device context. - /// The new object replaces the previous object of the same type, unless if the previous object is a palette object. If the previous object is a palette object, then the META_SELECTPALETTE record must be used instead of the META_SELECTOBJECT record, as the META_SELECTOBJECT record does not support replacing the palette object type. - /// - internal class META_SELECTOBJECT : Record - { - /// - /// A 16-bit unsigned integer used to index into the WMF Object Table to get the object to be selected. - /// - public ushort ObjectIndex; - - public META_SELECTOBJECT() - { - Header.RecordFunction = RecordType.META_SELECTOBJECT; - } - - public override void Read(BinaryReader reader) - { - this.ObjectIndex = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - writer.Write(this.ObjectIndex); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTPALETTE.cs deleted file mode 100644 index 0888d0c4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/META_SELECTPALETTE.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - - /// - /// The META_SELECTPALETTE record defines the current logical palette with a specified Palette Object. - /// - /// - /// 2.3.4.11 META_SELECTPALETTE Record - /// - internal class META_SELECTPALETTE : Record - { - /// - /// A 16-bit unsigned integer used to index into the WMF Object Table to get the Palette Object to be selected. - /// - public ushort Palette; - - public override void Read(BinaryReader reader) - { - this.Palette = reader.ReadUInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/MetaCreatebrushindirect.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/MetaCreatebrushindirect.cs deleted file mode 100644 index 236166b0..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/ObjectRecordTypes/MetaCreatebrushindirect.cs +++ /dev/null @@ -1,46 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_CREATEBRUSHINDIRECT record creates a Brush Object (section 2.2.1.1) from a LogBrush Object (section 2.2.2.10). - /// - /// - /// 2.3.4.1 META_CREATEBRUSHINDIRECT Record - /// - internal class MetaCreatebrushindirect : Record - { - /// - /// LogBrush Object data that defines the brush to create. - /// The BrushStyle field specified in the LogBrush Object SHOULD be BS_SOLID, BS_NULL, or BS_HATCHED; otherwise, a default Brush Object MAY be created. - /// See the following table for details. - /// - public LogBrush LogBrush { get; set; } = new LogBrush(); - - public MetaCreatebrushindirect() - { - Header.RecordFunction = RecordType.META_CREATEBRUSHINDIRECT; - } - - public override void Read(BinaryReader reader) - { - LogBrush.BrushStyle = (BrushStyle)reader.ReadUInt16(); - var color = new ColorRef(); - color.Read(reader); - LogBrush.ColorRef = color; - LogBrush.BrushHatch = (HatchStyle)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)LogBrush.BrushStyle); - LogBrush.ColorRef.Write(writer); - writer.Write((ushort)(LogBrush.BrushHatch ?? 0)); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/Record.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/Record.cs deleted file mode 100644 index 5efc7129..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/Record.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.IO; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - internal class Record - { - public RecordHeader Header; - - public virtual void Read(BinaryReader reader) - { - } - - public virtual void Write(BinaryWriter writer) - { - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/RecordHeader.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/RecordHeader.cs deleted file mode 100644 index 813cd138..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/RecordHeader.cs +++ /dev/null @@ -1,38 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal struct RecordHeader - { - /// - /// A 32-bit unsigned integer that defines the number of 16-bit WORDs in the record. - /// - public uint RecordSize; - - /// - /// A 16-bit unsigned integer that defines the type of this record. - /// The low-order byte MUST match the low-order byte of one of the values in the RecordType Enumeration. - /// - public RecordType RecordFunction; - - public void Read(BinaryReader reader) - { - this.RecordSize = reader.ReadUInt32(); - this.RecordFunction = (RecordType)reader.ReadUInt16(); - } - - public void Write(BinaryWriter writer) - { - writer.Write(this.RecordSize); - writer.Write((ushort)this.RecordFunction); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_ANIMATEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_ANIMATEPALETTE.cs deleted file mode 100644 index 54301fa4..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_ANIMATEPALETTE.cs +++ /dev/null @@ -1,39 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - /// - /// The META_ANIMATEPALETTE record redefines entries in the logical palette that is defined in the playback device context with the specified Palette object (section 2.2.1.3). - /// - /// - /// 2.3.5.1 META_ANIMATEPALETTE Record - /// - internal class META_ANIMATEPALETTE : Record - { - /// - /// A variable-sized Palette object that specifies a logical palette. - /// - public Palette Palette { get; set; } = new Palette(); - - public META_ANIMATEPALETTE() - { - Header.RecordFunction = RecordType.META_ANIMATEPALETTE; - } - - public override void Read(BinaryReader reader) - { - Palette.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - Palette.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_EXCLUDECLIPRECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_EXCLUDECLIPRECT.cs deleted file mode 100644 index be45de93..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_EXCLUDECLIPRECT.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - - /// - /// The META_EXCLUDECLIPRECT record sets the clipping region in the playback device context to the existing clipping region minus the specified rectangle. - /// - /// - /// 2.3.5.2 META_EXCLUDECLIPRECT Record - /// - internal class META_EXCLUDECLIPRECT : Record - { - /// - /// Defines the y-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public ushort Bottom; - - /// - /// Defines the x-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public ushort Right; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public ushort Top; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public ushort Left; - - public override void Read(BinaryReader reader) - { - this.Bottom = reader.ReadUInt16(); - this.Right = reader.ReadUInt16(); - this.Top = reader.ReadUInt16(); - this.Left = reader.ReadUInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_INTERSECTCLIPRECT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_INTERSECTCLIPRECT.cs deleted file mode 100644 index 9c5637ac..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_INTERSECTCLIPRECT.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - - /// - /// The META_INTERSECTCLIPRECT record sets the clipping region in the playback device context to the intersection of the existing clipping region and the specified rectangle. - /// - /// - /// 2.3.5.3 META_INTERSECTCLIPRECT Record - /// - internal class META_INTERSECTCLIPRECT : Record - { - /// - /// Defines the y-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public ushort Bottom; - - /// - /// Defines the x-coordinate, in logical units, of the lower-right corner of the rectangle. - /// - public ushort Right; - - /// - /// Defines the y-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public ushort Top; - - /// - /// Defines the x-coordinate, in logical units, of the upper-left corner of the rectangle. - /// - public ushort Left; - - public override void Read(BinaryReader reader) - { - this.Bottom = reader.ReadUInt16(); - this.Right = reader.ReadUInt16(); - this.Top = reader.ReadUInt16(); - this.Left = reader.ReadUInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_MOVETO.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_MOVETO.cs deleted file mode 100644 index 9b58b0d3..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_MOVETO.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - /// - /// The META_MOVETO record sets the output position in the playback device context to a specified point. - /// - /// - /// 2.3.5.4 META_MOVETO Record - /// - internal class META_MOVETO : Record - { - /// - /// Defines the y-coordinate, in logical units. - /// - public short Y; - - /// - /// Defines the x-coordinate, in logical units. - /// - public short X; - - public override void Read(BinaryReader reader) - { - this.Y = reader.ReadInt16(); - this.X = reader.ReadInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETCLIPRGN.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETCLIPRGN.cs deleted file mode 100644 index 71b83f91..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETCLIPRGN.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - /// - /// The META_OFFSETCLIPRGN record moves the clipping region in the playback device context by the specified offsets. - /// - /// - /// 2.3.5.5 META_OFFSETCLIPRGN Record - /// - internal class META_OFFSETCLIPRGN : Record - { - /// - /// Defines the number of logical units to move up or down. - /// - public short YOffset; - - /// - /// Defines the number of logical units to move left or right. - /// - public short XOffset; - - public override void Read(BinaryReader reader) - { - this.YOffset = reader.ReadInt16(); - this.XOffset = reader.ReadInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETVIEWPORTORG.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETVIEWPORTORG.cs deleted file mode 100644 index 3d962835..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETVIEWPORTORG.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - /// - /// The META_OFFSETVIEWPORTORG record moves the viewport origin in the playback device context by specified horizontal and vertical offsets. - /// - /// - /// 2.3.5.6 META_OFFSETVIEWPORTORG Record - /// - internal class META_OFFSETVIEWPORTORG : Record - { - /// - /// Defines the vertical offset, in device units. - /// - public short YOffset; - - /// - /// Defines the horizontal offset, in device units. - /// - public short XOffset; - - public override void Read(BinaryReader reader) - { - this.YOffset = reader.ReadInt16(); - this.XOffset = reader.ReadInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETWINDOWORG.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETWINDOWORG.cs deleted file mode 100644 index 2e7aae98..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_OFFSETWINDOWORG.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - /// - /// The META_OFFSETWINDOWORG record moves the output window origin in the playback device context by specified horizontal and vertical offsets. - /// - /// - /// 2.3.5.7 META_OFFSETWINDOWORG Record - /// - internal class META_OFFSETWINDOWORG : Record - { - /// - /// Defines the vertical offset, in device units. - /// - public short YOffset; - - /// - /// Defines the horizontal offset, in device units. - /// - public short XOffset; - - public override void Read(BinaryReader reader) - { - this.YOffset = reader.ReadInt16(); - this.XOffset = reader.ReadInt16(); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_REALIZEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_REALIZEPALETTE.cs deleted file mode 100644 index ec6be5c2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_REALIZEPALETTE.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - /// - /// The META_REALIZEPALETTE record maps entries from the logical palette that is defined in the playback device context to the system palette. - /// - /// - /// 2.3.5.8 META_REALIZEPALETTE Record - /// - internal class META_REALIZEPALETTE :Record - { - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESIZEPALETTE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESIZEPALETTE.cs deleted file mode 100644 index 30ae70bb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESIZEPALETTE.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - /// - /// The META_RESIZEPALETTE record redefines the size of the logical palette that is defined in the playback device context. - /// - /// - /// 2.3.5.9 META_RESIZEPALETTE Record - /// - internal class META_RESIZEPALETTE : Record - { - /// - /// Defines the number of entries in the logical palette. - /// - public ushort NumberOfEntries; - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESTOREDC.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESTOREDC.cs deleted file mode 100644 index 1981fcaf..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_RESTOREDC.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_RESTOREDC : Record - { - public short SavedDC; - - public META_RESTOREDC() - { - Header.RecordFunction = RecordType.META_RESTOREDC; - } - - public override void Read(BinaryReader reader) - { - SavedDC = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(SavedDC); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SAVEDC.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SAVEDC.cs deleted file mode 100644 index b0c0d372..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SAVEDC.cs +++ /dev/null @@ -1,25 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SAVEDC : Record - { - public META_SAVEDC() - { - Header.RecordFunction = RecordType.META_SAVEDC; - } - - public override void Read(BinaryReader reader) - { - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEVIEWPORTEXT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEVIEWPORTEXT.cs deleted file mode 100644 index e99559a5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEVIEWPORTEXT.cs +++ /dev/null @@ -1,41 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SCALEVIEWPORTEXT : Record - { - public short YNumerator; - - public short YDenominator; - - public short XNumerator; - - public short XDenominator; - - public META_SCALEVIEWPORTEXT() - { - Header.RecordFunction = RecordType.META_SCALEVIEWPORTEXT; - } - - public override void Read(BinaryReader reader) - { - YNumerator = reader.ReadInt16(); - YDenominator = reader.ReadInt16(); - XNumerator = reader.ReadInt16(); - XDenominator = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(YNumerator); - writer.Write(YDenominator); - writer.Write(XNumerator); - writer.Write(XDenominator); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEWINDOWEXT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEWINDOWEXT.cs deleted file mode 100644 index 2b25f1f2..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SCALEWINDOWEXT.cs +++ /dev/null @@ -1,40 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SCALEWINDOWEXT : Record - { - public short YNumerator; - - public short YDenominator; - - public short XNumerator; - - public short XDenominator; - - public META_SCALEWINDOWEXT() - { - Header.RecordFunction = RecordType.META_SCALEWINDOWEXT; - } - - public override void Read(BinaryReader reader) - { - YNumerator = reader.ReadInt16(); - YDenominator = reader.ReadInt16(); - XNumerator = reader.ReadInt16(); - XDenominator = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(YNumerator); - writer.Write(YDenominator); - writer.Write(XNumerator); - writer.Write(XDenominator); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKCOLOR.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKCOLOR.cs deleted file mode 100644 index 9ef83f32..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKCOLOR.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class META_SETBKCOLOR : Record - { - public ColorRef Color; - - public META_SETBKCOLOR() - { - Header.RecordFunction = RecordType.META_SETBKCOLOR; - } - - public override void Read(BinaryReader reader) - { - Color.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - Color.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKMODE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKMODE.cs deleted file mode 100644 index fce8e306..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETBKMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SETBKMODE : Record - { - public MixMode BackgroundMode; - - public META_SETBKMODE() - { - Header.RecordFunction = RecordType.META_SETBKMODE; - } - - public override void Read(BinaryReader reader) - { - BackgroundMode = (MixMode)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)BackgroundMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETLAYOUT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETLAYOUT.cs deleted file mode 100644 index ab508676..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETLAYOUT.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETLAYOUT : Record - { - public Layout Layout; - - public ushort Reserved; - - public META_SETLAYOUT() - { - Header.RecordFunction = RecordType.META_SETLAYOUT; - } - - public override void Read(BinaryReader reader) - { - Layout = (Layout)reader.ReadUInt16(); - Reserved = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)Layout); - writer.Write(Reserved); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPMODE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPMODE.cs deleted file mode 100644 index 3b878581..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - - internal class META_SETMAPMODE : Record - { - public MapMode MapMode; - - public META_SETMAPMODE() - { - Header.RecordFunction = RecordType.META_SETMAPMODE; - } - - public override void Read(BinaryReader reader) - { - MapMode = (MapMode)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)MapMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPPERFLAGS.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPPERFLAGS.cs deleted file mode 100644 index 109089da..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETMAPPERFLAGS.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SETMAPPERFLAGS : Record - { - public uint MapperValues; - - public META_SETMAPPERFLAGS() - { - Header.RecordFunction = RecordType.META_SETMAPPERFLAGS; - } - - public override void Read(BinaryReader reader) - { - MapperValues = reader.ReadUInt32(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(MapperValues); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPALENTRIES.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPALENTRIES.cs deleted file mode 100644 index b95481e6..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPALENTRIES.cs +++ /dev/null @@ -1,48 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System; - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class META_SETPALENTRIES : Record - { - public ushort Start; - - public ushort NumberOfEntries; - - public PaletteEntry[] PaletteEntries { get; set; } = Array.Empty(); - - public META_SETPALENTRIES() - { - Header.RecordFunction = RecordType.META_SETPALENTRIES; - } - - public override void Read(BinaryReader reader) - { - Start = reader.ReadUInt16(); - NumberOfEntries = reader.ReadUInt16(); - PaletteEntries = new PaletteEntry[NumberOfEntries]; - for (int i = 0; i < NumberOfEntries; i++) - { - var entry = new PaletteEntry(); - entry.Read(reader); - PaletteEntries[i] = entry; - } - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - ushort entryCount = NumberOfEntries == 0 ? (ushort)PaletteEntries.Length : NumberOfEntries; - writer.Write(Start); - writer.Write(entryCount); - for (int i = 0; i < entryCount; i++) - { - PaletteEntries[i].Write(writer); - } - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPOLYFILLMODE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPOLYFILLMODE.cs deleted file mode 100644 index 31982f8d..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETPOLYFILLMODE.cs +++ /dev/null @@ -1,28 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SETPOLYFILLMODE : Record - { - public PolyFillMode PolyFillMode; - - public META_SETPOLYFILLMODE() - { - Header.RecordFunction = RecordType.META_SETPOLYFILLMODE; - } - - public override void Read(BinaryReader reader) - { - PolyFillMode = (PolyFillMode)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)PolyFillMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETRELABS.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETRELABS.cs deleted file mode 100644 index 3ec96cc5..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETRELABS.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETRELABS : Record - { - public ushort Relative; - - public META_SETRELABS() - { - Header.RecordFunction = RecordType.META_SETRELABS; - } - - public override void Read(BinaryReader reader) - { - Relative = reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Relative); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETROP2.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETROP2.cs deleted file mode 100644 index 9ad6a696..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETROP2.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETROP2 : Record - { - public BinaryRasterOperation DrawMode; - - public META_SETROP2() - { - Header.RecordFunction = RecordType.META_SETROP2; - } - - public override void Read(BinaryReader reader) - { - DrawMode = (BinaryRasterOperation)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)DrawMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETSTRETCHBLTMODE.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETSTRETCHBLTMODE.cs deleted file mode 100644 index 09051901..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETSTRETCHBLTMODE.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETSTRETCHBLTMODE : Record - { - public StretchMode StretchMode; - - public META_SETSTRETCHBLTMODE() - { - Header.RecordFunction = RecordType.META_SETSTRETCHBLTMODE; - } - - public override void Read(BinaryReader reader) - { - StretchMode = (StretchMode)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)StretchMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTALIGN.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTALIGN.cs deleted file mode 100644 index 16decb62..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTALIGN.cs +++ /dev/null @@ -1,30 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Flags; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETTEXTALIGN : Record - { - public TextAlignmentMode TextAlignmentMode; - - public META_SETTEXTALIGN() - { - Header.RecordFunction = RecordType.META_SETTEXTALIGN; - } - - public override void Read(BinaryReader reader) - { - TextAlignmentMode = (TextAlignmentMode)reader.ReadUInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write((ushort)TextAlignmentMode); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCHAREXTRA.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCHAREXTRA.cs deleted file mode 100644 index cb81bbcb..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCHAREXTRA.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETTEXTCHAREXTRA : Record - { - public short CharacterExtra; - - public META_SETTEXTCHAREXTRA() - { - Header.RecordFunction = RecordType.META_SETTEXTCHAREXTRA; - } - - public override void Read(BinaryReader reader) - { - CharacterExtra = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(CharacterExtra); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCOLOR.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCOLOR.cs deleted file mode 100644 index e894be5c..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTCOLOR.cs +++ /dev/null @@ -1,29 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Objects; - - internal class META_SETTEXTCOLOR : Record - { - public ColorRef Color; - - public META_SETTEXTCOLOR() - { - Header.RecordFunction = RecordType.META_SETTEXTCOLOR; - } - - public override void Read(BinaryReader reader) - { - Color.Read(reader); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - Color.Write(writer); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTJUSTIFICATION.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTJUSTIFICATION.cs deleted file mode 100644 index 8fbe5f27..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETTEXTJUSTIFICATION.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETTEXTJUSTIFICATION : Record - { - public short BreakExtra; - - public short BreakCount; - - public META_SETTEXTJUSTIFICATION() - { - Header.RecordFunction = RecordType.META_SETTEXTJUSTIFICATION; - } - - public override void Read(BinaryReader reader) - { - BreakExtra = reader.ReadInt16(); - BreakCount = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(BreakExtra); - writer.Write(BreakCount); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTEXT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTEXT.cs deleted file mode 100644 index 1299a293..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTEXT.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETVIEWPORTEXT : Record - { - public short Y; - - public short X; - - public META_SETVIEWPORTEXT() - { - Header.RecordFunction = RecordType.META_SETVIEWPORTEXT; - } - - public override void Read(BinaryReader reader) - { - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Y); - writer.Write(X); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTORG.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTORG.cs deleted file mode 100644 index 72ec7fbc..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETVIEWPORTORG.cs +++ /dev/null @@ -1,33 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using System.IO; - - internal class META_SETVIEWPORTORG : Record - { - public short Y; - - public short X; - - public META_SETVIEWPORTORG() - { - Header.RecordFunction = RecordType.META_SETVIEWPORTORG; - } - - public override void Read(BinaryReader reader) - { - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Y); - writer.Write(X); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWEXT.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWEXT.cs deleted file mode 100644 index 44a5b0d7..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWEXT.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SETWINDOWEXT : Record - { - public short Y; - - public short X; - - public META_SETWINDOWEXT() - { - Header.RecordFunction = RecordType.META_SETWINDOWEXT; - } - - public override void Read(BinaryReader reader) - { - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Y); - writer.Write(X); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWORG.cs b/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWORG.cs deleted file mode 100644 index cf50e39a..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/Records/StateRecordTypes/META_SETWINDOWORG.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Metafile.Wmf; - -namespace MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes -{ - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using System.IO; - - internal class META_SETWINDOWORG : Record - { - public short Y; - - public short X; - - public META_SETWINDOWORG() - { - Header.RecordFunction = RecordType.META_SETWINDOWORG; - } - - public override void Read(BinaryReader reader) - { - Y = reader.ReadInt16(); - X = reader.ReadInt16(); - } - - public override void Write(BinaryWriter writer) - { - base.Write(writer); - writer.Write(Y); - writer.Write(X); - } - } -} diff --git a/src/MiniPdf/Drawing/Metafile/Wmf/WmfReader.cs b/src/MiniPdf/Drawing/Metafile/Wmf/WmfReader.cs deleted file mode 100644 index d8742626..00000000 --- a/src/MiniPdf/Drawing/Metafile/Wmf/WmfReader.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MiniSoftware.Drawing.Metafile.Wmf -{ - using System.IO; - using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; - using MiniSoftware.Drawing.Metafile.Wmf.Records; - using MiniSoftware.Drawing.Metafile.Wmf.Records.EscapeRecordTypes; - using MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes; - using MiniSoftware.Drawing.Metafile.Wmf.Records.StateRecordTypes; - - internal class WmfReader - { - public List Records { get; } = new(); - - public MetaHeader Header { get; private set; } = new(); - - public void Read(Stream stream) - { - var reader = new BinaryReader(stream); - - this.Header = new MetaHeader(); - this.Header.Read(reader); - - while (stream.Position < stream.Length) - { - var header = new RecordHeader(); - header.Read(reader); - - long expectedEndPosition = stream.Position + (header.RecordSize * 2) - 6; - var record = CreateRecord(header, reader); - if (record == null) - { - record = new Record - { - Header = header - }; - } - Records.Add(record); - stream.Position = expectedEndPosition; - } - } - - public static Record? CreateRecord(RecordHeader header, BinaryReader reader) - { - Record? record = header.RecordFunction switch - { - RecordType.META_EOF => new META_EOF(), - RecordType.META_REALIZEPALETTE => new META_REALIZEPALETTE(), - RecordType.META_SETPALENTRIES => new META_SETPALENTRIES(), - RecordType.META_SETBKMODE => new META_SETBKMODE(), - RecordType.META_SETMAPMODE => new META_SETMAPMODE(), - RecordType.META_SETROP2 => new META_SETROP2(), - RecordType.META_SETRELABS => new META_SETRELABS(), - RecordType.META_SETPOLYFILLMODE => new META_SETPOLYFILLMODE(), - RecordType.META_SETSTRETCHBLTMODE => new META_SETSTRETCHBLTMODE(), - RecordType.META_SETTEXTCHAREXTRA => new META_SETTEXTCHAREXTRA(), - RecordType.META_RESTOREDC => new META_RESTOREDC(), - RecordType.META_RESIZEPALETTE => new META_RESIZEPALETTE(), - RecordType.META_DIBCREATEPATTERNBRUSH => new META_DIBCREATEPATTERNBRUSH(), - RecordType.META_SETLAYOUT => new META_SETLAYOUT(), - RecordType.META_SETBKCOLOR => new META_SETBKCOLOR(), - RecordType.META_SETTEXTCOLOR => new META_SETTEXTCOLOR(), - RecordType.META_OFFSETVIEWPORTORG => new META_OFFSETVIEWPORTORG(), - RecordType.META_LINETO => new META_LINETO(), - RecordType.META_MOVETO => new META_MOVETO(), - RecordType.META_OFFSETCLIPRGN => new META_OFFSETCLIPRGN(), - RecordType.META_FILLREGION => new META_FILLREGION(), - RecordType.META_SETMAPPERFLAGS => new META_SETMAPPERFLAGS(), - RecordType.META_SELECTPALETTE => new META_SELECTPALETTE(), - RecordType.META_POLYGON => new META_POLYGON(), - RecordType.META_POLYLINE => new META_POLYLINE(), - RecordType.META_SETTEXTJUSTIFICATION => new META_SETTEXTJUSTIFICATION(), - RecordType.META_SETWINDOWORG => new META_SETWINDOWORG(), - RecordType.META_SETWINDOWEXT => new META_SETWINDOWEXT(), - RecordType.META_SETVIEWPORTORG => new META_SETVIEWPORTORG(), - RecordType.META_SETVIEWPORTEXT => new META_SETVIEWPORTEXT(), - RecordType.META_OFFSETWINDOWORG => new META_OFFSETWINDOWORG(), - RecordType.META_SCALEWINDOWEXT => new META_SCALEWINDOWEXT(), - RecordType.META_SCALEVIEWPORTEXT => new META_SCALEVIEWPORTEXT(), - RecordType.META_EXCLUDECLIPRECT => new META_EXCLUDECLIPRECT(), - RecordType.META_INTERSECTCLIPRECT => new META_INTERSECTCLIPRECT(), - RecordType.META_ELLIPSE => new META_ELLIPSE(), - RecordType.META_FLOODFILL => new META_FLOODFILL(), - RecordType.META_FRAMEREGION => new META_FRAMEREGION(), - RecordType.META_ANIMATEPALETTE => new META_ANIMATEPALETTE(), - RecordType.META_TEXTOUT => new META_TEXTOUT(), - RecordType.META_POLYPOLYGON => new META_POLYPOLYGON(), - RecordType.META_EXTFLOODFILL => new META_EXTFLOODFILL(), - RecordType.META_ESCAPE => new MetaEscape(), - RecordType.META_RECTANGLE => new META_RECTANGLE(), - RecordType.META_ROUNDRECT => new META_ROUNDRECT(), - RecordType.META_SETPIXEL => new META_SETPIXEL(), - RecordType.META_PATBLT => new META_PATBLT(), - RecordType.META_SAVEDC => new META_SAVEDC(), - RecordType.META_PIE => new META_PIE(), - RecordType.META_STRETCHBLT => new META_STRETCHBLT(), - RecordType.META_INVERTREGION => new META_INVERTREGION(), - RecordType.META_PAINTREGION => new META_PAINTREGION(), - RecordType.META_SELECTCLIPREGION => new META_SELECTCLIPREGION(), - RecordType.META_SELECTOBJECT => new META_SELECTOBJECT(), - RecordType.META_SETTEXTALIGN => new META_SETTEXTALIGN(), - RecordType.META_ARC => new META_ARC(), - RecordType.META_CHORD => new META_CHORD(), - RecordType.META_BITBLT => new META_BITBLT(), - RecordType.META_EXTTEXTOUT => new META_EXTTEXTOUT(), - RecordType.META_SETDIBTODEV => new META_SETDIBTODEV(), - RecordType.META_STRETCHDIB => new META_STRETCHDIB(), - RecordType.META_DELETEOBJECT => new META_DELETEOBJECT(), - RecordType.META_CREATEPALETTE => new META_CREATEPALETTE(), - RecordType.META_CREATEPATTERNBRUSH => new META_CREATEPATTERNBRUSH(), - RecordType.META_CREATEPENINDIRECT => new META_CREATEPENINDIRECT(), - RecordType.META_CREATEFONTINDIRECT => new META_CREATEFONTINDIRECT(), - RecordType.META_CREATEBRUSHINDIRECT => new MetaCreatebrushindirect(), - RecordType.META_CREATEREGION => new META_CREATEREGION(), - _ => null, - }; - - if (record is not null) - { - record.Header = header; - record.Read(reader); - } - - return record; - } - } -} diff --git a/src/MiniPdf/Drawing/NOTICE.md b/src/MiniPdf/Drawing/NOTICE.md deleted file mode 100644 index 69a6ab73..00000000 --- a/src/MiniPdf/Drawing/NOTICE.md +++ /dev/null @@ -1,8 +0,0 @@ -# MiniSoftware.Drawing attribution - -MiniPdf.Drawing is based on DRIT.Drawing: -https://github.com/dritsoftware/DRIT.Drawing - -The incorporated DRIT.Drawing source is Copyright (c) 2026 DR-IT Ltd. and is -used and modified under the MIT License. The complete license text is included -in LICENSE.DRIT.Drawing and distributed with the MiniPdf NuGet package. \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Pens/AdjustableArrowCap.cs b/src/MiniPdf/Drawing/Pens/AdjustableArrowCap.cs deleted file mode 100644 index 6a8e295c..00000000 --- a/src/MiniPdf/Drawing/Pens/AdjustableArrowCap.cs +++ /dev/null @@ -1,62 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Pens -{ - /// - /// Represents an adjustable arrow-shaped line cap that can be added to any . - /// - /// - /// An can be used to draw arrowheads at the ends of lines. - /// The width and height can be adjusted independently, and the arrow can be filled or outlined. - /// - public sealed class AdjustableArrowCap : CustomLineCap - { - /// - /// Initializes a new with the specified width and height. - /// - /// The width of the arrow cap. - /// The height of the arrow cap. - /// If true, the arrow cap is filled; otherwise, it is outlined. - public AdjustableArrowCap(float width, float height, bool isFilled = true) - : base(null, null, LineCap.Flat, 0f) - { - Width = width; - Height = height; - Filled = isFilled; - } - - /// - /// Gets or sets the width of the arrow cap. - /// - public float Width { get; set; } - - /// - /// Gets or sets the height of the arrow cap. - /// - public float Height { get; set; } - - /// - /// Gets or sets the middle inset of the arrow cap. - /// - public float MiddleInset { get; set; } - - /// - /// Gets or sets a value indicating whether the arrow cap is filled. - /// - public bool Filled { get; set; } - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public override CustomLineCap Clone() - => new AdjustableArrowCap(Width, Height, Filled) - { - MiddleInset = MiddleInset, - BaseCap = BaseCap, - BaseInset = BaseInset, - StrokeJoin = StrokeJoin, - WidthScale = WidthScale, - }; - } -} diff --git a/src/MiniPdf/Drawing/Pens/CustomLineCap.cs b/src/MiniPdf/Drawing/Pens/CustomLineCap.cs deleted file mode 100644 index 211c2b80..00000000 --- a/src/MiniPdf/Drawing/Pens/CustomLineCap.cs +++ /dev/null @@ -1,114 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; -using System; - -namespace MiniSoftware.Drawing.Pens -{ - /// - /// Represents a custom line cap used to draw the ends of lines. - /// - /// - /// A can be used to create custom start and end caps - /// for lines drawn with a . The cap can be filled with a path - /// and outlined with another path. - /// - public class CustomLineCap : IDisposable - { - private bool _disposed; - - /// - /// Initializes a new with the specified fill and stroke paths. - /// - /// The path used to fill the cap. - /// The path used to outline the cap. - /// The base cap style. - /// The inset from the end of the line. - public CustomLineCap(GraphicsPath? fillPath, GraphicsPath? strokePath, - LineCap baseCap = LineCap.Flat, float baseInset = 0f) - { - FillPath = fillPath; - StrokePath = strokePath; - BaseCap = baseCap; - BaseInset = baseInset; - } - - /// - /// Gets or sets the path used to fill the cap. - /// - public GraphicsPath? FillPath { get; set; } - - /// - /// Gets or sets the path used to outline the cap. - /// - public GraphicsPath? StrokePath { get; set; } - - /// - /// Gets or sets the base cap style. - /// - public LineCap BaseCap { get; set; } - - /// - /// Gets or sets the stroke join style. - /// - public LineJoin StrokeJoin { get; set; } = LineJoin.Round; - - /// - /// Gets or sets the inset from the end of the line. - /// - public float BaseInset { get; set; } - - /// - /// Gets or sets the width scale for the cap. - /// - public float WidthScale { get; set; } = 1f; - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public virtual CustomLineCap Clone() - { - CheckDisposed(); - return new CustomLineCap( - (GraphicsPath?)FillPath?.Clone(), - (GraphicsPath?)StrokePath?.Clone(), - BaseCap, BaseInset) - { - StrokeJoin = StrokeJoin, - WidthScale = WidthScale, - }; - } - - /// - /// Releases all resources used by this custom line cap. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases the unmanaged resources used by the custom line cap and optionally releases the managed resources. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - FillPath?.Dispose(); - StrokePath?.Dispose(); - } - _disposed = true; - } - - /// - /// Throws an if this custom line cap has been disposed. - /// - protected void CheckDisposed() - { - if (_disposed) throw new ObjectDisposedException(GetType().Name); - } - } -} diff --git a/src/MiniPdf/Drawing/Pens/Pen.cs b/src/MiniPdf/Drawing/Pens/Pen.cs deleted file mode 100644 index 62d7bc74..00000000 --- a/src/MiniPdf/Drawing/Pens/Pen.cs +++ /dev/null @@ -1,391 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Pens -{ - /// - /// Defines a pen used to draw lines, curves, and shapes. - /// - /// - /// A can be initialized with a color or brush, and customized - /// with line caps, joins, dash patterns, and alignment. Pens are used with - /// objects to draw outlines of shapes. - /// - public sealed class Pen : IDisposable - { - private bool _disposed; - private Color _color; - private float _width; - private Brush? _brush; - private LineCap _startCap = LineCap.Flat; - private LineCap _endCap = LineCap.Flat; - private LineJoin _lineJoin = LineJoin.Miter; - private float _miterLimit = 10f; - private DashStyle _dashStyle = DashStyle.Solid; - private float _dashOffset; - private float[]? _dashPattern; - private DashCap _dashCap = DashCap.Flat; - private PenAlignment _alignment = PenAlignment.Center; - private float[]? _compoundArray; - private CustomLineCap? _customStartCap; - private CustomLineCap? _customEndCap; - private Matrix _transform; - - // ----------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------- - - /// - /// Initializes a new of the specified color and width of 1. - /// - /// The color of the pen. - public Pen(Color color) : this(color, 1f) { } - - /// - /// Initializes a new of the specified color and width. - /// - /// The color of the pen. - /// The width of the pen. - public Pen(Color color, float width) - { - _color = color; - _width = width; - _transform = new Matrix(); - } - - /// - /// Initializes a new of the specified brush and width of 1. - /// - /// The brush that determines the fill properties of the pen. - public Pen(Brush brush) : this(brush, 1f) { } - - /// - /// Initializes a new of the specified brush and width. - /// - /// The brush that determines the fill properties of the pen. - /// The width of the pen. - public Pen(Brush brush, float width) - { - if (brush == null) throw new ArgumentNullException(nameof(brush)); - _brush = brush; - _color = brush is SolidBrush sb ? sb.Color : Color.Black; - _width = width; - _transform = new Matrix(); - } - - // ----------------------------------------------------------------------- - // Properties - // ----------------------------------------------------------------------- - - /// - /// Gets or sets the color of this pen. - /// - public Color Color - { - get - { - CheckDisposed(); - return _brush is SolidBrush sb ? sb.Color : _color; - } - set - { - CheckDisposed(); - _color = value; - _brush = null; - } - } - - /// - /// Gets or sets the width of this pen. - /// - public float Width - { - get { CheckDisposed(); return _width; } - set { CheckDisposed(); _width = value; } - } - - /// - /// Gets or sets the brush that determines the fill properties of this pen. - /// - public Brush Brush - { - get - { - CheckDisposed(); - return _brush ?? new SolidBrush(_color); - } - set - { - CheckDisposed(); - if (value == null) throw new ArgumentNullException(nameof(value)); - _brush = value; - if (value is SolidBrush sb) - _color = sb.Color; - } - } - - /// - /// Gets the type of this pen (SolidColor, HatchFill, or LinearGradient). - /// - public PenType PenType - { - get - { - CheckDisposed(); - return _brush switch - { - null => PenType.SolidColor, - SolidBrush => PenType.SolidColor, - HatchBrush => PenType.HatchFill, - LinearGradientBrush => PenType.LinearGradient, - _ => PenType.SolidColor, - }; - } - } - - /// - /// Gets or sets the cap style at the start of the line. - /// - public LineCap StartCap - { - get { CheckDisposed(); return _startCap; } - set { CheckDisposed(); _startCap = value; } - } - - /// - /// Gets or sets the cap style at the end of the line. - /// - public LineCap EndCap - { - get { CheckDisposed(); return _endCap; } - set { CheckDisposed(); _endCap = value; } - } - - /// - /// Gets or sets the join style for connected line segments. - /// - public LineJoin LineJoin - { - get { CheckDisposed(); return _lineJoin; } - set { CheckDisposed(); _lineJoin = value; } - } - - /// - /// Gets or sets the miter limit for sharp join angles. - /// - public float MiterLimit - { - get { CheckDisposed(); return _miterLimit; } - set { CheckDisposed(); _miterLimit = value; } - } - - /// - /// Gets or sets the dash style for the line. - /// - public DashStyle DashStyle - { - get { CheckDisposed(); return _dashStyle; } - set - { - CheckDisposed(); - _dashStyle = value; - if (value != DashStyle.Custom) - _dashPattern = null; - } - } - - /// - /// Gets or sets the offset of the dash pattern. - /// - public float DashOffset - { - get { CheckDisposed(); return _dashOffset; } - set { CheckDisposed(); _dashOffset = value; } - } - - /// - /// Gets or sets the dash pattern for custom line styles. - /// - public float[] DashPattern - { - get - { - CheckDisposed(); - return _dashPattern != null ? (float[])_dashPattern.Clone() : Array.Empty(); - } - set - { - CheckDisposed(); - _dashPattern = value != null ? (float[])value.Clone() : null; - _dashStyle = DashStyle.Custom; - } - } - - /// - /// Gets or sets the dash cap style for the ends of dashes. - /// - public DashCap DashCap - { - get { CheckDisposed(); return _dashCap; } - set { CheckDisposed(); _dashCap = value; } - } - - /// - /// Gets or sets the alignment of the pen relative to the stroke outline. - /// - public PenAlignment Alignment - { - get { CheckDisposed(); return _alignment; } - set { CheckDisposed(); _alignment = value; } - } - - /// - /// Gets or sets the compound array for compound pen strokes. - /// - public float[]? CompoundArray - { - get { CheckDisposed(); return _compoundArray != null ? (float[])_compoundArray.Clone() : null; } - set { CheckDisposed(); _compoundArray = value != null ? (float[])value.Clone() : null; } - } - - /// - /// Gets or sets the custom start cap for the line. - /// - public CustomLineCap? CustomStartCap - { - get { CheckDisposed(); return _customStartCap; } - set { CheckDisposed(); _customStartCap = value; } - } - - /// - /// Gets or sets the custom end cap for the line. - /// - public CustomLineCap? CustomEndCap - { - get { CheckDisposed(); return _customEndCap; } - set { CheckDisposed(); _customEndCap = value; } - } - - /// - /// Gets or sets the transformation matrix for the pen. - /// - public Matrix Transform - { - get { CheckDisposed(); return _transform; } - set { CheckDisposed(); _transform = value ?? new Matrix(); } - } - - // ----------------------------------------------------------------------- - // Transform methods - // ----------------------------------------------------------------------- - - /// - /// Resets the transformation matrix to the identity matrix. - /// - public void ResetTransform() - { - CheckDisposed(); - _transform.Reset(); - } - - /// - /// Multiplies the transformation matrix by the specified matrix. - /// - /// The matrix to multiply. - /// The order of multiplication (prepend or append). - public void MultiplyTransform(Matrix matrix, MatrixOrder order = MatrixOrder.Prepend) - { - CheckDisposed(); - _transform.Multiply(matrix, order); - } - - /// - /// Rotates the transformation matrix by the specified angle. - /// - /// The angle of rotation in degrees. - /// The order of multiplication (prepend or append). - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - { - CheckDisposed(); - _transform.Rotate(angle, order); - } - - /// - /// Scales the transformation matrix by the specified factors. - /// - /// The horizontal scale factor. - /// The vertical scale factor. - /// The order of multiplication (prepend or append). - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - { - CheckDisposed(); - _transform.Scale(sx, sy, order); - } - - /// - /// Translates the transformation matrix by the specified offsets. - /// - /// The horizontal translation. - /// The vertical translation. - /// The order of multiplication (prepend or append). - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - { - CheckDisposed(); - _transform.Translate(dx, dy, order); - } - - // ----------------------------------------------------------------------- - // Clone / Dispose - // ----------------------------------------------------------------------- - - /// - /// Creates an exact copy of this . - /// - /// A new with the same properties. - public Pen Clone() - { - CheckDisposed(); - var clone = new Pen(_color, _width) - { - _brush = _brush?.Clone(), - _startCap = _startCap, - _endCap = _endCap, - _lineJoin = _lineJoin, - _miterLimit = _miterLimit, - _dashStyle = _dashStyle, - _dashOffset = _dashOffset, - _dashPattern = _dashPattern != null ? (float[])_dashPattern.Clone() : null, - _dashCap = _dashCap, - _alignment = _alignment, - _compoundArray = _compoundArray != null ? (float[])_compoundArray.Clone() : null, - }; - clone._transform = _transform.Clone(); - return clone; - } - - /// - /// Releases all resources used by this pen. - /// - public void Dispose() - { - _disposed = true; - _transform.Dispose(); - GC.SuppressFinalize(this); - } - - // ----------------------------------------------------------------------- - // Private helpers - // ----------------------------------------------------------------------- - - /// - /// Throws an if this pen has been disposed. - /// - private void CheckDisposed() - { - if (_disposed) - throw new ObjectDisposedException(nameof(Pen)); - } - } -} diff --git a/src/MiniPdf/Drawing/Pens/Pens.cs b/src/MiniPdf/Drawing/Pens/Pens.cs deleted file mode 100644 index da5aa38a..00000000 --- a/src/MiniPdf/Drawing/Pens/Pens.cs +++ /dev/null @@ -1,727 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Pens -{ - /// - /// Provides a set of predefined objects representing all colors. - /// - /// - /// Each property returns a cached with a width of 1. - /// These pens are commonly used for drawing shapes and lines. - /// - public static class Pens - { - private static readonly Pen?[] s_pens = new Pen?[141]; - - private static Pen Get(KnownColor kc) - { - int idx = (int)kc - 27; // KnownColor.Transparent == 27 - return s_pens[idx] ??= new Pen(Color.FromKnownColor(kc), 1f); - } - - /// - /// Gets a with color. - /// - public static Pen Transparent => Get(KnownColor.Transparent); - - /// - /// Gets a with color. - /// - public static Pen AliceBlue => Get(KnownColor.AliceBlue); - - /// - /// Gets a with color. - /// - public static Pen AntiqueWhite => Get(KnownColor.AntiqueWhite); - - /// - /// Gets a with color. - /// - public static Pen Aqua => Get(KnownColor.Aqua); - - /// - /// Gets a with color. - /// - public static Pen Aquamarine => Get(KnownColor.Aquamarine); - - /// - /// Gets a with color. - /// - public static Pen Azure => Get(KnownColor.Azure); - - /// - /// Gets a with color. - /// - public static Pen Beige => Get(KnownColor.Beige); - - /// - /// Gets a with color. - /// - public static Pen Bisque => Get(KnownColor.Bisque); - - /// - /// Gets a with color. - /// - public static Pen Black => Get(KnownColor.Black); - - /// - /// Gets a with color. - /// - public static Pen BlanchedAlmond => Get(KnownColor.BlanchedAlmond); - - /// - /// Gets a with color. - /// - public static Pen Blue => Get(KnownColor.Blue); - - /// - /// Gets a with color. - /// - public static Pen BlueViolet => Get(KnownColor.BlueViolet); - - /// - /// Gets a with color. - /// - public static Pen Brown => Get(KnownColor.Brown); - - /// - /// Gets a with color. - /// - public static Pen BurlyWood => Get(KnownColor.BurlyWood); - - /// - /// Gets a with color. - /// - public static Pen CadetBlue => Get(KnownColor.CadetBlue); - - /// - /// Gets a with color. - /// - public static Pen Chartreuse => Get(KnownColor.Chartreuse); - - /// - /// Gets a with color. - /// - public static Pen Chocolate => Get(KnownColor.Chocolate); - - /// - /// Gets a with color. - /// - public static Pen Coral => Get(KnownColor.Coral); - - /// - /// Gets a with color. - /// - public static Pen CornflowerBlue => Get(KnownColor.CornflowerBlue); - - /// - /// Gets a with color. - /// - public static Pen Cornsilk => Get(KnownColor.Cornsilk); - - /// - /// Gets a with color. - /// - public static Pen Crimson => Get(KnownColor.Crimson); - - /// - /// Gets a with color. - /// - public static Pen Cyan => Get(KnownColor.Cyan); - - /// - /// Gets a with color. - /// - public static Pen DarkBlue => Get(KnownColor.DarkBlue); - - /// - /// Gets a with color. - /// - public static Pen DarkCyan => Get(KnownColor.DarkCyan); - - /// - /// Gets a with color. - /// - public static Pen DarkGoldenrod => Get(KnownColor.DarkGoldenrod); - - /// - /// Gets a with color. - /// - public static Pen DarkGray => Get(KnownColor.DarkGray); - - /// - /// Gets a with color. - /// - public static Pen DarkGreen => Get(KnownColor.DarkGreen); - - /// - /// Gets a with color. - /// - public static Pen DarkKhaki => Get(KnownColor.DarkKhaki); - - /// - /// Gets a with color. - /// - public static Pen DarkMagenta => Get(KnownColor.DarkMagenta); - - /// - /// Gets a with color. - /// - public static Pen DarkOliveGreen => Get(KnownColor.DarkOliveGreen); - - /// - /// Gets a with color. - /// - public static Pen DarkOrange => Get(KnownColor.DarkOrange); - - /// - /// Gets a with color. - /// - public static Pen DarkOrchid => Get(KnownColor.DarkOrchid); - - /// - /// Gets a with color. - /// - public static Pen DarkRed => Get(KnownColor.DarkRed); - - /// - /// Gets a with color. - /// - public static Pen DarkSalmon => Get(KnownColor.DarkSalmon); - - /// - /// Gets a with color. - /// - public static Pen DarkSeaGreen => Get(KnownColor.DarkSeaGreen); - - /// - /// Gets a with color. - /// - public static Pen DarkSlateBlue => Get(KnownColor.DarkSlateBlue); - - /// - /// Gets a with color. - /// - public static Pen DarkSlateGray => Get(KnownColor.DarkSlateGray); - - /// - /// Gets a with color. - /// - public static Pen DarkTurquoise => Get(KnownColor.DarkTurquoise); - - /// - /// Gets a with color. - /// - public static Pen DarkViolet => Get(KnownColor.DarkViolet); - - /// - /// Gets a with color. - /// - public static Pen DeepPink => Get(KnownColor.DeepPink); - - /// - /// Gets a with color. - /// - public static Pen DeepSkyBlue => Get(KnownColor.DeepSkyBlue); - - /// - /// Gets a with color. - /// - public static Pen DimGray => Get(KnownColor.DimGray); - - /// - /// Gets a with color. - /// - public static Pen DodgerBlue => Get(KnownColor.DodgerBlue); - - /// - /// Gets a with color. - /// - public static Pen Firebrick => Get(KnownColor.Firebrick); - - /// - /// Gets a with color. - /// - public static Pen FloralWhite => Get(KnownColor.FloralWhite); - - /// - /// Gets a with color. - /// - public static Pen ForestGreen => Get(KnownColor.ForestGreen); - - /// - /// Gets a with color. - /// - public static Pen Fuchsia => Get(KnownColor.Fuchsia); - - /// - /// Gets a with color. - /// - public static Pen Gainsboro => Get(KnownColor.Gainsboro); - - /// - /// Gets a with color. - /// - public static Pen GhostWhite => Get(KnownColor.GhostWhite); - - /// - /// Gets a with color. - /// - public static Pen Gold => Get(KnownColor.Gold); - - /// - /// Gets a with color. - /// - public static Pen Goldenrod => Get(KnownColor.Goldenrod); - - /// - /// Gets a with color. - /// - public static Pen Gray => Get(KnownColor.Gray); - - /// - /// Gets a with color. - /// - public static Pen Green => Get(KnownColor.Green); - - /// - /// Gets a with color. - /// - public static Pen GreenYellow => Get(KnownColor.GreenYellow); - - /// - /// Gets a with color. - /// - public static Pen Honeydew => Get(KnownColor.Honeydew); - - /// - /// Gets a with color. - /// - public static Pen HotPink => Get(KnownColor.HotPink); - - /// - /// Gets a with color. - /// - public static Pen IndianRed => Get(KnownColor.IndianRed); - - /// - /// Gets a with color. - /// - public static Pen Indigo => Get(KnownColor.Indigo); - - /// - /// Gets a with color. - /// - public static Pen Ivory => Get(KnownColor.Ivory); - - /// - /// Gets a with color. - /// - public static Pen Khaki => Get(KnownColor.Khaki); - - /// - /// Gets a with color. - /// - public static Pen Lavender => Get(KnownColor.Lavender); - - /// - /// Gets a with color. - /// - public static Pen LavenderBlush => Get(KnownColor.LavenderBlush); - - /// - /// Gets a with color. - /// - public static Pen LawnGreen => Get(KnownColor.LawnGreen); - - /// - /// Gets a with color. - /// - public static Pen LemonChiffon => Get(KnownColor.LemonChiffon); - - /// - /// Gets a with color. - /// - public static Pen LightBlue => Get(KnownColor.LightBlue); - - /// - /// Gets a with color. - /// - public static Pen LightCoral => Get(KnownColor.LightCoral); - - /// - /// Gets a with color. - /// - public static Pen LightCyan => Get(KnownColor.LightCyan); - - /// - /// Gets a with color. - /// - public static Pen LightGoldenrodYellow => Get(KnownColor.LightGoldenrodYellow); - - /// - /// Gets a with color. - /// - public static Pen LightGray => Get(KnownColor.LightGray); - - /// - /// Gets a with color. - /// - public static Pen LightGreen => Get(KnownColor.LightGreen); - - /// - /// Gets a with color. - /// - public static Pen LightPink => Get(KnownColor.LightPink); - - /// - /// Gets a with color. - /// - public static Pen LightSalmon => Get(KnownColor.LightSalmon); - - /// - /// Gets a with color. - /// - public static Pen LightSeaGreen => Get(KnownColor.LightSeaGreen); - - /// - /// Gets a with color. - /// - public static Pen LightSkyBlue => Get(KnownColor.LightSkyBlue); - - /// - /// Gets a with color. - /// - public static Pen LightSlateGray => Get(KnownColor.LightSlateGray); - - /// - /// Gets a with color. - /// - public static Pen LightSteelBlue => Get(KnownColor.LightSteelBlue); - - /// - /// Gets a with color. - /// - public static Pen LightYellow => Get(KnownColor.LightYellow); - - /// - /// Gets a with color. - /// - public static Pen Lime => Get(KnownColor.Lime); - - /// - /// Gets a with color. - /// - public static Pen LimeGreen => Get(KnownColor.LimeGreen); - - /// - /// Gets a with color. - /// - public static Pen Linen => Get(KnownColor.Linen); - - /// - /// Gets a with color. - /// - public static Pen Magenta => Get(KnownColor.Magenta); - - /// - /// Gets a with color. - /// - public static Pen Maroon => Get(KnownColor.Maroon); - - /// - /// Gets a with color. - /// - public static Pen MediumAquamarine => Get(KnownColor.MediumAquamarine); - - /// - /// Gets a with color. - /// - public static Pen MediumBlue => Get(KnownColor.MediumBlue); - - /// - /// Gets a with color. - /// - public static Pen MediumOrchid => Get(KnownColor.MediumOrchid); - - /// - /// Gets a with color. - /// - public static Pen MediumPurple => Get(KnownColor.MediumPurple); - - /// - /// Gets a with color. - /// - public static Pen MediumSeaGreen => Get(KnownColor.MediumSeaGreen); - - /// - /// Gets a with color. - /// - public static Pen MediumSlateBlue => Get(KnownColor.MediumSlateBlue); - - /// - /// Gets a with color. - /// - public static Pen MediumSpringGreen => Get(KnownColor.MediumSpringGreen); - - /// - /// Gets a with color. - /// - public static Pen MediumTurquoise => Get(KnownColor.MediumTurquoise); - - /// - /// Gets a with color. - /// - public static Pen MediumVioletRed => Get(KnownColor.MediumVioletRed); - - /// - /// Gets a with color. - /// - public static Pen MidnightBlue => Get(KnownColor.MidnightBlue); - - /// - /// Gets a with color. - /// - public static Pen MintCream => Get(KnownColor.MintCream); - - /// - /// Gets a with color. - /// - public static Pen MistyRose => Get(KnownColor.MistyRose); - - /// - /// Gets a with color. - /// - public static Pen Moccasin => Get(KnownColor.Moccasin); - - /// - /// Gets a with color. - /// - public static Pen NavajoWhite => Get(KnownColor.NavajoWhite); - - /// - /// Gets a with color. - /// - public static Pen Navy => Get(KnownColor.Navy); - - /// - /// Gets a with color. - /// - public static Pen OldLace => Get(KnownColor.OldLace); - - /// - /// Gets a with color. - /// - public static Pen Olive => Get(KnownColor.Olive); - - /// - /// Gets a with color. - /// - public static Pen OliveDrab => Get(KnownColor.OliveDrab); - - /// - /// Gets a with color. - /// - public static Pen Orange => Get(KnownColor.Orange); - - /// - /// Gets a with color. - /// - public static Pen OrangeRed => Get(KnownColor.OrangeRed); - - /// - /// Gets a with color. - /// - public static Pen Orchid => Get(KnownColor.Orchid); - - /// - /// Gets a with color. - /// - public static Pen PaleGoldenrod => Get(KnownColor.PaleGoldenrod); - - /// - /// Gets a with color. - /// - public static Pen PaleGreen => Get(KnownColor.PaleGreen); - - /// - /// Gets a with color. - /// - public static Pen PaleTurquoise => Get(KnownColor.PaleTurquoise); - - /// - /// Gets a with color. - /// - public static Pen PaleVioletRed => Get(KnownColor.PaleVioletRed); - - /// - /// Gets a with color. - /// - public static Pen PapayaWhip => Get(KnownColor.PapayaWhip); - - /// - /// Gets a with color. - /// - public static Pen PeachPuff => Get(KnownColor.PeachPuff); - - /// - /// Gets a with color. - /// - public static Pen Peru => Get(KnownColor.Peru); - - /// - /// Gets a with color. - /// - public static Pen Pink => Get(KnownColor.Pink); - - /// - /// Gets a with color. - /// - public static Pen Plum => Get(KnownColor.Plum); - - /// - /// Gets a with color. - /// - public static Pen PowderBlue => Get(KnownColor.PowderBlue); - - /// - /// Gets a with color. - /// - public static Pen Purple => Get(KnownColor.Purple); - - /// - /// Gets a with color. - /// - public static Pen Red => Get(KnownColor.Red); - - /// - /// Gets a with color. - /// - public static Pen RosyBrown => Get(KnownColor.RosyBrown); - - /// - /// Gets a with color. - /// - public static Pen RoyalBlue => Get(KnownColor.RoyalBlue); - - /// - /// Gets a with color. - /// - public static Pen SaddleBrown => Get(KnownColor.SaddleBrown); - - /// - /// Gets a with color. - /// - public static Pen Salmon => Get(KnownColor.Salmon); - - /// - /// Gets a with color. - /// - public static Pen SandyBrown => Get(KnownColor.SandyBrown); - - /// - /// Gets a with color. - /// - public static Pen SeaGreen => Get(KnownColor.SeaGreen); - - /// - /// Gets a with color. - /// - public static Pen SeaShell => Get(KnownColor.SeaShell); - - /// - /// Gets a with color. - /// - public static Pen Sienna => Get(KnownColor.Sienna); - - /// - /// Gets a with color. - /// - public static Pen Silver => Get(KnownColor.Silver); - - /// - /// Gets a with color. - /// - public static Pen SkyBlue => Get(KnownColor.SkyBlue); - - /// - /// Gets a with color. - /// - public static Pen SlateBlue => Get(KnownColor.SlateBlue); - - /// - /// Gets a with color. - /// - public static Pen SlateGray => Get(KnownColor.SlateGray); - - /// - /// Gets a with color. - /// - public static Pen Snow => Get(KnownColor.Snow); - - /// - /// Gets a with color. - /// - public static Pen SpringGreen => Get(KnownColor.SpringGreen); - - /// - /// Gets a with color. - /// - public static Pen SteelBlue => Get(KnownColor.SteelBlue); - - /// - /// Gets a with color. - /// - public static Pen Tan => Get(KnownColor.Tan); - - /// - /// Gets a with color. - /// - public static Pen Teal => Get(KnownColor.Teal); - - /// - /// Gets a with color. - /// - public static Pen Thistle => Get(KnownColor.Thistle); - - /// - /// Gets a with color. - /// - public static Pen Tomato => Get(KnownColor.Tomato); - - /// - /// Gets a with color. - /// - public static Pen Turquoise => Get(KnownColor.Turquoise); - - /// - /// Gets a with color. - /// - public static Pen Violet => Get(KnownColor.Violet); - - /// - /// Gets a with color. - /// - public static Pen Wheat => Get(KnownColor.Wheat); - - /// - /// Gets a with color. - /// - public static Pen White => Get(KnownColor.White); - - /// - /// Gets a with color. - /// - public static Pen WhiteSmoke => Get(KnownColor.WhiteSmoke); - - /// - /// Gets a with color. - /// - public static Pen Yellow => Get(KnownColor.Yellow); - - /// - /// Gets a with color. - /// - public static Pen YellowGreen => Get(KnownColor.YellowGreen); - } -} diff --git a/src/MiniPdf/Drawing/Rendering/ActiveEdge.cs b/src/MiniPdf/Drawing/Rendering/ActiveEdge.cs deleted file mode 100644 index 0b625eb0..00000000 --- a/src/MiniPdf/Drawing/Rendering/ActiveEdge.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace MiniSoftware.Drawing.Rendering -{ - internal struct ActiveEdge - { - public int YMaxExclusive; - public float CurrentX; - public float DxPerY; - public int Winding; - } -} diff --git a/src/MiniPdf/Drawing/Rendering/BrushSampler.cs b/src/MiniPdf/Drawing/Rendering/BrushSampler.cs deleted file mode 100644 index 449c8d02..00000000 --- a/src/MiniPdf/Drawing/Rendering/BrushSampler.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class BrushSampler - { - public static Color Sample(Brush brush, float x, float y, InterpolationMode interpolation) - { - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - if (brush is SolidBrush solid) - return solid.Color; - - if (brush is LinearGradientBrush linear) - return GradientEvaluator.SampleLinear(linear, x, y); - - if (brush is PathGradientBrush path) - return GradientEvaluator.SamplePath(path, x, y); - - if (brush is TextureBrush texture) - return TextureSampler.Sample(texture, x, y, interpolation); - - if (brush is HatchBrush hatch) - return HatchRenderer.Sample(hatch, (int)Math.Floor(x), (int)Math.Floor(y)); - - return Color.Black; - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/DashExpander.cs b/src/MiniPdf/Drawing/Rendering/DashExpander.cs deleted file mode 100644 index 7f51ceab..00000000 --- a/src/MiniPdf/Drawing/Rendering/DashExpander.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class DashExpander - { - public static GraphicsPath Expand(GraphicsPath path, Pens.Pen pen, float flatness = 0.25f) - { - if (path == null) throw new ArgumentNullException(nameof(path)); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - float[] pattern = GetPattern(pen); - if (pattern.Length == 0) - return path.Clone(); - - GraphicsPath flat = path.Clone(); - flat.Flatten(null, flatness); - PointF[] points = flat.PathPoints; - byte[] types = flat.PathTypes; - - var dashed = new GraphicsPath(flat.FillMode); - int subpathStart = -1; - float patternPos = pen.DashOffset * pen.Width; - int patternIndex = 0; - bool draw = true; - - for (int i = 0; i < points.Length; i++) - { - byte raw = (byte)(types[i] & (byte)PathPointType.PathTypeMask); - if (raw == (byte)PathPointType.Start) - { - subpathStart = i; - continue; - } - - if (i > 0) - EmitDashedSegment(dashed, points[i - 1], points[i], pattern, ref patternIndex, ref patternPos, ref draw); - - bool closes = (types[i] & (byte)PathPointType.CloseSubpath) != 0; - if (closes && subpathStart >= 0 && subpathStart != i) - EmitDashedSegment(dashed, points[i], points[subpathStart], pattern, ref patternIndex, ref patternPos, ref draw); - } - - return dashed; - } - - private static void EmitDashedSegment( - GraphicsPath output, - PointF a, - PointF b, - float[] pattern, - ref int patternIndex, - ref float patternPos, - ref bool draw) - { - float dx = b.X - a.X; - float dy = b.Y - a.Y; - float len = (float)Math.Sqrt(dx * dx + dy * dy); - if (len <= 1e-6f) - return; - - float ux = dx / len; - float uy = dy / len; - float consumed = 0f; - - while (consumed < len) - { - float dashLen = Math.Max(1e-6f, pattern[patternIndex]); - float remainInDash = dashLen - patternPos; - float run = Math.Min(remainInDash, len - consumed); - - if (draw) - { - PointF p0 = new PointF(a.X + ux * consumed, a.Y + uy * consumed); - PointF p1 = new PointF(a.X + ux * (consumed + run), a.Y + uy * (consumed + run)); - output.StartFigure(); - output.AddLine(p0, p1); - } - - consumed += run; - patternPos += run; - - if (patternPos >= dashLen - 1e-6f) - { - patternPos = 0f; - patternIndex = (patternIndex + 1) % pattern.Length; - draw = !draw; - } - } - } - - private static float[] GetPattern(Pens.Pen pen) - { - if (pen.DashStyle == DashStyle.Custom) - { - float[] custom = pen.DashPattern; - if (custom != null && custom.Length > 0) - return ScalePattern(custom, pen.Width); - return Array.Empty(); - } - - switch (pen.DashStyle) - { - case DashStyle.Solid: - return Array.Empty(); - case DashStyle.Dash: - return new[] { 3f * pen.Width, 1f * pen.Width }; - case DashStyle.Dot: - return new[] { 1f * pen.Width, 1f * pen.Width }; - case DashStyle.DashDot: - return new[] { 3f * pen.Width, 1f * pen.Width, 1f * pen.Width, 1f * pen.Width }; - case DashStyle.DashDotDot: - return new[] { 3f * pen.Width, 1f * pen.Width, 1f * pen.Width, 1f * pen.Width, 1f * pen.Width, 1f * pen.Width }; - default: - return Array.Empty(); - } - } - - private static float[] ScalePattern(float[] pattern, float width) - { - var result = new float[pattern.Length]; - for (int i = 0; i < pattern.Length; i++) - result[i] = Math.Max(1e-6f, pattern[i] * width); - return result; - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/EdgeBuilder.cs b/src/MiniPdf/Drawing/Rendering/EdgeBuilder.cs deleted file mode 100644 index a329dd0a..00000000 --- a/src/MiniPdf/Drawing/Rendering/EdgeBuilder.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Rendering -{ - internal readonly struct EdgeSeed - { - public EdgeSeed(int yStart, ActiveEdge edge) - { - YStart = yStart; - Edge = edge; - } - - public int YStart { get; } - public ActiveEdge Edge { get; } - } - - internal static class EdgeBuilder - { - public static List Build(GraphicsPath path, float flatness = 0.25f) - { - if (path == null) throw new ArgumentNullException(nameof(path)); - - GraphicsPath flat = path.Clone(); - flat.Flatten(null, flatness); - - PointF[] points = flat.PathPoints; - byte[] types = flat.PathTypes; - var edges = new List(points.Length); - - int subpathStart = -1; - for (int i = 0; i < points.Length; i++) - { - byte rawType = (byte)(types[i] & (byte)PathPointType.PathTypeMask); - if (rawType == (byte)PathPointType.Start) - { - subpathStart = i; - continue; - } - - if (i > 0) - AddEdge(points[i - 1], points[i], edges); - - bool closes = (types[i] & (byte)PathPointType.CloseSubpath) != 0; - if (closes && subpathStart >= 0 && subpathStart != i) - AddEdge(points[i], points[subpathStart], edges); - } - - return edges; - } - - private static void AddEdge(PointF a, PointF b, List edges) - { - float x0 = a.X; - float y0 = a.Y; - float x1 = b.X; - float y1 = b.Y; - - if (Math.Abs(y1 - y0) < 1e-6f) - return; - - int winding; - if (y1 > y0) - { - winding = 1; - } - else - { - float tx = x0; x0 = x1; x1 = tx; - float ty = y0; y0 = y1; y1 = ty; - winding = -1; - } - - float dxPerY = (x1 - x0) / (y1 - y0); - - int yStart = (int)Math.Ceiling(y0 - 0.5f); - int yEndExclusive = (int)Math.Ceiling(y1 - 0.5f); - if (yStart >= yEndExclusive) - return; - - float sampleY = yStart + 0.5f; - float xAtStart = x0 + (sampleY - y0) * dxPerY; - - var edge = new ActiveEdge - { - YMaxExclusive = yEndExclusive, - CurrentX = xAtStart, - DxPerY = dxPerY, - Winding = winding, - }; - - edges.Add(new EdgeSeed(yStart, edge)); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/EmfPlayer.cs b/src/MiniPdf/Drawing/Rendering/EmfPlayer.cs deleted file mode 100644 index a2b2a1eb..00000000 --- a/src/MiniPdf/Drawing/Rendering/EmfPlayer.cs +++ /dev/null @@ -1,694 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Metafile.Emf.Enumerations; -using MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes; -using MiniSoftware.Drawing.Pens; -using MiniPdfFont = MiniSoftware.Drawing.Text.Font; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Replays EMF/EMF+ records onto any (raster - /// , , or any other - /// context). The legacy overload remains as a thin - /// backward-compat wrapper that creates a raster and - /// delegates to . - /// - internal static class EmfPlayer - { - private sealed class PenState - { - public Color Color = Color.Black; - public float Width = 1f; - public bool IsNull; - } - - private sealed class BrushState - { - public Color Color = Color.Transparent; - public bool IsNull = true; - } - - private sealed class FontState - { - public string FamilyName = "Arial"; - public float Size = 12f; - public bool Bold; - public bool Italic; - public bool Underline; - public bool Strikeout; - } - - private readonly struct Viewport - { - private readonly Rectangle _logical; - private readonly float _scaleX; - private readonly float _scaleY; - - public Viewport(Rectangle logicalBounds, int pixelWidth, int pixelHeight) - { - _logical = logicalBounds; - int logicalWidth = Math.Max(1, logicalBounds.Width); - int logicalHeight = Math.Max(1, logicalBounds.Height); - _scaleX = pixelWidth / (float)logicalWidth; - _scaleY = pixelHeight / (float)logicalHeight; - } - - public PointF MapPoint(float x, float y) - { - return new PointF( - (x - _logical.X) * _scaleX, - (y - _logical.Y) * _scaleY); - } - - public RectangleF MapRect(float left, float top, float right, float bottom) - { - float x1 = (left - _logical.X) * _scaleX; - float y1 = (top - _logical.Y) * _scaleY; - float x2 = (right - _logical.X) * _scaleX; - float y2 = (bottom - _logical.Y) * _scaleY; - - float minX = Math.Min(x1, x2); - float minY = Math.Min(y1, y2); - float width = Math.Abs(x2 - x1); - float height = Math.Abs(y2 - y1); - return new RectangleF(minX, minY, width, height); - } - } - - /// - /// Replays EMF records onto the specified drawing context. - /// - public static void Play(Metafile.MetafileDocument document, IDrawingContext ctx, Rectangle logicalBounds) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - if (ctx == null) - throw new ArgumentNullException(nameof(ctx)); - - var viewport = new Viewport(logicalBounds, ctx.Width, ctx.Height); - var objects = new Dictionary(); - - var currentPoint = new PointF(0f, 0f); - var currentPen = new PenState(); - var currentBrush = new BrushState(); - var currentFont = new FontState(); - var textColor = Color.Black; - - GraphicsPath? pathBuilder = null; - var pathCurrentPoint = new PointF(0f, 0f); - - ctx.Clear(Color.Transparent); - - foreach (var record in document.EmfRecords) - { - switch (record) - { - // ── Pixel ── - case EMR_SETPIXELV setPixel: - { - var mapped = viewport.MapPoint(setPixel.Position.x, setPixel.Position.y); - int x = ClampToPixel(ctx.Width, mapped.X); - int y = ClampToPixel(ctx.Height, mapped.Y); - SetPixel(ctx, x, y, ToColor(setPixel.Color)); - break; - } - - // ── Move/Line (path-aware) ── - case EMR_MOVETOEX moveTo: - { - var mapped = viewport.MapPoint(moveTo.Offset.x, moveTo.Offset.y); - if (pathBuilder != null) - { - pathBuilder.StartFigure(); - pathCurrentPoint = mapped; - } - currentPoint = mapped; - break; - } - - case EMR_LINETO lineTo: - { - var next = viewport.MapPoint(lineTo.Point.x, lineTo.Point.y); - if (pathBuilder != null) - { - pathBuilder.AddLine(pathCurrentPoint, next); - pathCurrentPoint = next; - } - else - { - DrawLine(ctx, currentPen, currentPoint, next); - } - currentPoint = next; - break; - } - - // ── Polylines (outside path) ── - case EMR_POLYLINE polyline when polyline.Points.Length >= 2: - { - var points = MapPoints(viewport, polyline.Points); - DrawPolyline(ctx, currentPen, points); - currentPoint = points[points.Length - 1]; - break; - } - case EMR_POLYLINE16 polyline16 when polyline16.Points.Length >= 2: - { - var points = MapPointsS(viewport, polyline16.Points); - DrawPolyline(ctx, currentPen, points); - currentPoint = points[points.Length - 1]; - break; - } - - // ── PolylineTo (path-aware) ── - case EMR_POLYLINETO polyLineTo when polyLineTo.Points.Length >= 1: - { - var points = MapPoints(viewport, polyLineTo.Points); - if (pathBuilder != null) - { - for (int i = 0; i < points.Length; i++) - { - pathBuilder.AddLine(pathCurrentPoint, points[i]); - pathCurrentPoint = points[i]; - } - } - currentPoint = points[points.Length - 1]; - break; - } - case EMR_POLYLINETO16 polyLineTo16 when polyLineTo16.Points.Length >= 1: - { - var points = MapPointsS(viewport, polyLineTo16.Points); - if (pathBuilder != null) - { - for (int i = 0; i < points.Length; i++) - { - pathBuilder.AddLine(pathCurrentPoint, points[i]); - pathCurrentPoint = points[i]; - } - } - currentPoint = points[points.Length - 1]; - break; - } - - // ── PolyBezierTo (path-aware) ── - case EMR_POLYBEZIERTO polyBezierTo when polyBezierTo.Points.Length >= 3: - { - var points = MapPoints(viewport, polyBezierTo.Points); - if (pathBuilder != null) - { - for (int i = 0; i + 2 < points.Length; i += 3) - { - pathBuilder.AddBezier(pathCurrentPoint, points[i], points[i + 1], points[i + 2]); - pathCurrentPoint = points[i + 2]; - } - } - currentPoint = points[points.Length - 1]; - break; - } - case EMR_POLYBEZIERTO16 polyBezierTo16 when polyBezierTo16.Points.Length >= 3: - { - var points = MapPointsS(viewport, polyBezierTo16.Points); - if (pathBuilder != null) - { - for (int i = 0; i + 2 < points.Length; i += 3) - { - pathBuilder.AddBezier(pathCurrentPoint, points[i], points[i + 1], points[i + 2]); - pathCurrentPoint = points[i + 2]; - } - } - currentPoint = points[points.Length - 1]; - break; - } - - // ── Polygons ── - case EMR_POLYGON polygon when polygon.Points.Length >= 2: - { - var points = MapPoints(viewport, polygon.Points); - FillPolygon(ctx, currentBrush, points); - DrawPolygon(ctx, currentPen, points); - break; - } - case EMR_POLYGON16 polygon16 when polygon16.Points.Length >= 2: - { - var points = MapPointsS(viewport, polygon16.Points); - FillPolygon(ctx, currentBrush, points); - DrawPolygon(ctx, currentPen, points); - break; - } - - // ── Primitives ── - case EMR_RECTANGLE rectangle: - { - RectangleF rect = viewport.MapRect( - rectangle.Box.Left, rectangle.Box.Top, - rectangle.Box.Right, rectangle.Box.Bottom); - FillRectangle(ctx, currentBrush, rect); - DrawRectangle(ctx, currentPen, rect); - break; - } - case EMR_ELLIPSE ellipse: - { - RectangleF rect = viewport.MapRect( - ellipse.Box.Left, ellipse.Box.Top, - ellipse.Box.Right, ellipse.Box.Bottom); - FillEllipse(ctx, currentBrush, rect); - DrawEllipse(ctx, currentPen, rect); - break; - } - - // ── Path bracket ── - case EMR_BEGINPATH _: - pathBuilder = new GraphicsPath(); - pathCurrentPoint = currentPoint; - break; - - case EMR_ENDPATH _: - // Path is finalized; pathBuilder stays for STROKEPATH/FILLPATH - break; - - case EMR_CLOSEFIGURE _: - pathBuilder?.CloseFigure(); - break; - - case EMR_ABORTPATH _: - pathBuilder = null; - break; - - case EMR_FLATTENPATH _: - // No-op: our path model is already flat-compatible - break; - - case EMR_STROKEPATH _: - { - if (pathBuilder != null && pathBuilder.PointCount > 0) - DrawPathDirect(ctx, currentPen, pathBuilder); - break; - } - case EMR_FILLPATH _: - { - if (pathBuilder != null && pathBuilder.PointCount > 0) - FillPathDirect(ctx, currentBrush, pathBuilder); - break; - } - case EMR_STROKEANDFILLPATH _: - { - if (pathBuilder != null && pathBuilder.PointCount > 0) - { - FillPathDirect(ctx, currentBrush, pathBuilder); - DrawPathDirect(ctx, currentPen, pathBuilder); - } - break; - } - - // ── Object table ── - case EMR_CREATEPEN createPen: - objects[createPen.IhPen] = CreatePenState(createPen.Pen); - break; - - case EMR_CREATEBRUSHINDIRECT createBrush: - objects[createBrush.IhBrush] = CreateBrushState(createBrush.LogBrush); - break; - - case EMR_EXTCREATEFONTINDIRECTW createFont: - objects[createFont.IhFont] = CreateFontState(createFont.Font); - break; - - case EMR_SELECTOBJECT selectObject: - { - if (!objects.TryGetValue(selectObject.ObjectIndex, out object? selected)) - break; - if (selected is PenState penState) - currentPen = penState; - else if (selected is BrushState brushState) - currentBrush = brushState; - else if (selected is FontState fontState) - currentFont = fontState; - break; - } - case EMR_DELETEOBJECT deleteObject: - objects.Remove(deleteObject.ObjectIndex); - break; - - // ── Transforms ── - case EMR_SETWORLDTRANSFORM wt: - { - var m = new Matrix(wt.M11, wt.M12, wt.M21, wt.M22, wt.Dx, wt.Dy); - ctx.Transform = m; - break; - } - case EMR_MODIFYWORLDTRANSFORM mwt: - { - var m = new Matrix(mwt.M11, mwt.M12, mwt.M21, mwt.M22, mwt.Dx, mwt.Dy); - switch (mwt.ModifyWorldTransformMode) - { - case ModifyWorldTransformMode.MWT_IDENTITY: - ctx.ResetTransform(); - break; - case ModifyWorldTransformMode.MWT_LEFTMULTIPLY: - ctx.MultiplyTransform(m, MatrixOrder.Prepend); - break; - case ModifyWorldTransformMode.MWT_RIGHTMULTIPLY: - ctx.MultiplyTransform(m, MatrixOrder.Append); - break; - case ModifyWorldTransformMode.MWT_SET: - ctx.Transform = m; - break; - } - break; - } - - // ── State stack ── - case EMR_SAVEDC _: - ctx.Save(); - break; - case EMR_RESTOREDC rdc: - // SavedDC is negative in well-formed EMF (relative restore) - // We do a single Restore for each RESTOREDC - ctx.Restore(ctx.Save()); - break; - - // ── Window/MapMode (accepted but viewport handles scaling) ── - case EMR_SETWINDOWEXTEX _: - case EMR_SETWINDOWORGEX _: - case EMR_SETVIEWPORTEXTEX _: - case EMR_SETVIEWPORTORGEX _: - case EMR_SETMAPMODE _: - case EMR_SETPOLYFILLMODE _: - case EMR_SETBKMODE _: - case EMR_SETBKCOLOR _: - case EMR_SETROP2 _: - case EMR_SETSTRETCHBLTMODE _: - case EMR_SETTEXTALIGN _: - case EMR_SETMITERLIMIT _: - case EMR_SETARCDIRECTION _: - case EMR_SETLAYOUT _: - break; - - case EMR_SETTEXTCOLOR stc: - textColor = ToColor(stc.Color); - break; - - // ── Clip ── - case EMR_INTERSECTCLIPRECT icr: - { - RectangleF rect = viewport.MapRect( - icr.Clip.Left, icr.Clip.Top, - icr.Clip.Right, icr.Clip.Bottom); - ctx.IntersectClip(rect); - break; - } - case EMR_EXCLUDECLIPRECT ecr: - { - var rf = viewport.MapRect( - ecr.Clip.Left, ecr.Clip.Top, - ecr.Clip.Right, ecr.Clip.Bottom); - var rect = new Rectangle( - (int)Math.Round(rf.X), (int)Math.Round(rf.Y), - (int)Math.Round(rf.Width), (int)Math.Round(rf.Height)); - ctx.ExcludeClip(rect); - break; - } - case EMR_EXTSELECTCLIPRGN _: - // Region data parsing is complex; skip for now - break; - case EMR_SETMETARGN _: - break; - - // ── Text ── - case EMR_EXTTEXTOUTW textOut: - { - if (textOut.EmrText?.OutputString?.Length > 0) - { - var refPoint = viewport.MapPoint( - textOut.EmrText.Reference.x, - textOut.EmrText.Reference.y); - string text = System.Text.Encoding.Unicode.GetString(textOut.EmrText.OutputString); - var style = FontStyle.Regular; - if (currentFont.Bold) style |= FontStyle.Bold; - if (currentFont.Italic) style |= FontStyle.Italic; - if (currentFont.Underline) style |= FontStyle.Underline; - if (currentFont.Strikeout) style |= FontStyle.Strikeout; - using var font = new MiniPdfFont(currentFont.FamilyName, currentFont.Size, style, GraphicsUnit.Pixel); - using var brush = new SolidBrush(textColor); - var layoutRect = new RectangleF(refPoint.X, refPoint.Y - font.Height, 1000, font.Height); - ctx.DrawString(text, font, brush, layoutRect, null); - } - break; - } - - // ── Image ── - case EMR_STRETCHDIBITS dibits: - { - var destRect = viewport.MapRect( - dibits.Bounds.Left, dibits.Bounds.Top, - dibits.Bounds.Right, dibits.Bounds.Bottom); - var bmp = DibToBitmap(dibits.BmiSrc, dibits.BitsSrc); - if (bmp != null) - { - ctx.DrawImage(bmp, destRect, - new RectangleF(0, 0, bmp.Width, bmp.Height), - GraphicsUnit.Pixel, null); - } - break; - } - } - } - } - - /// - /// Renders an EMF document to a raster bitmap (backward-compat wrapper). - /// - public static void Render(Metafile.MetafileDocument document, Bitmap target, Rectangle logicalBounds) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - if (target == null) - throw new ArgumentNullException(nameof(target)); - - using var graphics = Graphics.FromImage(target); - Play(document, graphics, logicalBounds); - } - - // ── Helpers ────────────────────────────────────────────────────────── - - private static PointF[] MapPoints(Viewport vp, Metafile.Wmf.Objects.PointL[] pts) - { - var result = new PointF[pts.Length]; - for (int i = 0; i < pts.Length; i++) - result[i] = vp.MapPoint(pts[i].x, pts[i].y); - return result; - } - - private static PointF[] MapPointsS(Viewport vp, Metafile.Wmf.Objects.PointS[] pts) - { - var result = new PointF[pts.Length]; - for (int i = 0; i < pts.Length; i++) - result[i] = vp.MapPoint(pts[i].x, pts[i].y); - return result; - } - - private static PenState CreatePenState(Metafile.Wmf.Objects.Pen pen) - { - return new PenState - { - Color = ToColor(pen.ColorRef), - Width = Math.Max(1f, Math.Abs(pen.Width.x)), - IsNull = pen.PenStyle == Metafile.Wmf.Enumerations.PenStyle.PS_NULL, - }; - } - - private static BrushState CreateBrushState(Metafile.Wmf.Objects.LogBrush brush) - { - return new BrushState - { - Color = ToColor(brush.ColorRef), - IsNull = brush.BrushStyle == Metafile.Wmf.Enumerations.BrushStyle.BS_NULL, - }; - } - - private static FontState CreateFontState(Metafile.Wmf.Objects.Font font) - { - return new FontState - { - FamilyName = string.IsNullOrEmpty(font.Facename) ? "Arial" : font.Facename, - Size = Math.Abs(font.Height) > 0 ? Math.Abs(font.Height) : 12f, - Bold = font.Weight >= 700, - Italic = font.Italic != 0, - Underline = font.Underline != 0, - Strikeout = font.StrikeOut != 0, - }; - } - - private static int ClampToPixel(int size, float value) - { - int v = (int)Math.Round(value); - if (v < 0) return 0; - if (v >= size) return size - 1; - return v; - } - - private static Color ToColor(Metafile.Wmf.Objects.ColorRef color) - => Color.FromArgb(255, color.Red, color.Green, color.Blue); - - private static void SetPixel(IDrawingContext ctx, int x, int y, Color color) - { - using var brush = new SolidBrush(color); - var path = new GraphicsPath(); - path.AddRectangle(new RectangleF(x, y, 1, 1)); - ctx.FillPath(brush, path); - } - - private static void DrawPathDirect(IDrawingContext ctx, PenState penState, GraphicsPath path) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - ctx.DrawPath(pen, path); - } - - private static void FillPathDirect(IDrawingContext ctx, BrushState brushState, GraphicsPath path) - { - if (brushState.IsNull) return; - using var brush = new SolidBrush(brushState.Color); - ctx.FillPath(brush, path); - } - - private static void DrawLine(IDrawingContext ctx, PenState penState, PointF p1, PointF p2) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddLine(p1, p2); - ctx.DrawPath(pen, path); - } - - private static void DrawPolyline(IDrawingContext ctx, PenState penState, PointF[] points) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddLines(points); - ctx.DrawPath(pen, path); - } - - private static void DrawPolygon(IDrawingContext ctx, PenState penState, PointF[] points) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddPolygon(points); - ctx.DrawPath(pen, path); - } - - private static void FillPolygon(IDrawingContext ctx, BrushState brushState, PointF[] points) - { - if (brushState.IsNull) return; - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddPolygon(points); - ctx.FillPath(brush, path); - } - - private static void DrawRectangle(IDrawingContext ctx, PenState penState, RectangleF rect) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddRectangle(rect); - ctx.DrawPath(pen, path); - } - - private static void FillRectangle(IDrawingContext ctx, BrushState brushState, RectangleF rect) - { - if (brushState.IsNull) return; - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddRectangle(rect); - ctx.FillPath(brush, path); - } - - private static void DrawEllipse(IDrawingContext ctx, PenState penState, RectangleF rect) - { - if (penState.IsNull) return; - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddEllipse(rect); - ctx.DrawPath(pen, path); - } - - private static void FillEllipse(IDrawingContext ctx, BrushState brushState, RectangleF rect) - { - if (brushState.IsNull) return; - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddEllipse(rect); - ctx.FillPath(brush, path); - } - - private static Bitmap? DibToBitmap(byte[] bmi, byte[] bits) - { - if (bmi == null || bmi.Length < 40 || bits == null || bits.Length == 0) - return null; - - try - { - int width = BitConverter.ToInt32(bmi, 4); - int height = BitConverter.ToInt32(bmi, 8); - ushort bpp = BitConverter.ToUInt16(bmi, 14); - if (width <= 0 || height == 0 || bpp == 0) - return null; - - bool topDown = height < 0; - height = Math.Abs(height); - - var format = bpp switch - { - 32 => PixelFormat.Format32bppArgb, - 24 => PixelFormat.Format24bppRgb, - _ => PixelFormat.Format32bppArgb, - }; - - var bmp = new Bitmap(width, height, format); - int stride = Bitmap.CalcStride(width, format); - int copyLen = Math.Min(bits.Length, stride * height); - Buffer.BlockCopy(bits, 0, bmp._pixels, 0, copyLen); - - if (topDown) - { - // Already top-down - } - else - { - // Flip vertically (bottom-up → top-down) - FlipVertical(bmp._pixels, stride, height); - } - - return bmp; - } - catch - { - return null; - } - } - - private static void FlipVertical(byte[] pixels, int stride, int height) - { - int half = height / 2; - var temp = new byte[stride]; - for (int y = 0; y < half; y++) - { - int top = y * stride; - int bot = (height - 1 - y) * stride; - Buffer.BlockCopy(pixels, top, temp, 0, stride); - Buffer.BlockCopy(pixels, bot, pixels, top, stride); - Buffer.BlockCopy(temp, 0, pixels, bot, stride); - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Rendering/GradientEvaluator.cs b/src/MiniPdf/Drawing/Rendering/GradientEvaluator.cs deleted file mode 100644 index 2d6133f4..00000000 --- a/src/MiniPdf/Drawing/Rendering/GradientEvaluator.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class GradientEvaluator - { - public static Color SampleLinear(LinearGradientBrush brush, float x, float y) - { - PointF p = TransformToBrushSpace(new PointF(x, y), brush.Transform); - PointF p0 = brush.Point1; - PointF p1 = brush.Point2; - - float dx = p1.X - p0.X; - float dy = p1.Y - p0.Y; - float lenSq = dx * dx + dy * dy; - float t = lenSq <= 1e-6f ? 0f : ((p.X - p0.X) * dx + (p.Y - p0.Y) * dy) / lenSq; - - t = ApplyWrap(t, brush.WrapMode); - t = ApplyBlend(brush.Blend, t); - - ColorBlend cb = brush.InterpolationColors; - Color color = SampleColorBlend(cb, t); - - if (!brush.GammaCorrection) - return color; - - return Color.FromArgb( - color.A, - GammaEncode(color.R), - GammaEncode(color.G), - GammaEncode(color.B)); - } - - public static Color SamplePath(PathGradientBrush brush, float x, float y) - { - PointF p = TransformToBrushSpace(new PointF(x, y), brush.Transform); - RectangleF rect = brush.Rectangle; - PointF center = brush.CenterPoint; - - float rx = Math.Max(1e-6f, rect.Width * 0.5f); - float ry = Math.Max(1e-6f, rect.Height * 0.5f); - float nx = (p.X - center.X) / rx; - float ny = (p.Y - center.Y) / ry; - float t = (float)Math.Sqrt(nx * nx + ny * ny); - t = Math.Max(0f, Math.Min(1f, t)); - t = ApplyBlend(brush.Blend, t); - - if (brush.InterpolationColors != null && brush.InterpolationColors.Colors.Length > 0) - return SampleColorBlend(brush.InterpolationColors, t); - - Color edge = Average(brush.SurroundColors); - return Lerp(brush.CenterColor, edge, t); - } - - internal static Color SampleColorBlend(ColorBlend blend, float t) - { - if (blend.Colors == null || blend.Positions == null || blend.Colors.Length == 0 || blend.Positions.Length == 0) - return Color.Black; - - if (blend.Colors.Length == 1) - return blend.Colors[0]; - - int n = Math.Min(blend.Colors.Length, blend.Positions.Length); - if (n == 1) - return blend.Colors[0]; - - t = Math.Max(0f, Math.Min(1f, t)); - if (t <= blend.Positions[0]) return blend.Colors[0]; - if (t >= blend.Positions[n - 1]) return blend.Colors[n - 1]; - - for (int i = 1; i < n; i++) - { - float p0 = blend.Positions[i - 1]; - float p1 = blend.Positions[i]; - if (t > p1) continue; - - float u = Math.Abs(p1 - p0) < 1e-6f ? 0f : (t - p0) / (p1 - p0); - return Lerp(blend.Colors[i - 1], blend.Colors[i], u); - } - - return blend.Colors[n - 1]; - } - - private static float ApplyBlend(Blend? blend, float t) - { - if (blend == null || blend.Positions == null || blend.Factors == null) - return Math.Max(0f, Math.Min(1f, t)); - - int n = Math.Min(blend.Positions.Length, blend.Factors.Length); - if (n == 0) - return Math.Max(0f, Math.Min(1f, t)); - - t = Math.Max(0f, Math.Min(1f, t)); - if (t <= blend.Positions[0]) return blend.Factors[0]; - if (t >= blend.Positions[n - 1]) return blend.Factors[n - 1]; - - for (int i = 1; i < n; i++) - { - float p0 = blend.Positions[i - 1]; - float p1 = blend.Positions[i]; - if (t > p1) continue; - - float u = Math.Abs(p1 - p0) < 1e-6f ? 0f : (t - p0) / (p1 - p0); - float v = blend.Factors[i - 1] + (blend.Factors[i] - blend.Factors[i - 1]) * u; - return Math.Max(0f, Math.Min(1f, v)); - } - - return Math.Max(0f, Math.Min(1f, blend.Factors[n - 1])); - } - - private static float ApplyWrap(float t, WrapMode wrap) - { - if (wrap == WrapMode.Clamp) - return Math.Max(0f, Math.Min(1f, t)); - - double floor = Math.Floor(t); - float frac = (float)(t - floor); - if (frac < 0f) frac += 1f; - - bool odd = (((int)floor) & 1) != 0; - switch (wrap) - { - case WrapMode.Tile: - return frac; - case WrapMode.TileFlipX: - case WrapMode.TileFlipY: - case WrapMode.TileFlipXY: - return odd ? 1f - frac : frac; - default: - return Math.Max(0f, Math.Min(1f, t)); - } - } - - private static PointF TransformToBrushSpace(PointF p, Matrix m) - { - Matrix inv = m.Clone(); - if (!inv.IsInvertible) - return p; - inv.Invert(); - PointF[] pts = new[] { p }; - inv.TransformPoints(pts); - return pts[0]; - } - - private static Color Average(Color[] colors) - { - if (colors == null || colors.Length == 0) - return Color.Black; - - int a = 0, r = 0, g = 0, b = 0; - for (int i = 0; i < colors.Length; i++) - { - a += colors[i].A; - r += colors[i].R; - g += colors[i].G; - b += colors[i].B; - } - - return Color.FromArgb(a / colors.Length, r / colors.Length, g / colors.Length, b / colors.Length); - } - - private static Color Lerp(Color a, Color b, float t) - { - t = Math.Max(0f, Math.Min(1f, t)); - int aa = (int)Math.Round(a.A + (b.A - a.A) * t); - int rr = (int)Math.Round(a.R + (b.R - a.R) * t); - int gg = (int)Math.Round(a.G + (b.G - a.G) * t); - int bb = (int)Math.Round(a.B + (b.B - a.B) * t); - return Color.FromArgb(aa, rr, gg, bb); - } - - private static byte GammaEncode(int v) - { - float lin = Math.Max(0f, Math.Min(255f, v)) / 255f; - float g = (float)Math.Pow(lin, 1.0 / 2.2); - return (byte)Math.Round(g * 255f); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/GraphicsContainer.cs b/src/MiniPdf/Drawing/Rendering/GraphicsContainer.cs deleted file mode 100644 index 0f324074..00000000 --- a/src/MiniPdf/Drawing/Rendering/GraphicsContainer.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Represents a graphics container that stores state information for a object. - /// - public sealed class GraphicsContainer - { - internal GraphicsContainer(GraphicsState state) - { - State = state; - } - - /// - /// Gets the graphics state stored in this container. - /// - internal GraphicsState State { get; } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/GraphicsState.cs b/src/MiniPdf/Drawing/Rendering/GraphicsState.cs deleted file mode 100644 index 2107ee42..00000000 --- a/src/MiniPdf/Drawing/Rendering/GraphicsState.cs +++ /dev/null @@ -1,94 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Represents the state of a object including transform, clipping, and rendering settings. - /// - public sealed class GraphicsState - { - internal GraphicsState( - Matrix transform, - Region clip, - GraphicsUnit pageUnit, - float pageScale, - SmoothingMode smoothingMode, - InterpolationMode interpolationMode, - CompositingMode compositingMode, - CompositingQuality compositingQuality, - PixelOffsetMode pixelOffsetMode, - TextRenderingHint textRenderingHint, - Point renderingOrigin) - { - Transform = transform; - Clip = clip; - PageUnit = pageUnit; - PageScale = pageScale; - SmoothingMode = smoothingMode; - InterpolationMode = interpolationMode; - CompositingMode = compositingMode; - CompositingQuality = compositingQuality; - PixelOffsetMode = pixelOffsetMode; - TextRenderingHint = textRenderingHint; - RenderingOrigin = renderingOrigin; - } - - /// - /// Gets the transformation matrix. - /// - internal Matrix Transform { get; } - - /// - /// Gets the clipping region. - /// - internal Region Clip { get; } - - /// - /// Gets the page unit of measure. - /// - internal GraphicsUnit PageUnit { get; } - - /// - /// Gets the page scale factor. - /// - internal float PageScale { get; } - - /// - /// Gets the smoothing mode. - /// - internal SmoothingMode SmoothingMode { get; } - - /// - /// Gets the interpolation mode. - /// - internal InterpolationMode InterpolationMode { get; } - - /// - /// Gets the compositing mode. - /// - internal CompositingMode CompositingMode { get; } - - /// - /// Gets the compositing quality. - /// - internal CompositingQuality CompositingQuality { get; } - - /// - /// Gets the pixel offset mode. - /// - internal PixelOffsetMode PixelOffsetMode { get; } - - /// - /// Gets the text rendering hint. - /// - internal TextRenderingHint TextRenderingHint { get; } - - /// - /// Gets the rendering origin point. - /// - internal Point RenderingOrigin { get; } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/HatchRenderer.cs b/src/MiniPdf/Drawing/Rendering/HatchRenderer.cs deleted file mode 100644 index 4082bcc7..00000000 --- a/src/MiniPdf/Drawing/Rendering/HatchRenderer.cs +++ /dev/null @@ -1,56 +0,0 @@ -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class HatchRenderer - { - public static Color Sample(HatchBrush brush, int x, int y) - { - bool fg = IsForeground(brush.HatchStyle, x, y); - return fg ? brush.ForegroundColor : brush.BackgroundColor; - } - - private static bool IsForeground(HatchStyle style, int x, int y) - { - switch (style) - { - case HatchStyle.Horizontal: - return (y & 3) == 0; - case HatchStyle.Vertical: - return (x & 3) == 0; - case HatchStyle.ForwardDiagonal: - return ((x + y) & 3) == 0; - case HatchStyle.BackwardDiagonal: - return ((x - y) & 3) == 0; - case HatchStyle.Cross: - return (x & 3) == 0 || (y & 3) == 0; - case HatchStyle.DiagonalCross: - return ((x + y) & 3) == 0 || ((x - y) & 3) == 0; - case HatchStyle.Percent05: - return ((x * 17 + y * 31) & 31) == 0; - case HatchStyle.Percent10: - return ((x * 17 + y * 31) & 15) == 0; - case HatchStyle.Percent20: - return ((x * 17 + y * 31) & 7) <= 1; - case HatchStyle.Percent25: - return ((x + y) & 3) == 0; - case HatchStyle.Percent40: - return ((x * 5 + y * 3) & 7) <= 2; - case HatchStyle.Percent50: - return ((x + y) & 1) == 0; - case HatchStyle.Percent60: - return ((x * 5 + y * 3) & 7) <= 4; - case HatchStyle.Percent75: - return ((x + y) & 3) != 0; - case HatchStyle.Percent80: - return ((x * 17 + y * 31) & 7) >= 1; - case HatchStyle.Percent90: - return ((x * 17 + y * 31) & 15) != 0; - default: - // Deterministic fallback for unimplemented style variants. - return ((x * 11 + y * 7) & 3) == 0; - } - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/ImageInterpolator.cs b/src/MiniPdf/Drawing/Rendering/ImageInterpolator.cs deleted file mode 100644 index 02bb867f..00000000 --- a/src/MiniPdf/Drawing/Rendering/ImageInterpolator.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Samples a source Bitmap at fractional pixel coordinates using NearestNeighbour, - /// Bilinear (4-tap), or Bicubic (Catmull-Rom 16-tap) interpolation. - /// - internal static class ImageInterpolator - { - public static Color Sample(Bitmap src, float x, float y, InterpolationMode mode) - { - switch (mode) - { - case InterpolationMode.Bilinear: - case InterpolationMode.HighQualityBilinear: - return SampleBilinear(src, x, y); - case InterpolationMode.Bicubic: - case InterpolationMode.HighQualityBicubic: - return SampleBicubic(src, x, y); - default: - return SampleNearest(src, x, y); - } - } - - // ── Nearest-neighbour ──────────────────────────────────────────────── - - private static Color SampleNearest(Bitmap src, float x, float y) - { - int ix = ClampInt((int)Math.Floor(x), 0, src.Width - 1); - int iy = ClampInt((int)Math.Floor(y), 0, src.Height - 1); - return src.GetPixel(ix, iy); - } - - // ── Bilinear (4-tap) ───────────────────────────────────────────────── - - private static Color SampleBilinear(Bitmap src, float x, float y) - { - int x0 = ClampInt((int)Math.Floor(x), 0, src.Width - 1); - int y0 = ClampInt((int)Math.Floor(y), 0, src.Height - 1); - int x1 = ClampInt(x0 + 1, 0, src.Width - 1); - int y1 = ClampInt(y0 + 1, 0, src.Height - 1); - - float u = x - (float)Math.Floor(x); - float v = y - (float)Math.Floor(y); - - Color p00 = src.GetPixel(x0, y0); - Color p10 = src.GetPixel(x1, y0); - Color p01 = src.GetPixel(x0, y1); - Color p11 = src.GetPixel(x1, y1); - - float fu = 1f - u, fv = 1f - v; - float w00 = fu * fv, w10 = u * fv, w01 = fu * v, w11 = u * v; - - return Color.FromArgb( - ClampByte(p00.A * w00 + p10.A * w10 + p01.A * w01 + p11.A * w11), - ClampByte(p00.R * w00 + p10.R * w10 + p01.R * w01 + p11.R * w11), - ClampByte(p00.G * w00 + p10.G * w10 + p01.G * w01 + p11.G * w11), - ClampByte(p00.B * w00 + p10.B * w10 + p01.B * w01 + p11.B * w11)); - } - - // ── Bicubic — Catmull-Rom 16-tap ───────────────────────────────────── - - private static Color SampleBicubic(Bitmap src, float x, float y) - { - float fx = x - (float)Math.Floor(x); - float fy = y - (float)Math.Floor(y); - int px = (int)Math.Floor(x); - int py = (int)Math.Floor(y); - - float a = 0f, r = 0f, g = 0f, b = 0f; - for (int row = -1; row <= 2; row++) - { - float wy = CatmullRom(row - fy); - for (int col = -1; col <= 2; col++) - { - float wx = CatmullRom(col - fx); - float w = wx * wy; - Color c = src.GetPixel( - ClampInt(px + col, 0, src.Width - 1), - ClampInt(py + row, 0, src.Height - 1)); - a += c.A * w; - r += c.R * w; - g += c.G * w; - b += c.B * w; - } - } - - return Color.FromArgb(ClampByte(a), ClampByte(r), ClampByte(g), ClampByte(b)); - } - - /// Catmull-Rom basis function (α = 0.5). - private static float CatmullRom(float t) - { - float at = t < 0f ? -t : t; - if (at < 1f) return 1.5f * at * at * at - 2.5f * at * at + 1f; - if (at < 2f) return -0.5f * at * at * at + 2.5f * at * at - 4f * at + 2f; - return 0f; - } - - // ── Helpers ────────────────────────────────────────────────────────── - - private static int ClampInt(int v, int min, int max) - => v < min ? min : v > max ? max : v; - - private static byte ClampByte(float v) - { - if (v <= 0f) return 0; - if (v >= 255f) return 255; - return (byte)Math.Round(v); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/ImageRenderer.cs b/src/MiniPdf/Drawing/Rendering/ImageRenderer.cs deleted file mode 100644 index d0f3429b..00000000 --- a/src/MiniPdf/Drawing/Rendering/ImageRenderer.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Entry point for all DrawImage operations. - /// Delegates to for sampling and - /// for affine warps. - /// - internal static class ImageRenderer - { - /// - /// Scale-blit a portion of into - /// on , applying optional colour adjustments. - /// - public static void Render( - Bitmap dst, Bitmap src, - RectangleF destRect, RectangleF srcRect, - Rectangle? clip, InterpolationMode mode, CompositingMode compositingMode, - ImageAttributes? attrs) - { - if (destRect.Width <= 0 || destRect.Height <= 0) return; - if (srcRect.Width <= 0 || srcRect.Height <= 0) return; - - Rectangle c = clip ?? new Rectangle(0, 0, dst.Width, dst.Height); - int x0 = Math.Max((int)Math.Floor(destRect.X), c.X); - int y0 = Math.Max((int)Math.Floor(destRect.Y), c.Y); - int x1 = Math.Min((int)Math.Ceiling(destRect.Right), c.Right) - 1; - int y1 = Math.Min((int)Math.Ceiling(destRect.Bottom), c.Bottom) - 1; - - float scaleX = srcRect.Width / destRect.Width; - float scaleY = srcRect.Height / destRect.Height; - - for (int dy = y0; dy <= y1; dy++) - { - float sy = srcRect.Y + (dy - destRect.Y) * scaleY; - for (int dx = x0; dx <= x1; dx++) - { - float sx = srcRect.X + (dx - destRect.X) * scaleX; - Color sc = ImageInterpolator.Sample(src, sx, sy, mode); - if (attrs != null) sc = attrs.ApplyToColor(sc); - PixelCompositor.BlendPixel(dst, dx, dy, sc, compositingMode); - } - } - } - - /// - /// Affine-warp blit into a parallelogram defined by 3 destination points. - /// - public static void RenderAffine( - Bitmap dst, Bitmap src, - PointF[] destPoints, RectangleF srcRect, - Rectangle? clip, InterpolationMode mode, CompositingMode compositingMode, - ImageAttributes? attrs) - => ImageTransformer.RenderAffine(dst, src, destPoints, srcRect, clip, mode, compositingMode, attrs); - } -} diff --git a/src/MiniPdf/Drawing/Rendering/ImageTransformer.cs b/src/MiniPdf/Drawing/Rendering/ImageTransformer.cs deleted file mode 100644 index 94f69e1f..00000000 --- a/src/MiniPdf/Drawing/Rendering/ImageTransformer.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Renders a source rectangle into a destination parallelogram defined by 3 corner - /// points (top-left, top-right, bottom-left) using an inverse-affine per-pixel scan. - /// - internal static class ImageTransformer - { - /// - /// Three points that define the parallelogram: - /// [0] = top-left, [1] = top-right, [2] = bottom-left. - /// - /// The source rectangle to render. - /// The clipping rectangle, or null for no clipping. - /// The interpolation mode. - /// The compositing mode. - /// The image attributes, or null for default. - public static void RenderAffine( - Bitmap dst, Bitmap src, - PointF[] destPoints, RectangleF srcRect, - Rectangle? clip, InterpolationMode mode, CompositingMode compositingMode, - Drawing2D.ImageAttributes? attrs) - { - if (destPoints == null || destPoints.Length < 3) return; - if (srcRect.Width <= 0f || srcRect.Height <= 0f) return; - - // Forward map: dest = p0 + u*(p1-p0) + v*(p2-p0) - // Inverse : solve for (u, v) given (dx, dy) - PointF p0 = destPoints[0], p1 = destPoints[1], p2 = destPoints[2]; - float ax = p1.X - p0.X, bx = p2.X - p0.X; - float ay = p1.Y - p0.Y, by = p2.Y - p0.Y; - float det = ax * by - bx * ay; - if (Math.Abs(det) < 1e-10f) return; // degenerate - - float invDet = 1f / det; - - // Implicit 4th point of the parallelogram - float p3x = p1.X + (p2.X - p0.X); - float p3y = p1.Y + (p2.Y - p0.Y); - - float minX = Min4(p0.X, p1.X, p2.X, p3x); - float minY = Min4(p0.Y, p1.Y, p2.Y, p3y); - float maxX = Max4(p0.X, p1.X, p2.X, p3x); - float maxY = Max4(p0.Y, p1.Y, p2.Y, p3y); - - Rectangle c = clip ?? new Rectangle(0, 0, dst.Width, dst.Height); - int x0 = Math.Max((int)Math.Floor(minX), c.X); - int y0 = Math.Max((int)Math.Floor(minY), c.Y); - int x1 = Math.Min((int)Math.Ceiling(maxX), c.Right - 1); - int y1 = Math.Min((int)Math.Ceiling(maxY), c.Bottom - 1); - - for (int dy = y0; dy <= y1; dy++) - { - float ey = dy - p0.Y; - for (int dx = x0; dx <= x1; dx++) - { - float ex = dx - p0.X; - float u = ( by * ex - bx * ey) * invDet; - float v = (-ay * ex + ax * ey) * invDet; - if (u < 0f || u > 1f || v < 0f || v > 1f) continue; - - float sx = srcRect.X + u * srcRect.Width; - float sy = srcRect.Y + v * srcRect.Height; - Color sc = ImageInterpolator.Sample(src, sx, sy, mode); - if (attrs != null) sc = attrs.ApplyToColor(sc); - PixelCompositor.BlendPixel(dst, dx, dy, sc, compositingMode); - } - } - } - - private static float Min4(float a, float b, float c, float d) - { - float m = a < b ? a : b; - m = m < c ? m : c; - return m < d ? m : d; - } - - private static float Max4(float a, float b, float c, float d) - { - float m = a > b ? a : b; - m = m > c ? m : c; - return m > d ? m : d; - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/LineCapRenderer.cs b/src/MiniPdf/Drawing/Rendering/LineCapRenderer.cs deleted file mode 100644 index 60397333..00000000 --- a/src/MiniPdf/Drawing/Rendering/LineCapRenderer.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class LineCapRenderer - { - public static void AddCap(GraphicsPath path, PointF point, PointF direction, float halfWidth, LineCap cap) - { - if (path == null) throw new ArgumentNullException(nameof(path)); - if (halfWidth <= 0f || cap == LineCap.Flat) - return; - - switch (cap) - { - case LineCap.Round: - path.AddEllipse(point.X - halfWidth, point.Y - halfWidth, halfWidth * 2f, halfWidth * 2f); - break; - case LineCap.Square: - AddOrientedSquare(path, point, direction, halfWidth); - break; - case LineCap.Triangle: - AddOrientedTriangle(path, point, direction, halfWidth); - break; - } - } - - private static void AddOrientedSquare(GraphicsPath path, PointF p, PointF dir, float half) - { - var d = Normalize(dir); - var n = new PointF(-d.Y, d.X); - - PointF a = new PointF(p.X + (-d.X - n.X) * half, p.Y + (-d.Y - n.Y) * half); - PointF b = new PointF(p.X + (-d.X + n.X) * half, p.Y + (-d.Y + n.Y) * half); - PointF c = new PointF(p.X + ( d.X + n.X) * half, p.Y + ( d.Y + n.Y) * half); - PointF dpt = new PointF(p.X + ( d.X - n.X) * half, p.Y + ( d.Y - n.Y) * half); - path.AddPolygon(new[] { a, b, c, dpt }); - } - - private static void AddOrientedTriangle(GraphicsPath path, PointF p, PointF dir, float half) - { - var d = Normalize(dir); - var n = new PointF(-d.Y, d.X); - - PointF tip = new PointF(p.X + d.X * (half * 1.5f), p.Y + d.Y * (half * 1.5f)); - PointF left = new PointF(p.X - d.X * half + n.X * half, p.Y - d.Y * half + n.Y * half); - PointF right = new PointF(p.X - d.X * half - n.X * half, p.Y - d.Y * half - n.Y * half); - path.AddPolygon(new[] { left, tip, right }); - } - - private static PointF Normalize(PointF p) - { - float len = (float)Math.Sqrt(p.X * p.X + p.Y * p.Y); - if (len <= 1e-6f) - return new PointF(1f, 0f); - return new PointF(p.X / len, p.Y / len); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/PixelCompositor.cs b/src/MiniPdf/Drawing/Rendering/PixelCompositor.cs deleted file mode 100644 index ca8b08fc..00000000 --- a/src/MiniPdf/Drawing/Rendering/PixelCompositor.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class PixelCompositor - { - public static void BlendPixel(Bitmap target, int x, int y, Color src, CompositingMode mode) - { - if ((uint)x >= (uint)target.Width || (uint)y >= (uint)target.Height) - return; - - if (mode == CompositingMode.SourceCopy) - { - target.SetPixel(x, y, src); - return; - } - - Color dst = target.GetPixel(x, y); - Color outColor = SourceOver(src, dst); - target.SetPixel(x, y, outColor); - } - - public static Color SourceOver(Color src, Color dst) - { - float sa = src.A / 255f; - float da = dst.A / 255f; - - float outA = sa + da * (1f - sa); - if (outA <= 0f) - return Color.FromArgb(0, 0, 0, 0); - - float outR = (src.R * sa + dst.R * da * (1f - sa)) / outA; - float outG = (src.G * sa + dst.G * da * (1f - sa)) / outA; - float outB = (src.B * sa + dst.B * da * (1f - sa)) / outA; - - return Color.FromArgb( - ClampToByte(outA * 255f), - ClampToByte(outR), - ClampToByte(outG), - ClampToByte(outB)); - } - - private static byte ClampToByte(float v) - { - if (v <= 0f) return 0; - if (v >= 255f) return 255; - return (byte)Math.Round(v); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/Rasterizer.cs b/src/MiniPdf/Drawing/Rendering/Rasterizer.cs deleted file mode 100644 index f193c936..00000000 --- a/src/MiniPdf/Drawing/Rendering/Rasterizer.cs +++ /dev/null @@ -1,253 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class Rasterizer - { - public static void FillPath( - Bitmap target, - GraphicsPath path, - Brush brush, - Matrix? transform, - FillMode fillMode, - Rectangle? clip, - SmoothingMode smoothingMode, - CompositingMode compositingMode, - InterpolationMode interpolationMode) - { - if (target == null) throw new ArgumentNullException(nameof(target)); - if (path == null) throw new ArgumentNullException(nameof(path)); - if (brush == null) throw new ArgumentNullException(nameof(brush)); - - bool aa = smoothingMode == SmoothingMode.AntiAlias || smoothingMode == SmoothingMode.HighQuality; - if (aa) - { - FillPathAntialiased(target, path, brush, transform, fillMode, clip, compositingMode, interpolationMode); - return; - } - - GraphicsPath effectivePath = path.Clone(); - if (transform != null) - effectivePath.Transform(transform); - - FillPathCore(target, effectivePath, brush, fillMode, clip, compositingMode, interpolationMode); - } - - public static void DrawPath( - Bitmap target, - GraphicsPath path, - Pens.Pen pen, - Matrix? transform, - Rectangle? clip, - SmoothingMode smoothingMode, - CompositingMode compositingMode, - InterpolationMode interpolationMode) - { - if (target == null) throw new ArgumentNullException(nameof(target)); - if (path == null) throw new ArgumentNullException(nameof(path)); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - GraphicsPath widened = StrokeExpander.Expand(path, pen, transform, 0.25f); - FillPath(target, widened, pen.Brush, null, FillMode.Winding, clip, smoothingMode, compositingMode, interpolationMode); - } - - private static void FillPathAntialiased( - Bitmap target, - GraphicsPath path, - Brush brush, - Matrix? transform, - FillMode fillMode, - Rectangle? clip, - CompositingMode compositingMode, - InterpolationMode interpolationMode) - { - int w2 = target.Width * 2; - int h2 = target.Height * 2; - - using var hi = new Bitmap(w2, h2, PixelFormat.Format32bppArgb); - GraphicsPath hiPath = path.Clone(); - - var aaTransform = new Matrix(2f, 0f, 0f, 2f, 0f, 0f); - if (transform != null) - aaTransform.Multiply(transform, MatrixOrder.Append); - hiPath.Transform(aaTransform); - - Rectangle? hiClip = null; - if (clip.HasValue) - hiClip = new Rectangle(clip.Value.X * 2, clip.Value.Y * 2, clip.Value.Width * 2, clip.Value.Height * 2); - - FillPathCore(hi, hiPath, brush, fillMode, hiClip, CompositingMode.SourceOver, interpolationMode); - - Rectangle clipRect = ClipToBounds(clip, target.Width, target.Height); - for (int y = clipRect.Y; y < clipRect.Bottom; y++) - { - for (int x = clipRect.X; x < clipRect.Right; x++) - { - Color c00 = hi.GetPixel(x * 2, y * 2); - Color c10 = hi.GetPixel(x * 2 + 1, y * 2); - Color c01 = hi.GetPixel(x * 2, y * 2 + 1); - Color c11 = hi.GetPixel(x * 2 + 1, y * 2 + 1); - - Color avg = Color.FromArgb( - (c00.A + c10.A + c01.A + c11.A + 2) / 4, - (c00.R + c10.R + c01.R + c11.R + 2) / 4, - (c00.G + c10.G + c01.G + c11.G + 2) / 4, - (c00.B + c10.B + c01.B + c11.B + 2) / 4); - - PixelCompositor.BlendPixel(target, x, y, avg, compositingMode); - } - } - } - - private static void FillPathCore( - Bitmap target, - GraphicsPath path, - Brush brush, - FillMode fillMode, - Rectangle? clip, - CompositingMode compositingMode, - InterpolationMode interpolationMode) - { - List seeds = EdgeBuilder.Build(path, 0.25f); - if (seeds.Count == 0) - return; - - int minY = int.MaxValue; - int maxYEx = int.MinValue; - var buckets = new Dictionary>(); - - for (int i = 0; i < seeds.Count; i++) - { - EdgeSeed seed = seeds[i]; - if (!buckets.TryGetValue(seed.YStart, out List? list)) - { - list = new List(); - buckets[seed.YStart] = list; - } - - list.Add(seed.Edge); - if (seed.YStart < minY) minY = seed.YStart; - if (seed.Edge.YMaxExclusive > maxYEx) maxYEx = seed.Edge.YMaxExclusive; - } - - Rectangle clipRect = ClipToBounds(clip, target.Width, target.Height); - minY = Math.Max(minY, clipRect.Y); - maxYEx = Math.Min(maxYEx, clipRect.Bottom); - - var active = new List(); - var spans = new ScanlineBuffer(); - - for (int y = minY; y < maxYEx; y++) - { - if (buckets.TryGetValue(y, out List? startEdges)) - active.AddRange(startEdges); - - for (int i = active.Count - 1; i >= 0; i--) - { - if (active[i].YMaxExclusive <= y) - active.RemoveAt(i); - } - - if (active.Count == 0) - continue; - - active.Sort((a, b) => a.CurrentX.CompareTo(b.CurrentX)); - spans.Clear(); - - if (fillMode == FillMode.Alternate) - { - for (int i = 0; i + 1 < active.Count; i += 2) - AddSpan(spans, active[i].CurrentX, active[i + 1].CurrentX, clipRect); - } - else - { - int winding = 0; - float startX = 0f; - for (int i = 0; i < active.Count; i++) - { - int prev = winding; - winding += active[i].Winding; - - if (prev == 0 && winding != 0) - startX = active[i].CurrentX; - else if (prev != 0 && winding == 0) - AddSpan(spans, startX, active[i].CurrentX, clipRect); - } - } - - DrawSpans(target, y, spans, brush, compositingMode, interpolationMode); - - for (int i = 0; i < active.Count; i++) - { - ActiveEdge edge = active[i]; - edge.CurrentX += edge.DxPerY; - active[i] = edge; - } - } - } - - private static void AddSpan(ScanlineBuffer spans, float x0, float x1, Rectangle clipRect) - { - if (x1 <= x0) - return; - - int xs = (int)Math.Ceiling(x0); - int xe = (int)Math.Floor(x1 - 1e-6f); - if (xe < xs) - return; - - if (xs < clipRect.X) xs = clipRect.X; - if (xe >= clipRect.Right) xe = clipRect.Right - 1; - if (xe < xs) - return; - - spans.AddSpan(xs, xe); - } - - private static void DrawSpans( - Bitmap target, - int y, - ScanlineBuffer spans, - Brush brush, - CompositingMode compositingMode, - InterpolationMode interpolationMode) - { - var list = spans.Spans; - for (int i = 0; i < list.Count; i++) - { - int x0 = list[i].X0; - int x1 = list[i].X1; - for (int x = x0; x <= x1; x++) - { - Color src = BrushSampler.Sample(brush, x + 0.5f, y + 0.5f, interpolationMode); - PixelCompositor.BlendPixel(target, x, y, src, compositingMode); - } - } - } - - private static Rectangle ClipToBounds(Rectangle? clip, int width, int height) - { - Rectangle bounds = new Rectangle(0, 0, width, height); - if (!clip.HasValue) - return bounds; - - Rectangle c = clip.Value; - int x = Math.Max(bounds.X, c.X); - int y = Math.Max(bounds.Y, c.Y); - int r = Math.Min(bounds.Right, c.Right); - int b = Math.Min(bounds.Bottom, c.Bottom); - - if (r <= x || b <= y) - return Rectangle.Empty; - - return Rectangle.FromLTRB(x, y, r, b); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/ScanlineBuffer.cs b/src/MiniPdf/Drawing/Rendering/ScanlineBuffer.cs deleted file mode 100644 index b7aaf082..00000000 --- a/src/MiniPdf/Drawing/Rendering/ScanlineBuffer.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Rendering -{ - internal sealed class ScanlineBuffer - { - private readonly List<(int X0, int X1)> _spans = new List<(int X0, int X1)>(); - - public void Clear() => _spans.Clear(); - - public void AddSpan(int x0, int x1) - { - if (x1 < x0) - { - int t = x0; - x0 = x1; - x1 = t; - } - - _spans.Add((x0, x1)); - } - - public IReadOnlyList<(int X0, int X1)> Spans => _spans; - } -} diff --git a/src/MiniPdf/Drawing/Rendering/StrokeExpander.cs b/src/MiniPdf/Drawing/Rendering/StrokeExpander.cs deleted file mode 100644 index 80bc81da..00000000 --- a/src/MiniPdf/Drawing/Rendering/StrokeExpander.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class StrokeExpander - { - public static GraphicsPath Expand(GraphicsPath source, Pens.Pen pen, Matrix? transform = null, float flatness = 0.25f) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (pen == null) throw new ArgumentNullException(nameof(pen)); - - GraphicsPath effective = DashExpander.Expand(source, pen, flatness); - if (transform != null) - effective.Transform(transform); - - effective.Flatten(null, flatness); - - PointF[] points = effective.PathPoints; - byte[] types = effective.PathTypes; - var outline = new GraphicsPath(FillMode.Winding); - - float halfWidth = Math.Max(0.5f, pen.Width * 0.5f); - int subpathStart = -1; - PointF? firstDir = null; - PointF? lastDir = null; - - for (int i = 0; i < points.Length; i++) - { - byte raw = (byte)(types[i] & (byte)PathPointType.PathTypeMask); - if (raw == (byte)PathPointType.Start) - { - subpathStart = i; - firstDir = null; - lastDir = null; - continue; - } - - PointF a = points[i - 1]; - PointF b = points[i]; - PointF dir = new PointF(b.X - a.X, b.Y - a.Y); - if (Math.Abs(dir.X) < 1e-6f && Math.Abs(dir.Y) < 1e-6f) - continue; - - AddSegmentQuad(outline, a, b, halfWidth); - if (firstDir == null) - firstDir = dir; - lastDir = dir; - - bool closes = (types[i] & (byte)PathPointType.CloseSubpath) != 0; - if (closes && subpathStart >= 0 && subpathStart != i) - { - PointF c = points[subpathStart]; - PointF closeDir = new PointF(c.X - b.X, c.Y - b.Y); - if (Math.Abs(closeDir.X) > 1e-6f || Math.Abs(closeDir.Y) > 1e-6f) - AddSegmentQuad(outline, b, c, halfWidth); - } - else if (subpathStart >= 0 && i == subpathStart + 1) - { - LineCapRenderer.AddCap(outline, a, dir, halfWidth, pen.StartCap); - } - - bool endOfOpenSubpath = !closes && (i + 1 >= points.Length || (types[i + 1] & (byte)PathPointType.PathTypeMask) == (byte)PathPointType.Start); - if (endOfOpenSubpath && lastDir != null) - LineCapRenderer.AddCap(outline, b, lastDir.Value, halfWidth, pen.EndCap); - } - - return outline; - } - - private static void AddSegmentQuad(GraphicsPath path, PointF a, PointF b, float halfWidth) - { - float dx = b.X - a.X; - float dy = b.Y - a.Y; - float len = (float)Math.Sqrt(dx * dx + dy * dy); - if (len <= 1e-6f) - return; - - float nx = -dy / len * halfWidth; - float ny = dx / len * halfWidth; - - PointF p0 = new PointF(a.X + nx, a.Y + ny); - PointF p1 = new PointF(a.X - nx, a.Y - ny); - PointF p2 = new PointF(b.X - nx, b.Y - ny); - PointF p3 = new PointF(b.X + nx, b.Y + ny); - path.AddPolygon(new[] { p0, p1, p2, p3 }); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/TextureSampler.cs b/src/MiniPdf/Drawing/Rendering/TextureSampler.cs deleted file mode 100644 index 3a413734..00000000 --- a/src/MiniPdf/Drawing/Rendering/TextureSampler.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Rendering -{ - internal static class TextureSampler - { - public static Color Sample(TextureBrush brush, float x, float y, InterpolationMode interpolation) - { - if (!(brush.Image is Bitmap bmp)) - return Color.Black; - - PointF p = TransformToBrushSpace(new PointF(x, y), brush.Transform); - float u = p.X; - float v = p.Y; - - bool flipX = brush.WrapMode == WrapMode.TileFlipX || brush.WrapMode == WrapMode.TileFlipXY; - bool flipY = brush.WrapMode == WrapMode.TileFlipY || brush.WrapMode == WrapMode.TileFlipXY; - bool clamp = brush.WrapMode == WrapMode.Clamp; - - u = WrapCoordinate(u, bmp.Width, clamp, flipX); - v = WrapCoordinate(v, bmp.Height, clamp, flipY); - - switch (interpolation) - { - case InterpolationMode.Bilinear: - case InterpolationMode.HighQualityBilinear: - case InterpolationMode.Bicubic: - case InterpolationMode.HighQualityBicubic: - return SampleBilinear(bmp, u, v); - default: - return SampleNearest(bmp, u, v); - } - } - - private static PointF TransformToBrushSpace(PointF p, Matrix m) - { - Matrix inv = m.Clone(); - if (!inv.IsInvertible) - return p; - inv.Invert(); - PointF[] pts = new[] { p }; - inv.TransformPoints(pts); - return pts[0]; - } - - private static float WrapCoordinate(float value, int size, bool clamp, bool flip) - { - if (size <= 0) - return 0f; - - if (clamp) - return Math.Max(0f, Math.Min(size - 1, value)); - - float tile = value / size; - int tileIndex = (int)Math.Floor(tile); - float frac = value - tileIndex * size; - if (frac < 0f) - frac += size; - - if (flip && ((tileIndex & 1) != 0)) - frac = (size - 1) - frac; - - return frac; - } - - private static Color SampleNearest(Bitmap bmp, float x, float y) - { - int ix = (int)Math.Round(x); - int iy = (int)Math.Round(y); - ix = Math.Max(0, Math.Min(bmp.Width - 1, ix)); - iy = Math.Max(0, Math.Min(bmp.Height - 1, iy)); - return bmp.GetPixel(ix, iy); - } - - private static Color SampleBilinear(Bitmap bmp, float x, float y) - { - int x0 = (int)Math.Floor(x); - int y0 = (int)Math.Floor(y); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float u = x - x0; - float v = y - y0; - - x0 = Math.Max(0, Math.Min(bmp.Width - 1, x0)); - y0 = Math.Max(0, Math.Min(bmp.Height - 1, y0)); - x1 = Math.Max(0, Math.Min(bmp.Width - 1, x1)); - y1 = Math.Max(0, Math.Min(bmp.Height - 1, y1)); - - Color c00 = bmp.GetPixel(x0, y0); - Color c10 = bmp.GetPixel(x1, y0); - Color c01 = bmp.GetPixel(x0, y1); - Color c11 = bmp.GetPixel(x1, y1); - - return Lerp2D(c00, c10, c01, c11, u, v); - } - - private static Color Lerp2D(Color c00, Color c10, Color c01, Color c11, float u, float v) - { - int a = Bilinear(c00.A, c10.A, c01.A, c11.A, u, v); - int r = Bilinear(c00.R, c10.R, c01.R, c11.R, u, v); - int g = Bilinear(c00.G, c10.G, c01.G, c11.G, u, v); - int b = Bilinear(c00.B, c10.B, c01.B, c11.B, u, v); - return Color.FromArgb(a, r, g, b); - } - - private static int Bilinear(int c00, int c10, int c01, int c11, float u, float v) - { - float top = c00 * (1f - u) + c10 * u; - float bot = c01 * (1f - u) + c11 * u; - return (int)Math.Round(top * (1f - v) + bot * v); - } - } -} diff --git a/src/MiniPdf/Drawing/Rendering/WmfPlayer.cs b/src/MiniPdf/Drawing/Rendering/WmfPlayer.cs deleted file mode 100644 index c8c84a98..00000000 --- a/src/MiniPdf/Drawing/Rendering/WmfPlayer.cs +++ /dev/null @@ -1,355 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Metafile.Wmf.Records; -using MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes; -using MiniSoftware.Drawing.Pens; - -namespace MiniSoftware.Drawing.Rendering -{ - /// - /// Replays WMF records onto any (raster - /// , , or any other - /// context). The legacy overload remains as a thin - /// backward-compat wrapper that creates a raster and - /// delegates to . - /// - internal static class WmfPlayer - { - private sealed class PenState - { - public Color Color = Color.Black; - public float Width = 1f; - public bool IsNull; - } - - private sealed class BrushState - { - public Color Color = Color.Transparent; - public bool IsNull = true; - } - - private readonly struct Viewport - { - private readonly Rectangle _logical; - private readonly float _scaleX; - private readonly float _scaleY; - - public Viewport(Rectangle logicalBounds, int pixelWidth, int pixelHeight) - { - _logical = logicalBounds; - int logicalWidth = Math.Max(1, logicalBounds.Width); - int logicalHeight = Math.Max(1, logicalBounds.Height); - _scaleX = pixelWidth / (float)logicalWidth; - _scaleY = pixelHeight / (float)logicalHeight; - } - - public PointF MapPoint(float x, float y) - { - return new PointF( - (x - _logical.X) * _scaleX, - (y - _logical.Y) * _scaleY); - } - - public RectangleF MapRect(float left, float top, float right, float bottom) - { - float x1 = (left - _logical.X) * _scaleX; - float y1 = (top - _logical.Y) * _scaleY; - float x2 = (right - _logical.X) * _scaleX; - float y2 = (bottom - _logical.Y) * _scaleY; - - float minX = Math.Min(x1, x2); - float minY = Math.Min(y1, y2); - float width = Math.Abs(x2 - x1); - float height = Math.Abs(y2 - y1); - return new RectangleF(minX, minY, width, height); - } - } - - /// - /// Replays WMF records onto the specified drawing context. This is the - /// generalized entry point that targets any surface (raster, recording, - /// SVG, EMF). The context's and - /// define the output pixel size. - /// - /// The metafile document containing WMF records. - /// The target drawing context. - /// The logical bounds of the metafile. - public static void Play(Metafile.MetafileDocument document, IDrawingContext ctx, Rectangle logicalBounds) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - if (ctx == null) - throw new ArgumentNullException(nameof(ctx)); - - var viewport = new Viewport(logicalBounds, ctx.Width, ctx.Height); - var objects = new List(); - - var currentPoint = new PointF(0f, 0f); - var currentPen = new PenState(); - var currentBrush = new BrushState(); - - ctx.Clear(Color.Transparent); - - foreach (var record in document.WmfRecords) - { - switch (record) - { - case META_SETPIXEL setPixel: - { - int x = ClampToPixel(ctx.Width, viewport.MapPoint(setPixel.X, setPixel.Y).X); - int y = ClampToPixel(ctx.Height, viewport.MapPoint(setPixel.X, setPixel.Y).Y); - SetPixel(ctx, x, y, ToColor(setPixel.ColorRef)); - break; - } - case Metafile.Wmf.Records.StateRecordTypes.META_MOVETO moveTo: - currentPoint = viewport.MapPoint(moveTo.X, moveTo.Y); - break; - - case META_LINETO lineTo: - { - var next = viewport.MapPoint(lineTo.X, lineTo.Y); - DrawLine(ctx, currentPen, currentPoint, next); - currentPoint = next; - break; - } - case META_POLYLINE polyline when polyline.aPoints.Length >= 2: - { - var points = new PointF[polyline.aPoints.Length]; - for (int i = 0; i < polyline.aPoints.Length; i++) - { - points[i] = viewport.MapPoint(polyline.aPoints[i].x, polyline.aPoints[i].y); - } - - DrawPolyline(ctx, currentPen, points); - currentPoint = points[points.Length - 1]; - break; - } - case META_POLYGON polygon when polygon.Points.Count >= 2: - { - var points = new PointF[polygon.Points.Count]; - for (int i = 0; i < polygon.Points.Count; i++) - { - Point p = polygon.Points[i]; - points[i] = viewport.MapPoint(p.X, p.Y); - } - - FillPolygon(ctx, currentBrush, points); - DrawPolygon(ctx, currentPen, points); - break; - } - case META_RECTANGLE rectangle: - { - RectangleF rect = viewport.MapRect( - rectangle.LeftRect, - rectangle.TopRect, - rectangle.RightRect, - rectangle.BottomRect); - - FillRectangle(ctx, currentBrush, rect); - DrawRectangle(ctx, currentPen, rect); - break; - } - case META_ELLIPSE ellipse: - { - RectangleF rect = viewport.MapRect( - ellipse.LeftRect, - ellipse.TopRect, - ellipse.RightRect, - ellipse.BottomRect); - - FillEllipse(ctx, currentBrush, rect); - DrawEllipse(ctx, currentPen, rect); - break; - } - case MiniSoftware.Drawing.Metafile.Wmf.Records.ObjectRecordTypes.META_CREATEPENINDIRECT createPen: - AllocateObject(objects, CreatePenState(createPen.Pen)); - break; - - case MetaCreatebrushindirect createBrush: - AllocateObject(objects, CreateBrushState(createBrush.LogBrush)); - break; - - case META_SELECTOBJECT selectObject: - { - if (selectObject.ObjectIndex >= objects.Count) - break; - - object? selected = objects[selectObject.ObjectIndex]; - if (selected is PenState penState) - currentPen = penState; - else if (selected is BrushState brushState) - currentBrush = brushState; - break; - } - case META_DELETEOBJECT deleteObject: - { - if (deleteObject.ObjectIndex < objects.Count) - objects[deleteObject.ObjectIndex] = null; - break; - } - } - } - } - - /// - /// Renders a WMF document to a raster bitmap. This is the backward-compat - /// wrapper that creates a from the bitmap and - /// delegates to . - /// - public static void Render(Metafile.MetafileDocument document, Bitmap target, Rectangle logicalBounds) - { - if (document == null) - throw new ArgumentNullException(nameof(document)); - if (target == null) - throw new ArgumentNullException(nameof(target)); - - using var graphics = Graphics.FromImage(target); - Play(document, graphics, logicalBounds); - } - - private static void AllocateObject(List objects, object value) - { - for (int i = 0; i < objects.Count; i++) - { - if (objects[i] == null) - { - objects[i] = value; - return; - } - } - - objects.Add(value); - } - - private static PenState CreatePenState(Metafile.Wmf.Objects.Pen pen) - { - return new PenState - { - Color = ToColor(pen.ColorRef), - Width = Math.Max(1f, Math.Abs(pen.Width.x)), - IsNull = pen.PenStyle == Metafile.Wmf.Enumerations.PenStyle.PS_NULL, - }; - } - - private static BrushState CreateBrushState(Metafile.Wmf.Objects.LogBrush brush) - { - return new BrushState - { - Color = ToColor(brush.ColorRef), - IsNull = brush.BrushStyle == Metafile.Wmf.Enumerations.BrushStyle.BS_NULL, - }; - } - - private static int ClampToPixel(int size, float value) - { - int v = (int)Math.Round(value); - if (v < 0) return 0; - if (v >= size) return size - 1; - return v; - } - - private static Color ToColor(Metafile.Wmf.Objects.ColorRef color) - => Color.FromArgb(255, color.Red, color.Green, color.Blue); - - private static void SetPixel(IDrawingContext ctx, int x, int y, Color color) - { - using var brush = new SolidBrush(color); - var path = new GraphicsPath(); - path.AddRectangle(new RectangleF(x, y, 1, 1)); - ctx.FillPath(brush, path); - } - - private static void DrawLine(IDrawingContext ctx, PenState penState, PointF p1, PointF p2) - { - if (penState.IsNull) - return; - - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddLine(p1, p2); - ctx.DrawPath(pen, path); - } - - private static void DrawPolyline(IDrawingContext ctx, PenState penState, PointF[] points) - { - if (penState.IsNull) - return; - - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddLines(points); - ctx.DrawPath(pen, path); - } - - private static void DrawPolygon(IDrawingContext ctx, PenState penState, PointF[] points) - { - if (penState.IsNull) - return; - - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddPolygon(points); - ctx.DrawPath(pen, path); - } - - private static void FillPolygon(IDrawingContext ctx, BrushState brushState, PointF[] points) - { - if (brushState.IsNull) - return; - - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddPolygon(points); - ctx.FillPath(brush, path); - } - - private static void DrawRectangle(IDrawingContext ctx, PenState penState, RectangleF rect) - { - if (penState.IsNull) - return; - - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddRectangle(rect); - ctx.DrawPath(pen, path); - } - - private static void FillRectangle(IDrawingContext ctx, BrushState brushState, RectangleF rect) - { - if (brushState.IsNull) - return; - - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddRectangle(rect); - ctx.FillPath(brush, path); - } - - private static void DrawEllipse(IDrawingContext ctx, PenState penState, RectangleF rect) - { - if (penState.IsNull) - return; - - using var pen = new Pen(penState.Color, penState.Width); - var path = new GraphicsPath(); - path.AddEllipse(rect); - ctx.DrawPath(pen, path); - } - - private static void FillEllipse(IDrawingContext ctx, BrushState brushState, RectangleF rect) - { - if (brushState.IsNull) - return; - - using var brush = new SolidBrush(brushState.Color); - var path = new GraphicsPath(); - path.AddEllipse(rect); - ctx.FillPath(brush, path); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiAlgorithm.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiAlgorithm.cs deleted file mode 100644 index 325c8f6f..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiAlgorithm.cs +++ /dev/null @@ -1,688 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Implements the Unicode Bidirectional Algorithm (UAX #9). - /// Pure function: string + paragraph direction → int[] embedding levels. - /// - internal static class BidiAlgorithm - { - private const int MaxDepth = 125; - - /// - /// Computes the Unicode bidirectional embedding level for each UTF-16 - /// code unit in . - /// - internal static int GetLevels(string text, BidiParagraphDirection paragraphDirection, out int[] levels) - { - if (text == null) throw new ArgumentNullException(nameof(text)); - levels = new int[text.Length]; - - if (text.Length == 0) - return 0; - - // ── P1–P3: Determine paragraph level ──────────────────────────── - int baseLevel; - if (paragraphDirection == BidiParagraphDirection.RTL) - baseLevel = 1; - else if (paragraphDirection == BidiParagraphDirection.LTR) - baseLevel = 0; - else - baseLevel = DetermineParagraphLevel(text); - - // ── Get initial character types ───────────────────────────────── - var types = new BidiCharacterType[text.Length]; - for (int i = 0; i < text.Length; i++) - types[i] = BidiCharacterTable.GetType(text, i); - - // ── X1a: Resolve FSI → LRI or RLI ─────────────────────────────── - ResolveFSI(text, types); - - // ── X1–X10: Explicit levels and directions ────────────────────── - ProcessExplicitLevels(text, types, levels, baseLevel); - - // ── W1–W7: Resolve weak types ─────────────────────────────────── - ResolveWeakTypes(types, levels, baseLevel); - - // ── N0–N2: Resolve neutral types ──────────────────────────────── - ResolveNeutralTypes(text, types, levels, baseLevel); - - // ── I1–I2: Resolve implicit levels ────────────────────────────── - ResolveImplicitLevels(types, levels, baseLevel); - - // ── L1: Reset trailing whitespace/segment separators ───────────── - ResetTrailingWhitespace(types, levels, baseLevel); - - return baseLevel; - } - - // ── P1–P3 ─────────────────────────────────────────────────────────── - - private static int DetermineParagraphLevel(string text) - { - for (int i = 0; i < text.Length; i++) - { - var t = BidiCharacterTable.GetType(text, i); - - if (t == BidiCharacterType.FSI || t == BidiCharacterType.LRI || t == BidiCharacterType.RLI) - { - i = SkipIsolate(text, i); - continue; - } - - if (t == BidiCharacterType.L) - return 0; - if (t == BidiCharacterType.R || t == BidiCharacterType.AL) - return 1; - } - return 0; - } - - private static int SkipIsolate(string text, int start) - { - int depth = 1; - for (int i = start + 1; i < text.Length; i++) - { - var t = BidiCharacterTable.GetType(text, i); - if (t == BidiCharacterType.LRI || t == BidiCharacterType.RLI || t == BidiCharacterType.FSI) - depth++; - else if (t == BidiCharacterType.PDI) - { - depth--; - if (depth == 0) return i; - } - } - return text.Length - 1; - } - - // ── X1a: Resolve FSI ──────────────────────────────────────────────── - - private static void ResolveFSI(string text, BidiCharacterType[] types) - { - for (int i = 0; i < types.Length; i++) - { - if (types[i] != BidiCharacterType.FSI) - continue; - - int end = SkipIsolate(text, i); - bool rtl = IsFirstStrongRTL(text, i + 1, end); - types[i] = rtl ? BidiCharacterType.RLI : BidiCharacterType.LRI; - } - } - - private static bool IsFirstStrongRTL(string text, int start, int end) - { - for (int i = start; i < end && i < text.Length; i++) - { - var t = BidiCharacterTable.GetType(text, i); - if (t == BidiCharacterType.L) return false; - if (t == BidiCharacterType.R || t == BidiCharacterType.AL) return true; - if (t == BidiCharacterType.FSI || t == BidiCharacterType.LRI || t == BidiCharacterType.RLI) - i = SkipIsolate(text, i); - } - return false; - } - - // ── X1–X10: Explicit embedding / override / isolate processing ────── - - private struct DirectionalStatus - { - public int EmbeddingLevel; - public BidiCharacterType OverrideStatus; - public bool IsolateStatus; - } - - private static void ProcessExplicitLevels( - string text, - BidiCharacterType[] types, - int[] levels, - int baseLevel) - { - var stack = new Stack(); - stack.Push(new DirectionalStatus - { - EmbeddingLevel = baseLevel, - OverrideStatus = BidiCharacterType.ON, - IsolateStatus = false - }); - - int overflowIsolate = 0; - int overflowEmbedding = 0; - int validIsolate = 0; - - for (int i = 0; i < text.Length; i++) - { - var t = types[i]; - var current = stack.Peek(); - - switch (t) - { - case BidiCharacterType.LRI: - case BidiCharacterType.RLI: - levels[i] = current.EmbeddingLevel; - if (current.OverrideStatus == BidiCharacterType.L) - types[i] = BidiCharacterType.L; - else if (current.OverrideStatus == BidiCharacterType.R) - types[i] = BidiCharacterType.R; - else - types[i] = BidiCharacterType.BN; - - if (overflowIsolate > 0) - { - overflowIsolate++; - } - else if (current.EmbeddingLevel + 1 > MaxDepth) - { - overflowIsolate++; - } - else - { - validIsolate++; - int newLevel = t == BidiCharacterType.LRI - ? NextOddLevel(current.EmbeddingLevel) - : NextEvenLevel(current.EmbeddingLevel); - stack.Push(new DirectionalStatus - { - EmbeddingLevel = newLevel, - OverrideStatus = BidiCharacterType.ON, - IsolateStatus = true - }); - } - break; - - case BidiCharacterType.PDI: - if (overflowIsolate > 0) - { - overflowIsolate--; - levels[i] = current.EmbeddingLevel; - types[i] = BidiCharacterType.BN; - } - else if (validIsolate > 0) - { - overflowEmbedding = 0; - while (stack.Count > 1 && !stack.Peek().IsolateStatus) - stack.Pop(); - if (stack.Count > 1) - stack.Pop(); - validIsolate--; - current = stack.Peek(); - levels[i] = current.EmbeddingLevel; - if (current.OverrideStatus == BidiCharacterType.L) - types[i] = BidiCharacterType.L; - else if (current.OverrideStatus == BidiCharacterType.R) - types[i] = BidiCharacterType.R; - else - types[i] = BidiCharacterType.BN; - } - else - { - levels[i] = current.EmbeddingLevel; - types[i] = BidiCharacterType.BN; - } - break; - - case BidiCharacterType.LRE: - case BidiCharacterType.RLE: - case BidiCharacterType.LRO: - case BidiCharacterType.RLO: - { - levels[i] = current.EmbeddingLevel; - if (current.OverrideStatus != BidiCharacterType.ON) - types[i] = current.OverrideStatus; - else - types[i] = BidiCharacterType.BN; - - bool isOverride = t == BidiCharacterType.LRO || t == BidiCharacterType.RLO; - BidiCharacterType overrideStatus = BidiCharacterType.ON; - if (isOverride) - overrideStatus = (t == BidiCharacterType.LRO) ? BidiCharacterType.L : BidiCharacterType.R; - - if (overflowIsolate > 0 || overflowEmbedding > 0) - { - overflowEmbedding++; - } - else - { - int newLevel = (t == BidiCharacterType.LRE || t == BidiCharacterType.LRO) - ? NextOddLevel(current.EmbeddingLevel) - : NextEvenLevel(current.EmbeddingLevel); - if (newLevel > MaxDepth) - { - overflowEmbedding++; - } - else - { - stack.Push(new DirectionalStatus - { - EmbeddingLevel = newLevel, - OverrideStatus = overrideStatus, - IsolateStatus = false - }); - } - } - } - break; - - case BidiCharacterType.PDF: - levels[i] = current.EmbeddingLevel; - types[i] = BidiCharacterType.BN; - if (overflowIsolate > 0) - { - // ignore - } - else if (overflowEmbedding > 0) - { - overflowEmbedding--; - } - else if (stack.Count > 1 && !stack.Peek().IsolateStatus) - { - stack.Pop(); - } - break; - - case BidiCharacterType.B: - levels[i] = baseLevel; - break; - - case BidiCharacterType.BN: - levels[i] = current.EmbeddingLevel; - break; - - default: - levels[i] = current.EmbeddingLevel; - if (current.OverrideStatus == BidiCharacterType.L) - types[i] = BidiCharacterType.L; - else if (current.OverrideStatus == BidiCharacterType.R) - types[i] = BidiCharacterType.R; - break; - } - } - } - - private static int NextOddLevel(int level) - { - return (level & 1) == 0 ? level + 1 : level + 2; - } - - private static int NextEvenLevel(int level) - { - return (level & 1) == 0 ? level + 2 : level + 1; - } - - // ── W1–W7 ─────────────────────────────────────────────────────────── - - private static void ResolveWeakTypes(BidiCharacterType[] types, int[] levels, int baseLevel) - { - int len = types.Length; - if (len == 0) return; - - var embedDir = baseLevel == 0 ? BidiCharacterType.L : BidiCharacterType.R; - - // W1: NSM inherits previous char's type (or embedding direction at start) - { - BidiCharacterType prevType = embedDir; - for (int i = 0; i < len; i++) - { - if (types[i] == BidiCharacterType.NSM) - { - types[i] = prevType; - } - else if (types[i] != BidiCharacterType.BN) - { - prevType = types[i]; - } - } - } - - // W2: EN after R/AL → AN - { - BidiCharacterType lastStrong = embedDir; - for (int i = 0; i < len; i++) - { - if (types[i] == BidiCharacterType.EN) - { - if (lastStrong == BidiCharacterType.R || lastStrong == BidiCharacterType.AL) - types[i] = BidiCharacterType.AN; - } - else if (IsStrong(types[i])) - { - lastStrong = types[i]; - } - } - } - - // W3: AL → R - for (int i = 0; i < len; i++) - if (types[i] == BidiCharacterType.AL) - types[i] = BidiCharacterType.R; - - // W4: ES between EN-EN → EN; CS between EN-AN or AN-AN → match - for (int i = 1; i < len - 1; i++) - { - if (types[i] == BidiCharacterType.ES && - types[i - 1] == BidiCharacterType.EN && - types[i + 1] == BidiCharacterType.EN) - types[i] = BidiCharacterType.EN; - else if (types[i] == BidiCharacterType.CS) - { - if (types[i - 1] == BidiCharacterType.EN && types[i + 1] == BidiCharacterType.AN) - types[i] = BidiCharacterType.EN; - else if (types[i - 1] == BidiCharacterType.AN && types[i + 1] == BidiCharacterType.EN) - types[i] = BidiCharacterType.AN; - else if (types[i - 1] == BidiCharacterType.AN && types[i + 1] == BidiCharacterType.AN) - types[i] = BidiCharacterType.AN; - } - } - - // W5: ET sequences adjacent to EN → EN - for (int i = 0; i < len; i++) - { - if (types[i] == BidiCharacterType.ET) - { - int j = i; - while (j < len && types[j] == BidiCharacterType.ET) j++; - bool convert = (j < len && types[j] == BidiCharacterType.EN) || - (i > 0 && types[i - 1] == BidiCharacterType.EN); - if (convert) - for (int k = i; k < j; k++) - types[k] = BidiCharacterType.EN; - i = j - 1; - } - } - - // W6: Remaining ES, ET, CS → ON - for (int i = 0; i < len; i++) - if (types[i] == BidiCharacterType.ES || types[i] == BidiCharacterType.ET || types[i] == BidiCharacterType.CS) - types[i] = BidiCharacterType.ON; - - // W7: EN with last strong L → L - { - BidiCharacterType lastStrong = embedDir; - for (int i = 0; i < len; i++) - { - if (types[i] == BidiCharacterType.EN && lastStrong == BidiCharacterType.L) - types[i] = BidiCharacterType.L; - else if (IsStrong(types[i])) - lastStrong = types[i]; - } - } - } - - private static bool IsStrong(BidiCharacterType t) - => t == BidiCharacterType.L || t == BidiCharacterType.R; - - // ── N0–N2 ─────────────────────────────────────────────────────────── - - private static void ResolveNeutralTypes(string text, BidiCharacterType[] types, int[] levels, int baseLevel) - { - int len = types.Length; - if (len == 0) return; - - // N0: Resolve bracket pairs - ResolveBracketPairs(text, types, baseLevel); - - // N1–N2: Resolve neutral sequences - for (int i = 0; i < len; i++) - { - if (!IsNeutral(types[i])) continue; - - int start = i; - while (i < len && IsNeutral(types[i])) i++; - int end = i; - - BidiCharacterType? left = LeftStrongOrNumber(types, start); - BidiCharacterType? right = RightStrongOrNumber(types, end); - - BidiCharacterType resolved; - if (left.HasValue && right.HasValue) - { - if (left == right) - resolved = left.Value; - else - resolved = baseLevel == 0 ? BidiCharacterType.L : BidiCharacterType.R; - } - else if (left.HasValue) - resolved = left.Value; - else if (right.HasValue) - resolved = right.Value; - else - resolved = baseLevel == 0 ? BidiCharacterType.L : BidiCharacterType.R; - - for (int j = start; j < end; j++) - types[j] = resolved; - - i = end - 1; - } - } - - private static BidiCharacterType? LeftStrongOrNumber(BidiCharacterType[] types, int from) - { - for (int j = from - 1; j >= 0; j--) - { - if (IsStrong(types[j])) return types[j]; - if (types[j] == BidiCharacterType.AN || types[j] == BidiCharacterType.EN) - return BidiCharacterType.R; - } - return null; - } - - private static BidiCharacterType? RightStrongOrNumber(BidiCharacterType[] types, int from) - { - for (int j = from; j < types.Length; j++) - { - if (IsStrong(types[j])) return types[j]; - if (types[j] == BidiCharacterType.AN || types[j] == BidiCharacterType.EN) - return BidiCharacterType.R; - } - return null; - } - - private static bool IsNeutral(BidiCharacterType t) - => t == BidiCharacterType.ON || t == BidiCharacterType.WS || - t == BidiCharacterType.B || t == BidiCharacterType.S; - - private static void ResolveBracketPairs(string text, BidiCharacterType[] types, int baseLevel) - { - int len = types.Length; - var embedDir = baseLevel == 0 ? BidiCharacterType.L : BidiCharacterType.R; - - for (int i = 0; i < len; i++) - { - uint cp = CodePointAt(text, i); - var bracketType = BidiBrackets.GetBracketType(cp); - - if (bracketType != BidiBracketType.Open) - continue; - - uint pair = BidiBrackets.GetPairedBracket(cp); - - // Scan forward for the matching close bracket, respecting nesting - int depth = 1; - int closeIdx = -1; - for (int j = i + 1; j < len; j++) - { - // Skip characters on a different embedding level - // (bracket pairs must be on the same level) - uint jcp = CodePointAt(text, j); - var jt = BidiBrackets.GetBracketType(jcp); - - if (jt == BidiBracketType.Open) - depth++; - else if (jt == BidiBracketType.Close) - { - if (BidiBrackets.GetPairedBracket(jcp) == cp || jcp == pair) - { - depth--; - if (depth == 0) - { - closeIdx = j; - break; - } - } - } - - // Advance past surrogate pairs - if (char.IsHighSurrogate(text[j]) && j + 1 < text.Length && char.IsLowSurrogate(text[j + 1])) - j++; - } - - if (closeIdx < 0) - continue; - - // Check the direction of the enclosing context - // Look at the strong type immediately before the opening bracket - BidiCharacterType? dirBefore = null; - for (int j = i - 1; j >= 0; j--) - { - if (IsStrong(types[j])) - { - dirBefore = types[j]; - break; - } - if (types[j] == BidiCharacterType.AN || types[j] == BidiCharacterType.EN) - { - dirBefore = BidiCharacterType.R; - break; - } - } - - // Look at the strong type immediately after the closing bracket - BidiCharacterType? dirAfter = null; - for (int j = closeIdx + 1; j < len; j++) - { - if (IsStrong(types[j])) - { - dirAfter = types[j]; - break; - } - if (types[j] == BidiCharacterType.AN || types[j] == BidiCharacterType.EN) - { - dirAfter = BidiCharacterType.R; - break; - } - } - - // N0b: If dirBefore == dirAfter, bracket content takes that direction - // N0c: If dirBefore != dirAfter, check if content has a strong char matching embedDir - BidiCharacterType bracketDir; - if (dirBefore.HasValue && dirAfter.HasValue && dirBefore == dirAfter) - { - bracketDir = dirBefore.Value; - } - else - { - // Check if any char inside brackets is strong and matches embedding direction - bool foundEmbed = false; - bool foundOpposite = false; - for (int j = i + 1; j < closeIdx; j++) - { - if (IsStrong(types[j])) - { - if (types[j] == embedDir) foundEmbed = true; - else foundOpposite = true; - } - if (types[j] == BidiCharacterType.AN || types[j] == BidiCharacterType.EN) - { - if (embedDir == BidiCharacterType.R) foundEmbed = true; - else foundOpposite = true; - } - } - - if (foundEmbed) - bracketDir = embedDir; - else if (dirBefore.HasValue) - bracketDir = dirBefore.Value; - else if (dirAfter.HasValue) - bracketDir = dirAfter.Value; - else - bracketDir = embedDir; - } - - // Set bracket characters and enclosed neutrals to bracketDir - types[i] = bracketDir; - types[closeIdx] = bracketDir; - for (int j = i + 1; j < closeIdx; j++) - { - if (IsNeutral(types[j])) - types[j] = bracketDir; - } - - // Advance past the close bracket - i = closeIdx; - } - } - - private static uint CodePointAt(string text, int index) - { - char c = text[index]; - if (char.IsHighSurrogate(c) && index + 1 < text.Length && char.IsLowSurrogate(text[index + 1])) - return (uint)char.ConvertToUtf32(c, text[index + 1]); - return (uint)c; - } - - // ── I1–I2 ─────────────────────────────────────────────────────────── - - private static void ResolveImplicitLevels(BidiCharacterType[] types, int[] levels, int baseLevel) - { - for (int i = 0; i < types.Length; i++) - { - if ((levels[i] & 1) == 0) - { - if (types[i] == BidiCharacterType.R) - levels[i] += 1; - else if (types[i] == BidiCharacterType.AN || types[i] == BidiCharacterType.EN) - levels[i] += 2; - } - else - { - if (types[i] == BidiCharacterType.L || - types[i] == BidiCharacterType.EN || - types[i] == BidiCharacterType.AN) - { - levels[i] += 1; - } - } - } - } - - // ── L1 ────────────────────────────────────────────────────────────── - - private static void ResetTrailingWhitespace(BidiCharacterType[] types, int[] levels, int baseLevel) - { - int len = levels.Length; - - for (int i = len - 1; i >= 0; i--) - { - var t = types[i]; - if (t == BidiCharacterType.WS || t == BidiCharacterType.B || - t == BidiCharacterType.S || t == BidiCharacterType.BN) - { - levels[i] = baseLevel; - } - else - break; - } - - for (int i = 0; i < len; i++) - { - if (types[i] == BidiCharacterType.B) - { - for (int j = i - 1; j >= 0; j--) - { - if (types[j] == BidiCharacterType.WS || types[j] == BidiCharacterType.S || types[j] == BidiCharacterType.BN) - levels[j] = baseLevel; - else - break; - } - levels[i] = baseLevel; - } - else if (types[i] == BidiCharacterType.S) - { - levels[i] = baseLevel; - } - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiBrackets.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiBrackets.cs deleted file mode 100644 index 293ee3bf..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiBrackets.cs +++ /dev/null @@ -1,183 +0,0 @@ -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Bracket type for UAX #9 N0 (bracket pair resolution). - /// - internal enum BidiBracketType : byte - { - None = 0, - Open = 1, - Close = 2, - } - - /// - /// Bidirectional bracket pairs (UAX #9 §3.1.3, from BidiBrackets.txt). - /// Maps an opening bracket code point to its closing bracket code point, - /// and vice versa. Used by the N0 rule. - /// - internal static class BidiBrackets - { - // (codePoint, pairedCodePoint, type) - private static readonly (uint Cp, uint Pair, BidiBracketType Type)[] s_brackets = - { - (0x0028, 0x0029, BidiBracketType.Open), // ( ) - (0x0029, 0x0028, BidiBracketType.Close), - (0x005B, 0x005D, BidiBracketType.Open), // [ ] - (0x005D, 0x005B, BidiBracketType.Close), - (0x007B, 0x007D, BidiBracketType.Open), // { } - (0x007D, 0x007B, BidiBracketType.Close), - (0x0F3A, 0x0F3B, BidiBracketType.Open), // Tibetan marks - (0x0F3B, 0x0F3A, BidiBracketType.Close), - (0x0F3C, 0x0F3D, BidiBracketType.Open), - (0x0F3D, 0x0F3C, BidiBracketType.Close), - (0x169B, 0x169C, BidiBracketType.Open), // Ogham - (0x169C, 0x169B, BidiBracketType.Close), - (0x2018, 0x2019, BidiBracketType.Open), // ' ' - (0x2019, 0x2018, BidiBracketType.Close), - (0x201C, 0x201D, BidiBracketType.Open), // " " - (0x201D, 0x201C, BidiBracketType.Close), - (0x2039, 0x203A, BidiBracketType.Open), // ‹ › - (0x203A, 0x2039, BidiBracketType.Close), - (0x2045, 0x2046, BidiBracketType.Open), // ⁅ ⁆ - (0x2046, 0x2045, BidiBracketType.Close), - (0x207D, 0x207E, BidiBracketType.Open), // ⁽ ⁾ - (0x207E, 0x207D, BidiBracketType.Close), - (0x208D, 0x208E, BidiBracketType.Open), // ₍ ₎ - (0x208E, 0x208D, BidiBracketType.Close), - (0x2308, 0x2309, BidiBracketType.Open), // ⌈ ⌉ - (0x2309, 0x2308, BidiBracketType.Close), - (0x230A, 0x230B, BidiBracketType.Open), // ⌊ ⌋ - (0x230B, 0x230A, BidiBracketType.Close), - (0x2329, 0x232A, BidiBracketType.Open), // 〈 〉 - (0x232A, 0x2329, BidiBracketType.Close), - (0x2768, 0x2769, BidiBracketType.Open), // ❨ ❩ - (0x2769, 0x2768, BidiBracketType.Close), - (0x276A, 0x276B, BidiBracketType.Open), - (0x276B, 0x276A, BidiBracketType.Close), - (0x276C, 0x276D, BidiBracketType.Open), - (0x276D, 0x276C, BidiBracketType.Close), - (0x276E, 0x276F, BidiBracketType.Open), - (0x276F, 0x276E, BidiBracketType.Close), - (0x2770, 0x2771, BidiBracketType.Open), - (0x2771, 0x2770, BidiBracketType.Close), - (0x2772, 0x2773, BidiBracketType.Open), - (0x2773, 0x2772, BidiBracketType.Close), - (0x2774, 0x2775, BidiBracketType.Open), - (0x2775, 0x2774, BidiBracketType.Close), - (0x27C5, 0x27C6, BidiBracketType.Open), // ⟅ ⟆ - (0x27C6, 0x27C5, BidiBracketType.Close), - (0x27E6, 0x27E7, BidiBracketType.Open), // ⟦ ⟧ - (0x27E7, 0x27E6, BidiBracketType.Close), - (0x27E8, 0x27E9, BidiBracketType.Open), // ⟨ ⟩ - (0x27E9, 0x27E8, BidiBracketType.Close), - (0x27EA, 0x27EB, BidiBracketType.Open), // ⟪ ⟫ - (0x27EB, 0x27EA, BidiBracketType.Close), - (0x27EC, 0x27ED, BidiBracketType.Open), // ⟬ ⟭ - (0x27ED, 0x27EC, BidiBracketType.Close), - (0x27EE, 0x27EF, BidiBracketType.Open), // ⟮ ⟯ - (0x27EF, 0x27EE, BidiBracketType.Close), - (0x2983, 0x2984, BidiBracketType.Open), // ⦃ ⦄ - (0x2984, 0x2983, BidiBracketType.Close), - (0x2985, 0x2986, BidiBracketType.Open), - (0x2986, 0x2985, BidiBracketType.Close), - (0x2987, 0x2988, BidiBracketType.Open), - (0x2988, 0x2987, BidiBracketType.Close), - (0x2989, 0x298A, BidiBracketType.Open), - (0x298A, 0x2989, BidiBracketType.Close), - (0x298B, 0x298C, BidiBracketType.Open), - (0x298C, 0x298B, BidiBracketType.Close), - (0x298D, 0x2990, BidiBracketType.Open), - (0x298E, 0x298F, BidiBracketType.Close), - (0x298F, 0x298E, BidiBracketType.Open), - (0x2990, 0x298D, BidiBracketType.Close), - (0x2991, 0x2992, BidiBracketType.Open), - (0x2992, 0x2991, BidiBracketType.Close), - (0x2993, 0x2994, BidiBracketType.Open), - (0x2994, 0x2993, BidiBracketType.Close), - (0x2995, 0x2996, BidiBracketType.Open), - (0x2996, 0x2995, BidiBracketType.Close), - (0x2997, 0x2998, BidiBracketType.Open), - (0x2998, 0x2997, BidiBracketType.Close), - (0x29D8, 0x29D9, BidiBracketType.Open), - (0x29D9, 0x29D8, BidiBracketType.Close), - (0x29DA, 0x29DB, BidiBracketType.Open), - (0x29DB, 0x29DA, BidiBracketType.Close), - (0x29FC, 0x29FD, BidiBracketType.Open), - (0x29FD, 0x29FC, BidiBracketType.Close), - (0x2E22, 0x2E23, BidiBracketType.Open), // ⸢ ⸣ - (0x2E23, 0x2E22, BidiBracketType.Close), - (0x2E24, 0x2E25, BidiBracketType.Open), // ⸤ ⸥ - (0x2E25, 0x2E24, BidiBracketType.Close), - (0x2E26, 0x2E27, BidiBracketType.Open), - (0x2E27, 0x2E26, BidiBracketType.Close), - (0x2E28, 0x2E29, BidiBracketType.Open), - (0x2E29, 0x2E28, BidiBracketType.Close), - (0x3008, 0x3009, BidiBracketType.Open), // 〈 〉 - (0x3009, 0x3008, BidiBracketType.Close), - (0x300A, 0x300B, BidiBracketType.Open), // 《 》 - (0x300B, 0x300A, BidiBracketType.Close), - (0x300C, 0x300D, BidiBracketType.Open), // 「 」 - (0x300D, 0x300C, BidiBracketType.Close), - (0x300E, 0x300F, BidiBracketType.Open), // 『 』 - (0x300F, 0x300E, BidiBracketType.Close), - (0x3010, 0x3011, BidiBracketType.Open), // 【 】 - (0x3011, 0x3010, BidiBracketType.Close), - (0x3014, 0x3015, BidiBracketType.Open), // 〔 〕 - (0x3015, 0x3014, BidiBracketType.Close), - (0x3016, 0x3017, BidiBracketType.Open), // 〖 〗 - (0x3017, 0x3016, BidiBracketType.Close), - (0x3018, 0x3019, BidiBracketType.Open), // 〘 〙 - (0x3019, 0x3018, BidiBracketType.Close), - (0x301A, 0x301B, BidiBracketType.Open), // 〚 〛 - (0x301B, 0x301A, BidiBracketType.Close), - (0xFE59, 0xFE5A, BidiBracketType.Open), // Small ( ) - (0xFE5A, 0xFE59, BidiBracketType.Close), - (0xFE5B, 0xFE5C, BidiBracketType.Open), // Small { } - (0xFE5C, 0xFE5B, BidiBracketType.Close), - (0xFE5D, 0xFE5E, BidiBracketType.Open), // Small [ ] - (0xFE5E, 0xFE5D, BidiBracketType.Close), - (0xFF08, 0xFF09, BidiBracketType.Open), // Fullwidth ( ) - (0xFF09, 0xFF08, BidiBracketType.Close), - (0xFF3B, 0xFF3D, BidiBracketType.Open), // Fullwidth [ ] - (0xFF3D, 0xFF3B, BidiBracketType.Close), - (0xFF5B, 0xFF5D, BidiBracketType.Open), // Fullwidth { } - (0xFF5D, 0xFF5B, BidiBracketType.Close), - (0xFF5F, 0xFF60, BidiBracketType.Open), // Fullwidth ⦅ ⦆ - (0xFF60, 0xFF5F, BidiBracketType.Close), - (0xFF62, 0xFF63, BidiBracketType.Open), // Halfwidth 「 」 - (0xFF63, 0xFF62, BidiBracketType.Close), - }; - - /// - /// Returns the bracket type for , - /// or if it is not a bracket. - /// - internal static BidiBracketType GetBracketType(uint codePoint) - { - foreach (var (cp, pair, type) in s_brackets) - { - if (cp == codePoint) - return type; - if (cp > codePoint) - break; - } - return BidiBracketType.None; - } - - /// - /// Returns the paired bracket code point for , - /// or 0 if is not a bracket. - /// - internal static uint GetPairedBracket(uint codePoint) - { - foreach (var (cp, pair, type) in s_brackets) - { - if (cp == codePoint) - return pair; - if (cp > codePoint) - break; - } - return 0; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterTable.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterTable.cs deleted file mode 100644 index c5e4e877..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterTable.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Lookup table for Unicode bidirectional character types (UAX #9 §4.2). - /// Encoded as a sorted range table covering the major script ranges. - /// Code points not listed default to - /// (Left-to-Right), which is correct for unassigned code points per UAX #9. - /// - internal static class BidiCharacterTable - { - // Sorted by start code point. Binary-searched at runtime. - private static readonly (uint Start, uint End, BidiCharacterType Type)[] s_ranges; - - static BidiCharacterTable() - { - s_ranges = new (uint Start, uint End, BidiCharacterType Type)[] - { - // ── Control / format / whitespace ────────────────────────────── - (0x0009, 0x0009, BidiCharacterType.S), // TAB - (0x000A, 0x000A, BidiCharacterType.B), // LF - (0x000B, 0x000B, BidiCharacterType.S), // VT - (0x000C, 0x000C, BidiCharacterType.B), // FF - (0x000D, 0x000D, BidiCharacterType.B), // CR - (0x001C, 0x001E, BidiCharacterType.B), // File/Group/Record Separator - (0x001F, 0x001F, BidiCharacterType.S), // Unit Separator - (0x0020, 0x0020, BidiCharacterType.WS), // SPACE - (0x0085, 0x0085, BidiCharacterType.B), // NEL - (0x00A0, 0x00A0, BidiCharacterType.CS), // NBSP - (0x00A1, 0x00A1, BidiCharacterType.ON), // ¡ - (0x00A2, 0x00A5, BidiCharacterType.ET), // ¢ £ ¤ ¥ - (0x00A6, 0x00A9, BidiCharacterType.ON), // ¦ § ¨ © - (0x00AA, 0x00AA, BidiCharacterType.L), // ª (feminine ordinal) - (0x00AB, 0x00AC, BidiCharacterType.ON), // « ¬ - (0x00AD, 0x00AD, BidiCharacterType.BN), // SOFT HYPHEN - (0x00AE, 0x00AF, BidiCharacterType.ON), // ® ¯ - (0x00B0, 0x00B1, BidiCharacterType.ET), // ° ± - (0x00B2, 0x00B3, BidiCharacterType.EN), // ² ³ - (0x00B4, 0x00B4, BidiCharacterType.ON), // ´ - (0x00B5, 0x00B5, BidiCharacterType.L), // µ - (0x00B6, 0x00B8, BidiCharacterType.ON), // ¶ · ¸ - (0x00B9, 0x00B9, BidiCharacterType.EN), // ¹ - (0x00BA, 0x00BA, BidiCharacterType.L), // º (masculine ordinal) - (0x00BB, 0x00BF, BidiCharacterType.ON), // » ¼ ½ ¾ ¿ - (0x00D7, 0x00D7, BidiCharacterType.ON), // × - (0x00F7, 0x00F7, BidiCharacterType.ON), // ÷ - - // ── European digits ──────────────────────────────────────────── - (0x0030, 0x0039, BidiCharacterType.EN), // 0-9 - (0x002B, 0x002B, BidiCharacterType.ES), // + - (0x002D, 0x002D, BidiCharacterType.ES), // - - (0x002E, 0x002E, BidiCharacterType.CS), // . - (0x002F, 0x002F, BidiCharacterType.CS), // / - (0x0021, 0x0022, BidiCharacterType.ON), // ! " - (0x0023, 0x0025, BidiCharacterType.ET), // # $ % - (0x0026, 0x0027, BidiCharacterType.ON), // & ' - (0x0028, 0x0029, BidiCharacterType.ON), // ( ) - (0x002A, 0x002A, BidiCharacterType.ON), // * - (0x002C, 0x002C, BidiCharacterType.CS), // , - (0x003A, 0x003B, BidiCharacterType.CS), // : ; - (0x003C, 0x003E, BidiCharacterType.ON), // < = > - (0x003F, 0x0040, BidiCharacterType.ON), // ? @ - (0x005B, 0x005E, BidiCharacterType.ON), // [ \ ] ^ - (0x0060, 0x0060, BidiCharacterType.ON), // ` - (0x007B, 0x007E, BidiCharacterType.ON), // { | } ~ - - // ── Superscript/subscript digits ────────────────────────────── - // ── Arabic ──────────────────────────────────────────────────── - (0x0600, 0x0605, BidiCharacterType.AN), // Arabic number signs - (0x0606, 0x0607, BidiCharacterType.ON), // Arabic operator symbols - (0x0608, 0x0608, BidiCharacterType.ON), // Arabic ray - (0x0609, 0x060A, BidiCharacterType.ET), // Arabic-Indic per mille, per ten thousand - (0x060B, 0x060B, BidiCharacterType.AL), // Arabic afghanistan sign - (0x060C, 0x060C, BidiCharacterType.CS), // Arabic comma - (0x060D, 0x060F, BidiCharacterType.AL), // Arabic date separator, etc. - (0x0610, 0x061A, BidiCharacterType.NSM), // Arabic marks - (0x061B, 0x061B, BidiCharacterType.ON), // Arabic semicolon - (0x061C, 0x061C, BidiCharacterType.AL), // Arabic letter mark - (0x061E, 0x061F, BidiCharacterType.ON), // Arabic question mark - (0x0620, 0x063F, BidiCharacterType.AL), // Arabic letters - (0x0640, 0x0640, BidiCharacterType.AL), // Arabic tatweel - (0x0641, 0x064A, BidiCharacterType.AL), // Arabic letters - (0x064B, 0x065F, BidiCharacterType.NSM), // Arabic diacritics - (0x0660, 0x0669, BidiCharacterType.AN), // Arabic-Indic digits - (0x066A, 0x066A, BidiCharacterType.ET), // Arabic percent - (0x066B, 0x066C, BidiCharacterType.AN), // Arabic decimal separator, thousands separator - (0x066D, 0x066F, BidiCharacterType.AL), // Arabic five-pointed star etc. - (0x0670, 0x0670, BidiCharacterType.NSM), // Arabic superscript alef - (0x0671, 0x06D5, BidiCharacterType.AL), // Arabic letters - (0x06D6, 0x06DC, BidiCharacterType.NSM), // Arabic marks - (0x06DD, 0x06DD, BidiCharacterType.AN), // Arabic end of ayah - (0x06DE, 0x06DE, BidiCharacterType.ON), // Arabic start of rub el hizb - (0x06DF, 0x06E4, BidiCharacterType.NSM), // Arabic marks - (0x06E5, 0x06E6, BidiCharacterType.AL), // Arabic sawal, madda - (0x06E7, 0x06E8, BidiCharacterType.NSM), // Arabic marks - (0x06E9, 0x06E9, BidiCharacterType.ON), // Arabic place of sajdah - (0x06EA, 0x06ED, BidiCharacterType.NSM), // Arabic marks - (0x06EE, 0x06EF, BidiCharacterType.AL), // Arabic letter dal with ring, dot - (0x06F0, 0x06F9, BidiCharacterType.EN), // Extended Arabic-Indic digits - (0x06FA, 0x06FF, BidiCharacterType.AL), // Arabic letters - - // ── Syriac ──────────────────────────────────────────────────── - (0x0700, 0x070D, BidiCharacterType.AL), - (0x070F, 0x070F, BidiCharacterType.AL), // Syriac abbreviation mark - (0x0710, 0x074A, BidiCharacterType.AL), - (0x074D, 0x074F, BidiCharacterType.AL), - - // ── Arabic Supplement ───────────────────────────────────────── - (0x0750, 0x077F, BidiCharacterType.AL), - - // ── Thaana ──────────────────────────────────────────────────── - (0x0780, 0x07A5, BidiCharacterType.AL), - (0x07A6, 0x07B0, BidiCharacterType.NSM), - (0x07B1, 0x07B1, BidiCharacterType.AL), - - // ── NKo ─────────────────────────────────────────────────────── - (0x07C0, 0x07FA, BidiCharacterType.R), - - // ── Samaritan ───────────────────────────────────────────────── - (0x0800, 0x082D, BidiCharacterType.AL), - (0x0830, 0x083E, BidiCharacterType.AL), - - // ── Mandaic ─────────────────────────────────────────────────── - (0x0840, 0x085B, BidiCharacterType.AL), - (0x085E, 0x085E, BidiCharacterType.AL), - - // ── Arabic Extended-A ───────────────────────────────────────── - (0x08A0, 0x08B4, BidiCharacterType.AL), - (0x08B6, 0x08BD, BidiCharacterType.AL), - - // ── Hebrew ──────────────────────────────────────────────────── - (0x0591, 0x05BD, BidiCharacterType.NSM), - (0x05BE, 0x05BE, BidiCharacterType.R), - (0x05BF, 0x05BF, BidiCharacterType.NSM), - (0x05C0, 0x05C0, BidiCharacterType.R), - (0x05C1, 0x05C2, BidiCharacterType.NSM), - (0x05C3, 0x05C3, BidiCharacterType.R), - (0x05C4, 0x05C5, BidiCharacterType.NSM), - (0x05C6, 0x05C6, BidiCharacterType.R), - (0x05C7, 0x05C7, BidiCharacterType.NSM), - (0x05D0, 0x05EA, BidiCharacterType.R), - (0x05F0, 0x05F4, BidiCharacterType.R), - - // ── Format characters (explicit embedding/override/isolate) ─── - (0x200B, 0x200D, BidiCharacterType.BN), // ZWSP, ZWNJ, ZWJ - (0x200E, 0x200E, BidiCharacterType.L), // LRM - (0x200F, 0x200F, BidiCharacterType.R), // RLM - (0x2028, 0x2028, BidiCharacterType.WS), // LINE SEPARATOR (treated as B in some impls) - (0x2029, 0x2029, BidiCharacterType.B), // PARAGRAPH SEPARATOR - (0x202A, 0x202A, BidiCharacterType.LRE), - (0x202B, 0x202B, BidiCharacterType.RLE), - (0x202C, 0x202C, BidiCharacterType.PDF), - (0x202D, 0x202D, BidiCharacterType.LRO), - (0x202E, 0x202E, BidiCharacterType.RLO), - (0x2060, 0x2064, BidiCharacterType.BN), // Word joiner etc. - (0x2066, 0x2066, BidiCharacterType.LRI), - (0x2067, 0x2067, BidiCharacterType.RLI), - (0x2068, 0x2068, BidiCharacterType.FSI), - (0x2069, 0x2069, BidiCharacterType.PDI), - (0x206A, 0x206F, BidiCharacterType.BN), // Deprecated format controls - - // ── Whitespace ──────────────────────────────────────────────── - (0x1680, 0x1680, BidiCharacterType.WS), // OGHAM SPACE MARK - (0x2000, 0x200A, BidiCharacterType.WS), // Various spaces - (0x2028, 0x2028, BidiCharacterType.WS), // LINE SEPARATOR - (0x202F, 0x202F, BidiCharacterType.CS), // NARROW NBSP - (0x205F, 0x205F, BidiCharacterType.WS), // MEDIUM MATHEMATICAL SPACE - (0x3000, 0x3000, BidiCharacterType.WS), // IDEOGRAPHIC SPACE - - // ── Currency symbols ────────────────────────────────────────── - (0x09F2, 0x09F3, BidiCharacterType.ET), // Bengali currency - (0x0AF1, 0x0AF1, BidiCharacterType.ET), // Gujarati rupee - (0x0BF9, 0x0BF9, BidiCharacterType.ET), // Tamil rupee - (0x0E3F, 0x0E3F, BidiCharacterType.ET), // Thai baht - (0x17DB, 0x17DB, BidiCharacterType.ET), // Khmer riel - (0x2030, 0x2034, BidiCharacterType.ET), // ‰ ‱ ′ ″ ‴ - (0x20A0, 0x20C0, BidiCharacterType.ET), // Currency symbols - (0xFE5F, 0xFE6F, BidiCharacterType.ET), // Small currency symbols - - // ── Hebrew presentation forms ───────────────────────────────── - (0xFB1D, 0xFB4F, BidiCharacterType.R), - - // ── Arabic presentation forms-A ─────────────────────────────── - (0xFB1E, 0xFB1E, BidiCharacterType.NSM), // Hebrew point - (0xFB50, 0xFDFF, BidiCharacterType.AL), - - // ── Arabic presentation forms-B ─────────────────────────────── - (0xFE00, 0xFE0F, BidiCharacterType.NSM), // Variation selectors - (0xFE70, 0xFEFE, BidiCharacterType.AL), - - // ── Right-to-left historic scripts ──────────────────────────── - (0x10800, 0x10805, BidiCharacterType.R), // Cypriot syllabary - (0x10808, 0x10808, BidiCharacterType.R), - (0x1080A, 0x10835, BidiCharacterType.R), - (0x10837, 0x10838, BidiCharacterType.R), - (0x1083C, 0x1083C, BidiCharacterType.R), - (0x1083F, 0x1083F, BidiCharacterType.R), - (0x10900, 0x1091B, BidiCharacterType.R), // Phoenician - (0x10920, 0x10939, BidiCharacterType.R), // Lydian - (0x10980, 0x109B7, BidiCharacterType.R), // Meroitic hieroglyphs - (0x10A00, 0x10A03, BidiCharacterType.R), // Kharoshthi - (0x10A05, 0x10A06, BidiCharacterType.R), - (0x10A0C, 0x10A13, BidiCharacterType.R), - (0x10A15, 0x10A17, BidiCharacterType.R), - (0x10A19, 0x10A33, BidiCharacterType.R), - (0x10A38, 0x10A3A, BidiCharacterType.NSM), - (0x10A3F, 0x10A3F, BidiCharacterType.NSM), - (0x10A40, 0x10A47, BidiCharacterType.AN), // Kharoshthi numbers - (0x10A50, 0x10A58, BidiCharacterType.R), - (0x10A60, 0x10A7C, BidiCharacterType.R), // Old South Arabian - (0x10A80, 0x10A9C, BidiCharacterType.R), // Old North Arabian - (0x10AC0, 0x10AC7, BidiCharacterType.R), // Manichaean - (0x10AC9, 0x10AE4, BidiCharacterType.R), - (0x10AE7, 0x10AEA, BidiCharacterType.NSM), - (0x10AEB, 0x10AEF, BidiCharacterType.R), - (0x10B00, 0x10B35, BidiCharacterType.R), // Avestan - (0x10B40, 0x10B55, BidiCharacterType.R), // Inscriptional Parthian - (0x10B58, 0x10B72, BidiCharacterType.R), // Inscriptional Pahlavi - (0x10B78, 0x10B91, BidiCharacterType.R), // Psalter Pahlavi - (0x10C00, 0x10C48, BidiCharacterType.R), // Old Turkic - (0x10C80, 0x10CB2, BidiCharacterType.R), // Old Hungarian - (0x10D00, 0x10D23, BidiCharacterType.R), // Hanifi Rohingya - (0x10E60, 0x10E7E, BidiCharacterType.AN), // Rumi number digits - (0x10F30, 0x10F45, BidiCharacterType.R), // Sogdian - (0x10F51, 0x10F54, BidiCharacterType.R), - (0x10FB0, 0x10FC4, BidiCharacterType.R), // Chorasmian - (0x10FE0, 0x10FF6, BidiCharacterType.R), // Sogdian (old) - (0x1E800, 0x1E8C4, BidiCharacterType.R), // Mende Kikakui - (0x1E8C7, 0x1E8CF, BidiCharacterType.AN), - (0x1E900, 0x1E943, BidiCharacterType.AL), // Adlam - (0x1E94B, 0x1E94B, BidiCharacterType.AL), - - // ── Tibetan digits ──────────────────────────────────────────── - (0x0F20, 0x0F33, BidiCharacterType.ON), // Tibetan digits (treated as ON) - - // ── Ideographic ─────────────────────────────────────────────── - // CJK, Hiragana, Katakana, Hangul etc. are all L (left-to-right) - // per UAX #9. No entry needed — defaults to L. - }; - - // Sort by start code point so binary search works correctly. - System.Array.Sort(s_ranges, (a, b) => a.Start.CompareTo(b.Start)); - } - - /// - /// Returns the bidirectional character type for . - /// Unlisted code points default to . - /// - internal static BidiCharacterType GetType(uint codePoint) - { - int lo = 0, hi = s_ranges.Length - 1; - while (lo <= hi) - { - int mid = lo + (hi - lo) / 2; - var (start, end, type) = s_ranges[mid]; - if (codePoint < start) - hi = mid - 1; - else if (codePoint > end) - lo = mid + 1; - else - return type; - } - return BidiCharacterType.L; - } - - /// - /// Returns the bidirectional character type for a UTF-16 code unit. - /// Surrogate pairs are resolved to a full code point before lookup. - /// - internal static BidiCharacterType GetType(string text, int index) - { - char c = text[index]; - if (char.IsHighSurrogate(c) && index + 1 < text.Length && char.IsLowSurrogate(text[index + 1])) - { - uint cp = (uint)char.ConvertToUtf32(c, text[index + 1]); - return GetType(cp); - } - return GetType((uint)c); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterType.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterType.cs deleted file mode 100644 index a172dec7..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiCharacterType.cs +++ /dev/null @@ -1,77 +0,0 @@ -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Unicode bidirectional character types (UAX #9 §4.2). - /// - internal enum BidiCharacterType : byte - { - /// Left-to-Right (strong). - L = 0, - - /// Right-to-Left (strong). - R = 1, - - /// Right-to-Left Arabic (strong). - AL = 2, - - /// European Number (weak). - EN = 3, - - /// European Separator (weak). - ES = 4, - - /// European Terminator (weak). - ET = 5, - - /// Common Number Separator (weak). - AN = 6, - - /// Common Separator (weak). - CS = 7, - - /// Nonspacing Mark (weak). - NSM = 8, - - /// Boundary Neutral (weak). - BN = 9, - - /// Paragraph Separator (neutral). - B = 10, - - /// Segment Separator (neutral). - S = 11, - - /// Whitespace (neutral). - WS = 12, - - /// Other Neutral (neutral). - ON = 13, - - /// Left-to-Right Embedding (format, LRE). - LRE = 14, - - /// Right-to-Left Embedding (format, RLE). - RLE = 15, - - /// Left-to-Right Override (format, LRO). - LRO = 16, - - /// Right-to-Left Override (format, RLO). - RLO = 17, - - /// Pop Directional Format (format, PDF). - PDF = 18, - - /// Left-to-Right Isolate (format, LRI). - LRI = 19, - - /// Right-to-Left Isolate (format, RLI). - RLI = 20, - - /// First Strong Isolate (format, FSI). - FSI = 21, - - /// Pop Directional Isolate (format, PDI). - PDI = 22, - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiMirroring.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiMirroring.cs deleted file mode 100644 index dec38cc2..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiMirroring.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Bidi mirroring table (UAX #9 §3.1.4 / L4, from BidiMirroring.txt). - /// Characters that have a distinct mirrored glyph in RTL context. - /// - internal static class BidiMirroring - { - private static readonly Dictionary s_mirror = new Dictionary - { - { '(', ')' }, - { ')', '(' }, - { '[', ']' }, - { ']', '[' }, - { '{', '}' }, - { '}', '{' }, - { '<', '>' }, - { '>', '<' }, - { '\u00AB', '\u00BB' }, // « » - { '\u00BB', '\u00AB' }, - { '\u2039', '\u203A' }, // ‹ › - { '\u203A', '\u2039' }, - { '\u2045', '\u2046' }, // ⁅ ⁆ - { '\u2046', '\u2045' }, - { '\u207D', '\u207E' }, // ⁽ ⁾ - { '\u207E', '\u207D' }, - { '\u208D', '\u208E' }, // ₍ ₎ - { '\u208E', '\u208D' }, - { '\u2208', '\u220B' }, // ∈ ∋ - { '\u220B', '\u2208' }, - { '\u2209', '\u220C' }, // ∉ ∌ - { '\u220C', '\u2209' }, - { '\u220A', '\u220D' }, - { '\u220D', '\u220A' }, - { '\u2215', '\u29F5' }, // ∕ ⧵ - { '\u29F5', '\u2215' }, - { '\u223C', '\u223D' }, // ∼ ∽ - { '\u223D', '\u223C' }, - { '\u2243', '\u22CD' }, - { '\u22CD', '\u2243' }, - { '\u2252', '\u2253' }, - { '\u2253', '\u2252' }, - { '\u2254', '\u2255' }, - { '\u2255', '\u2254' }, - { '\u2266', '\u2267' }, // ≦ ≧ - { '\u2267', '\u2266' }, - { '\u2268', '\u2269' }, - { '\u2269', '\u2268' }, - { '\u226A', '\u226B' }, // ≪ ≫ - { '\u226B', '\u226A' }, - { '\u2272', '\u2273' }, - { '\u2273', '\u2272' }, - { '\u2276', '\u2277' }, - { '\u2277', '\u2276' }, - { '\u2278', '\u2279' }, - { '\u2279', '\u2278' }, - { '\u227A', '\u227B' }, // ≺ ≻ - { '\u227B', '\u227A' }, - { '\u2282', '\u2283' }, // ⊂ ⊃ - { '\u2283', '\u2282' }, - { '\u2286', '\u2287' }, // ⊆ ⊇ - { '\u2287', '\u2286' }, - { '\u2329', '\u232A' }, // 〈 〉 - { '\u232A', '\u2329' }, - { '\u2768', '\u2769' }, - { '\u2769', '\u2768' }, - { '\u276A', '\u276B' }, - { '\u276B', '\u276A' }, - { '\u276C', '\u276D' }, - { '\u276D', '\u276C' }, - { '\u276E', '\u276F' }, - { '\u276F', '\u276E' }, - { '\u2770', '\u2771' }, - { '\u2771', '\u2770' }, - { '\u2772', '\u2773' }, - { '\u2773', '\u2772' }, - { '\u2774', '\u2775' }, - { '\u2775', '\u2774' }, - { '\u27C5', '\u27C6' }, - { '\u27C6', '\u27C5' }, - { '\u27E6', '\u27E7' }, - { '\u27E7', '\u27E6' }, - { '\u27E8', '\u27E9' }, // ⟨ ⟩ - { '\u27E9', '\u27E8' }, - { '\u27EA', '\u27EB' }, - { '\u27EB', '\u27EA' }, - { '\u27EC', '\u27ED' }, - { '\u27ED', '\u27EC' }, - { '\u27EE', '\u27EF' }, - { '\u27EF', '\u27EE' }, - { '\u2308', '\u2309' }, // ⌈ ⌉ - { '\u2309', '\u2308' }, - { '\u230A', '\u230B' }, // ⌊ ⌋ - { '\u230B', '\u230A' }, - { '\u2983', '\u2984' }, - { '\u2984', '\u2983' }, - { '\u2985', '\u2986' }, - { '\u2986', '\u2985' }, - { '\u2987', '\u2988' }, - { '\u2988', '\u2987' }, - { '\u2989', '\u298A' }, - { '\u298A', '\u2989' }, - { '\u298B', '\u298C' }, - { '\u298C', '\u298B' }, - { '\u298D', '\u2990' }, - { '\u298E', '\u298F' }, - { '\u298F', '\u298E' }, - { '\u2990', '\u298D' }, - { '\u2991', '\u2992' }, - { '\u2992', '\u2991' }, - { '\u2993', '\u2994' }, - { '\u2994', '\u2993' }, - { '\u2995', '\u2996' }, - { '\u2996', '\u2995' }, - { '\u2997', '\u2998' }, - { '\u2998', '\u2997' }, - { '\u29D8', '\u29D9' }, - { '\u29D9', '\u29D8' }, - { '\u29DA', '\u29DB' }, - { '\u29DB', '\u29DA' }, - { '\u29FC', '\u29FD' }, - { '\u29FD', '\u29FC' }, - { '\u3008', '\u3009' }, // 〈 〉 - { '\u3009', '\u3008' }, - { '\u300A', '\u300B' }, // 《 》 - { '\u300B', '\u300A' }, - { '\u300C', '\u300D' }, // 「 」 - { '\u300D', '\u300C' }, - { '\u300E', '\u300F' }, // 『 』 - { '\u300F', '\u300E' }, - { '\u3010', '\u3011' }, // 【 】 - { '\u3011', '\u3010' }, - { '\u3014', '\u3015' }, // 〔 〕 - { '\u3015', '\u3014' }, - { '\u3016', '\u3017' }, // 〖 〗 - { '\u3017', '\u3016' }, - { '\u3018', '\u3019' }, // 〘 〙 - { '\u3019', '\u3018' }, - { '\u301A', '\u301B' }, // 〚 〛 - { '\u301B', '\u301A' }, - { '\uFF08', '\uFF09' }, // Fullwidth ( ) - { '\uFF09', '\uFF08' }, - { '\uFF3B', '\uFF3D' }, // Fullwidth [ ] - { '\uFF3D', '\uFF3B' }, - { '\uFF5B', '\uFF5D' }, // Fullwidth { } - { '\uFF5D', '\uFF5B' }, - }; - - /// - /// If has a mirrored glyph, returns the mirrored - /// character via and returns true. - /// Otherwise returns false. - /// - internal static bool TryGetMirror(char c, out char mirrored) - { - return s_mirror.TryGetValue(c, out mirrored); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Bidi/BidiParagraphDirection.cs b/src/MiniPdf/Drawing/Text/Bidi/BidiParagraphDirection.cs deleted file mode 100644 index 68f39e4f..00000000 --- a/src/MiniPdf/Drawing/Text/Bidi/BidiParagraphDirection.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace MiniSoftware.Drawing.Text.Bidi -{ - /// - /// Paragraph embedding direction for the Unicode Bidirectional Algorithm. - /// - internal enum BidiParagraphDirection - { - /// Left-to-right paragraph (base level 0). - LTR, - - /// Right-to-left paragraph (base level 1). - RTL, - - /// Auto-detect from first strong character (UAX #9 P1). - Auto - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/CharacterRange.cs b/src/MiniPdf/Drawing/Text/CharacterRange.cs deleted file mode 100644 index 5ec39d25..00000000 --- a/src/MiniPdf/Drawing/Text/CharacterRange.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies a range of character positions within a string. - /// - public struct CharacterRange - { - /// - /// Initializes a new with the specified first character and length. - /// - /// The zero-based position of the first character. - /// The number of characters in the range. - public CharacterRange(int first, int length) - { - First = first; - Length = length; - } - - /// - /// Gets or sets the zero-based position of the first character in the range. - /// - public int First { get; set; } - - /// - /// Gets or sets the number of characters in the range. - /// - public int Length { get; set; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Font.cs b/src/MiniPdf/Drawing/Text/Font.cs deleted file mode 100644 index e7d6cf9b..00000000 --- a/src/MiniPdf/Drawing/Text/Font.cs +++ /dev/null @@ -1,255 +0,0 @@ -using MiniSoftware.Drawing.Enums; -using System; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Defines a text font used for drawing text with . - /// - /// - /// A is created from a and size, - /// and can be styled with flags. Fonts are used with - /// to render text. - /// - public sealed class Font : IDisposable - { - /// - /// Initializes a new with the specified family name and size. - /// - /// The name of the font family. - /// The em size of the font in the specified units. - public Font(string familyName, float emSize) - : this(new FontFamily(familyName), emSize, FontStyle.Regular, GraphicsUnit.Point, 0, false, familyName) - { - } - - /// - /// Initializes a new with the specified family name, size, and style. - /// - /// The name of the font family. - /// The em size of the font in the specified units. - /// The style of the font. - public Font(string familyName, float emSize, FontStyle style) - : this(new FontFamily(familyName), emSize, style, GraphicsUnit.Point, 0, false, familyName) - { - } - - /// - /// Initializes a new with the specified family name, size, style, and unit. - /// - /// The name of the font family. - /// The em size of the font. - /// The style of the font. - /// The unit of measurement for the font size. - public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit) - : this(new FontFamily(familyName), emSize, style, unit, 0, false, familyName) - { - } - - /// - /// Initializes a new with the specified font family and size. - /// - /// The font family. - /// The em size of the font. - public Font(FontFamily family, float emSize) - : this(family, emSize, FontStyle.Regular, GraphicsUnit.Point, 0, false, GetFamilyName(family)) - { - } - - /// - /// Initializes a new with the specified font family, size, and style. - /// - /// The font family. - /// The em size of the font. - /// The style of the font. - public Font(FontFamily family, float emSize, FontStyle style) - : this(family, emSize, style, GraphicsUnit.Point, 0, false, GetFamilyName(family)) - { - } - - /// - /// Initializes a new with the specified font family, size, style, and unit. - /// - /// The font family. - /// The em size of the font. - /// The style of the font. - /// The unit of measurement for the font size. - public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit) - : this(family, emSize, style, unit, 0, false, GetFamilyName(family)) - { - } - - /// - /// Initializes a new with the specified font family, size, style, unit, and GDI character set. - /// - /// The font family. - /// The em size of the font. - /// The style of the font. - /// The unit of measurement for the font size. - /// The GDI character set. - public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) - : this(family, emSize, style, unit, gdiCharSet, false, GetFamilyName(family)) - { - } - - private Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont, string? originalFontName) - { - FontFamily = family ?? throw new ArgumentNullException(nameof(family)); - if (emSize <= 0f) - throw new ArgumentOutOfRangeException(nameof(emSize), "Font size must be positive."); - - Size = emSize; - Style = style; - Unit = unit; - GdiCharSet = gdiCharSet; - GdiVerticalFont = gdiVerticalFont; - OriginalFontName = string.IsNullOrWhiteSpace(originalFontName) - ? FontFamily.Name - : originalFontName!; - } - - /// - /// Gets the font family used by this font. - /// - public FontFamily FontFamily { get; } - - /// - /// Gets the name of this font. - /// - public string Name => FontFamily.Name; - - /// - /// Gets the size of this font in the specified units. - /// - public float Size { get; } - - /// - /// Gets the unit of measurement for the font size. - /// - public GraphicsUnit Unit { get; } - - /// - /// Gets the style of this font. - /// - public FontStyle Style { get; } - - /// - /// Gets a value indicating whether this font is bold. - /// - public bool Bold => (Style & FontStyle.Bold) != 0; - - /// - /// Gets a value indicating whether this font is italic. - /// - public bool Italic => (Style & FontStyle.Italic) != 0; - - /// - /// Gets a value indicating whether this font has underlined text. - /// - public bool Underline => (Style & FontStyle.Underline) != 0; - - /// - /// Gets a value indicating whether this font has strikethrough text. - /// - public bool Strikeout => (Style & FontStyle.Strikeout) != 0; - - /// - /// Gets the line spacing height of this font in pixels. - /// - public int Height - { - get - { - int emHeight = Math.Max(1, FontFamily.GetEmHeight(Style)); - float emInPixels = ToPixels(Size, Unit, 96f); - float emScale = emInPixels / emHeight; - return (int)Math.Ceiling((FontFamily.GetCellAscent(Style) + FontFamily.GetCellDescent(Style)) * emScale); - } - } - - /// - /// Gets the size of this font in points. - /// - public float SizeInPoints => ToPoints(Size, Unit, 96f); - - /// - /// Gets the GDI character set. - /// - public byte GdiCharSet { get; } - - /// - /// Gets a value indicating whether this font uses vertical GDI font metrics. - /// - public bool GdiVerticalFont { get; } - - /// - /// Gets the original font name passed to the constructor. - /// - public string OriginalFontName { get; } - - /// - /// Creates an exact copy of this font. - /// - /// A new with the same family, size, style, and unit. - public Font Clone() - => new Font(FontFamily, Size, Style, Unit, GdiCharSet, GdiVerticalFont, OriginalFontName); - - /// - /// Releases all resources used by this font. - /// - public void Dispose() - { - } - - /// - /// Converts a value from the specified unit to pixels. - /// - private static float ToPixels(float value, GraphicsUnit unit, float dpi) - { - switch (unit) - { - case GraphicsUnit.Pixel: - return value; - case GraphicsUnit.Point: - return value * dpi / 72f; - case GraphicsUnit.Inch: - return value * dpi; - case GraphicsUnit.Document: - return value * dpi / 300f; - case GraphicsUnit.Millimeter: - return value * dpi / 25.4f; - default: - return value; - } - } - - /// - /// Converts a value from the specified unit to points. - /// - private static float ToPoints(float value, GraphicsUnit unit, float dpi) - { - switch (unit) - { - case GraphicsUnit.Pixel: - return value * 72f / dpi; - case GraphicsUnit.Point: - return value; - case GraphicsUnit.Inch: - return value * 72f; - case GraphicsUnit.Document: - return value * 72f / 300f; - case GraphicsUnit.Millimeter: - return value * 72f / 25.4f; - default: - return value; - } - } - - private static string GetFamilyName(FontFamily family) - { - if (family == null) - throw new ArgumentNullException(nameof(family)); - return family.Name; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/FontCollection.cs b/src/MiniPdf/Drawing/Text/FontCollection.cs deleted file mode 100644 index 28bb6b8d..00000000 --- a/src/MiniPdf/Drawing/Text/FontCollection.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Sources; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Represents a collection of objects. - /// - public abstract class FontCollection : IDisposable - { - private readonly Dictionary _familiesByName = new Dictionary(StringComparer.OrdinalIgnoreCase); - - /// - /// Gets the array of font families in this collection. - /// - public FontFamily[] Families - { - get - { - var result = new FontFamily[_familiesByName.Count]; - _familiesByName.Values.CopyTo(result, 0); - return result; - } - } - - /// - /// Adds or merges a font family into this collection. - /// - /// The font family to add or merge. - protected void AddOrMergeFamily(FontFamily family) - { - if (family == null) - throw new ArgumentNullException(nameof(family)); - - if (_familiesByName.TryGetValue(family.Name, out var existing)) - { - existing.MergeFrom(family.CloneData()); - return; - } - - _familiesByName[family.Name] = new FontFamily(family.CloneData()); - } - - /// - /// Tries to find a font family by name in this collection. - /// - /// The case-insensitive family name to look up. - /// - /// The matching cloned from the collection, or - /// null when no family with that name is present. - /// - public FontFamily? FindFamily(string name) - { - if (string.IsNullOrEmpty(name)) - return null; - - if (_familiesByName.TryGetValue(name, out var existing)) - return new FontFamily(existing.CloneData()); - - return null; - } - - /// - /// Loads every face from a font collection file (single font or TTC) and merges - /// the resulting families into this collection. - /// - /// The stream source pointing at the font file. - protected void AddFacesFromSource(IStreamSource source) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - var collection = MiniSoftware.Drawing.Font.FontFactory.OpenCollection(source); - AddFaces(collection); - } - - /// - /// Merges every face in a loaded font collection into this - /// as entries. - /// - /// The loaded font faces. - protected void AddFaces(MiniSoftware.Drawing.Font.Core.FontFaceCollection collection) - { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - - foreach (var face in collection) - { - var data = new FontFamilyData(face.FontFamily); - var drawingStyle = MapStyle(face.Style); - data.AddStyle(drawingStyle, FontMetricsData.FromMetrics(face.Metrics)); - data.AddFontFace(drawingStyle, face); - AddOrMergeFamily(new FontFamily(data)); - } - } - - /// - /// Maps the integrated font engine - /// to the GDI+-compatible flags. - /// - private static Enums.FontStyle MapStyle(MiniSoftware.Drawing.Font.Core.FontFaceStyle style) - { - switch (style) - { - case MiniSoftware.Drawing.Font.Core.FontFaceStyle.Bold: - return Enums.FontStyle.Bold; - case MiniSoftware.Drawing.Font.Core.FontFaceStyle.Italic: - return Enums.FontStyle.Italic; - case MiniSoftware.Drawing.Font.Core.FontFaceStyle.BoldItalic: - return Enums.FontStyle.Bold | Enums.FontStyle.Italic; - default: - return Enums.FontStyle.Regular; - } - } - - /// - /// Releases resources used by the . - /// - public virtual void Dispose() - { - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/FontFallbackChain.cs b/src/MiniPdf/Drawing/Text/FontFallbackChain.cs deleted file mode 100644 index ba3fb1cd..00000000 --- a/src/MiniPdf/Drawing/Text/FontFallbackChain.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// An ordered list of font families queried to find a glyph for a code - /// point that the primary font lacks. Used for automatic font fallback - /// during text layout. - /// - public sealed class FontFallbackChain - { - private readonly List _families = new List(); - - /// Initializes an empty fallback chain. - public FontFallbackChain() { } - - /// Initializes a chain containing the specified families. - public FontFallbackChain(params FontFamily[] families) - { - if (families == null) throw new ArgumentNullException(nameof(families)); - foreach (var f in families) _families.Add(f); - } - - /// The ordered list of fallback font families. - public IReadOnlyList Families => _families; - - /// Adds a fallback family to the end of the chain. - public FontFallbackChain Add(FontFamily family) - { - if (family == null) throw new ArgumentNullException(nameof(family)); - _families.Add(family); - return this; - } - - /// - /// Returns the family from the chain that provides a glyph for - /// , or null if none do. - /// - public FontFamily? Resolve(uint codePoint, FontStyle style) - { - foreach (var family in _families) - { - var face = family.GetFontFace(style); - if (face != null && face.Encoding.HasGlyph(codePoint)) - return family; - } - return null; - } - - /// - /// Creates the default fallback chain for the current operating system, - /// using installed fonts. Returns an empty chain when no fallback - /// families are installed. - /// - public static FontFallbackChain CreateDefault() - { - var chain = new FontFallbackChain(); - - string[] candidateNames; - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - candidateNames = new[] - { - "Segoe UI", "Segoe UI Symbol", "Segoe UI Emoji", - "Segoe UI Historic", "Tahoma", "Arial Unicode MS", - "Arial", "Times New Roman" - }; - } - else if (Environment.OSVersion.Platform == PlatformID.Unix) - { - candidateNames = new[] - { - "DejaVu Sans", "Noto Sans", "Noto Sans Symbols", - "Noto Color Emoji", "Liberation Sans" - }; - } - else if (Environment.OSVersion.Platform == PlatformID.MacOSX) - { - candidateNames = new[] - { - "Helvetica Neue", "Apple Color Emoji", - "Apple Symbols", "Geneva" - }; - } - else - { - return chain; - } - - var installed = InstalledFontCollection.Default; - foreach (var name in candidateNames) - { - foreach (var fam in installed.Families) - { - if (string.Equals(fam.Name, name, StringComparison.OrdinalIgnoreCase)) - { - chain._families.Add(fam); - break; - } - } - } - - return chain; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/FontFallbackResolver.cs b/src/MiniPdf/Drawing/Text/FontFallbackResolver.cs deleted file mode 100644 index c05fe3cd..00000000 --- a/src/MiniPdf/Drawing/Text/FontFallbackResolver.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; -using FontStyle = MiniSoftware.Drawing.Enums.FontStyle; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Caches per-(FontFamily, FontStyle) IFont lookups and per-code-point - /// coverage to avoid re-querying the cmap for every character on every line. - /// Constructed per DrawString/MeasureString call and discarded. - /// - internal sealed class FontFallbackResolver - { - private readonly FontFamily _primaryFamily; - private readonly FontStyle _primaryStyle; - private readonly FontFallbackChain? _chain; - private readonly bool _fallbackEnabled; - - private readonly Dictionary<(FontFamily, FontStyle), IFont?> _fontFaceCache - = new Dictionary<(FontFamily, FontStyle), IFont?>(); - private readonly Dictionary<(FontFamily, uint), bool> _coverageCache - = new Dictionary<(FontFamily, uint), bool>(); - - internal FontFallbackResolver( - FontFamily primaryFamily, - FontStyle primaryStyle, - FontFallbackChain? chain, - bool fallbackEnabled) - { - _primaryFamily = primaryFamily; - _primaryStyle = primaryStyle; - _chain = chain; - _fallbackEnabled = fallbackEnabled; - } - - /// - /// Returns the (primary or fallback) that provides a - /// glyph for . When fallback is disabled or - /// no fallback font has the glyph, returns the primary IFont (or null - /// if the primary has no face for the style). - /// - internal IFont? Resolve(uint codePoint) - { - if (HasGlyph(_primaryFamily, _primaryStyle, codePoint)) - return GetFontFace(_primaryFamily, _primaryStyle); - - if (!_fallbackEnabled || _chain == null) - return GetFontFace(_primaryFamily, _primaryStyle); - - var fallbackFamily = _chain.Resolve(codePoint, _primaryStyle); - if (fallbackFamily != null) - return GetFontFace(fallbackFamily, _primaryStyle); - - return GetFontFace(_primaryFamily, _primaryStyle); - } - - /// - /// Returns the that would - /// use for . Used by RunSegmenter to detect - /// font-change boundaries without allocating an IFont. - /// - internal FontFamily ResolveFamily(uint codePoint) - { - if (HasGlyph(_primaryFamily, _primaryStyle, codePoint)) - return _primaryFamily; - - if (!_fallbackEnabled || _chain == null) - return _primaryFamily; - - var fallbackFamily = _chain.Resolve(codePoint, _primaryStyle); - return fallbackFamily ?? _primaryFamily; - } - - private IFont? GetFontFace(FontFamily family, FontStyle style) - { - var key = (family, style); - if (!_fontFaceCache.TryGetValue(key, out var face)) - { - face = family.GetFontFace(style); - _fontFaceCache[key] = face; - } - return face; - } - - private bool HasGlyph(FontFamily family, FontStyle style, uint codePoint) - { - var key = (family, codePoint); - if (_coverageCache.TryGetValue(key, out var has)) - return has; - - var face = GetFontFace(family, style); - has = face != null && face.Encoding.HasGlyph(codePoint); - _coverageCache[key] = has; - return has; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/FontFamily.cs b/src/MiniPdf/Drawing/Text/FontFamily.cs deleted file mode 100644 index 9b55ccef..00000000 --- a/src/MiniPdf/Drawing/Text/FontFamily.cs +++ /dev/null @@ -1,333 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Represents a font family used for drawing text. - /// - /// - /// A defines a set of fonts that share the same family name - /// but differ in style (bold, italic, etc.). Use , - /// , or for generic families. - /// - public sealed class FontFamily : IDisposable - { - private readonly FontFamilyData _data; - - /// - /// Initializes a new with the specified font family name. - /// - /// The name of the font family. - /// - /// The name is first looked up in the process-wide - /// . When a matching installed family is - /// found it is used (with real metrics and glyph outlines). When no installed - /// family matches, a fallback with guessed metrics is created so that the - /// instance is still usable for measurement. - /// - public FontFamily(string name) - : this(ResolveFamilyData(name)) - { - } - - /// - /// Resolves a family name to by consulting the - /// installed system font collection first and falling back to guessed metrics. - /// - private static FontFamilyData ResolveFamilyData(string name) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Font family name must not be empty.", nameof(name)); - - FontFamily? installed = InstalledFontCollection.Default.FindFamily(name); - if (installed != null) - return installed.CloneData(); - - return FontFamilyData.CreateFallback(name); - } - - /// - /// Initializes a new with the specified generic font family. - /// - /// The generic font family. - public FontFamily(GenericFontFamilies genericFamily) - : this(FontFamilyData.CreateGeneric(genericFamily)) - { - } - - internal FontFamily(FontFamilyData data) - { - _data = data ?? throw new ArgumentNullException(nameof(data)); - } - - /// - /// Gets a representing the serif font family. - /// - public static FontFamily GenericSerif => new FontFamily(GenericFontFamilies.Serif); - - /// - /// Gets a representing the sans-serif font family. - /// - public static FontFamily GenericSansSerif => new FontFamily(GenericFontFamilies.SansSerif); - - /// - /// Gets a representing the monospace font family. - /// - public static FontFamily GenericMonospace => new FontFamily(GenericFontFamilies.Monospace); - - /// - /// Gets the name of this font family. - /// - public string Name => _data.Name; - - /// - /// Gets the em height of the font in design units. - /// - /// The font style. - /// The em height in design units. - public int GetEmHeight(Enums.FontStyle style) => RoundMetric(_data.GetMetrics(style).UnitsPerEm, 2048); - - /// - /// Gets the cell ascent of the font in design units. - /// - /// The font style. - /// The cell ascent in design units. - public int GetCellAscent(Enums.FontStyle style) => RoundMetric(_data.GetMetrics(style).Ascender, 1854); - - /// - /// Gets the cell descent of the font in design units. - /// - /// The font style. - /// The cell descent in design units. - public int GetCellDescent(Enums.FontStyle style) - { - var metrics = _data.GetMetrics(style); - double descent = metrics.Descender <= 0 ? -metrics.Descender : metrics.Descender; - return RoundMetric(descent, 434); - } - - /// - /// Gets the line spacing of the font in design units. - /// - /// The font style. - /// The line spacing in design units. - public int GetLineSpacing(Enums.FontStyle style) - { - var metrics = _data.GetMetrics(style); - double descent = metrics.Descender <= 0 ? -metrics.Descender : metrics.Descender; - return RoundMetric(metrics.Ascender + descent + metrics.LineGap, 2048); - } - - /// - /// Gets a value indicating whether the specified font style is available. - /// - /// The font style to check. - /// true if the style is available; otherwise, false. - public bool IsStyleAvailable(Enums.FontStyle style) => _data.IsStyleAvailable(style); - - /// - /// Releases all resources used by this font family. - /// - public void Dispose() - { - } - - internal FontMetricsData GetMetricsData(Enums.FontStyle style) => _data.GetMetrics(style); - - internal FontFamilyData CloneData() => _data.Clone(); - - internal void MergeFrom(FontFamilyData other) => _data.MergeFrom(other); - - internal IFont? GetFontFace(Enums.FontStyle style) => _data.GetFontFace(style); - - private static int RoundMetric(double value, int fallback) - { - if (value <= 0) - return fallback; - return (int)Math.Ceiling(value); - } - } - - internal sealed class FontFamilyData - { - private readonly Dictionary _metricsByStyle; - private readonly Dictionary _fontsByStyle = new Dictionary(); - - public FontFamilyData(string name) - { - if (string.IsNullOrWhiteSpace(name)) - throw new ArgumentException("Font family name must not be empty.", nameof(name)); - - Name = name; - _metricsByStyle = new Dictionary(); - } - - public string Name { get; } - - public static FontFamilyData CreateGeneric(GenericFontFamilies genericFamily) - { - string name; - FontMetricsData metrics; - - switch (genericFamily) - { - case GenericFontFamilies.Serif: - name = "Serif"; - metrics = FontMetricsData.GenericSerif; - break; - case GenericFontFamilies.Monospace: - name = "Monospace"; - metrics = FontMetricsData.GenericMonospace; - break; - default: - name = "Sans Serif"; - metrics = FontMetricsData.GenericSansSerif; - break; - } - - var data = new FontFamilyData(name); - data.AddDefaultStyles(metrics); - return data; - } - - public static FontFamilyData CreateFallback(string name) - { - var metrics = GuessGenericMetrics(name); - var data = new FontFamilyData(name); - data.AddDefaultStyles(metrics); - return data; - } - - public FontFamilyData Clone() - { - var clone = new FontFamilyData(Name); - foreach (var pair in _metricsByStyle) - clone._metricsByStyle[pair.Key] = pair.Value; - foreach (var pair in _fontsByStyle) - clone._fontsByStyle[pair.Key] = pair.Value; - return clone; - } - - public void MergeFrom(FontFamilyData other) - { - if (other == null) - throw new ArgumentNullException(nameof(other)); - - foreach (var pair in other._metricsByStyle) - _metricsByStyle[pair.Key] = pair.Value; - foreach (var pair in other._fontsByStyle) - _fontsByStyle[pair.Key] = pair.Value; - } - - public bool IsStyleAvailable(Enums.FontStyle style) => _metricsByStyle.ContainsKey(NormalizeStyle(style)); - - public void AddStyle(Enums.FontStyle style, FontMetricsData metrics) => _metricsByStyle[NormalizeStyle(style)] = metrics; - - public void AddFontFace(Enums.FontStyle style, IFont font) => _fontsByStyle[NormalizeStyle(style)] = font; - - public IFont? GetFontFace(Enums.FontStyle style) - { - if (_fontsByStyle.TryGetValue(NormalizeStyle(style), out var face)) - return face; - if (_fontsByStyle.TryGetValue(Enums.FontStyle.Regular, out face)) - return face; - foreach (var pair in _fontsByStyle) - return pair.Value; - return null; - } - - public FontMetricsData GetMetrics(Enums.FontStyle style) - { - if (_metricsByStyle.TryGetValue(NormalizeStyle(style), out var metrics)) - return metrics; - - if (_metricsByStyle.TryGetValue(Enums.FontStyle.Regular, out metrics)) - return metrics; - - foreach (var pair in _metricsByStyle) - return pair.Value; - - return GuessGenericMetrics(Name); - } - - private void AddDefaultStyles(FontMetricsData metrics) - { - _metricsByStyle[Enums.FontStyle.Regular] = metrics; - _metricsByStyle[Enums.FontStyle.Bold] = metrics; - _metricsByStyle[Enums.FontStyle.Italic] = metrics; - _metricsByStyle[Enums.FontStyle.Bold | Enums.FontStyle.Italic] = metrics; - } - - private static FontMetricsData GuessGenericMetrics(string name) - { - if (string.IsNullOrWhiteSpace(name)) - return FontMetricsData.GenericSansSerif; - - string normalized = name.Trim(); - if (normalized.IndexOf("mono", StringComparison.OrdinalIgnoreCase) >= 0 - || normalized.IndexOf("courier", StringComparison.OrdinalIgnoreCase) >= 0 - || normalized.IndexOf("console", StringComparison.OrdinalIgnoreCase) >= 0) - return FontMetricsData.GenericMonospace; - - if (normalized.IndexOf("serif", StringComparison.OrdinalIgnoreCase) >= 0 - && normalized.IndexOf("sans", StringComparison.OrdinalIgnoreCase) < 0) - return FontMetricsData.GenericSerif; - - return FontMetricsData.GenericSansSerif; - } - - private static Enums.FontStyle NormalizeStyle(Enums.FontStyle style) - { - Enums.FontStyle normalized = style & (Enums.FontStyle.Bold | Enums.FontStyle.Italic); - return normalized == 0 ? Enums.FontStyle.Regular : normalized; - } - } - - internal readonly struct FontMetricsData - { - public static readonly FontMetricsData GenericSansSerif = new FontMetricsData(2048, 1854, -434, 67, -100, 50, 512, 50); - public static readonly FontMetricsData GenericSerif = new FontMetricsData(2048, 1825, -443, 90, -100, 50, 512, 50); - public static readonly FontMetricsData GenericMonospace = new FontMetricsData(2048, 1705, -443, 0, -100, 50, 512, 50); - - public FontMetricsData(double unitsPerEm, double ascender, double descender, double lineGap, - double underlinePosition, double underlineThickness, double strikeoutPosition, double strikeoutSize) - { - UnitsPerEm = unitsPerEm; - Ascender = ascender; - Descender = descender; - LineGap = lineGap; - UnderlinePosition = underlinePosition; - UnderlineThickness = underlineThickness; - StrikeoutPosition = strikeoutPosition; - StrikeoutSize = strikeoutSize; - } - - public double UnitsPerEm { get; } - public double Ascender { get; } - public double Descender { get; } - public double LineGap { get; } - public double UnderlinePosition { get; } - public double UnderlineThickness { get; } - public double StrikeoutPosition { get; } - public double StrikeoutSize { get; } - - public static FontMetricsData FromMetrics(IFontMetrics metrics) - { - if (metrics == null) - throw new ArgumentNullException(nameof(metrics)); - - return new FontMetricsData( - metrics.UnitsPerEM, - metrics.Ascender, - metrics.Descender, - metrics.LineGap, - metrics.UnderlinePosition, - metrics.UnderlineThickness, - metrics.StrikeoutPosition, - metrics.StrikeoutSize); - } - } -} diff --git a/src/MiniPdf/Drawing/Text/FontSettings.cs b/src/MiniPdf/Drawing/Text/FontSettings.cs deleted file mode 100644 index 04716e44..00000000 --- a/src/MiniPdf/Drawing/Text/FontSettings.cs +++ /dev/null @@ -1,80 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Controls global font-loading behaviour for the drawing library. All properties - /// must be set before the first access to - /// because the system font collection is scanned once and cached for the lifetime of - /// the process. - /// - public static class FontSettings - { - private static bool _autoLoadSystemFonts = true; - private static bool _useNativeFontApis = true; - - /// - /// Gets or sets a value indicating whether - /// automatically loads system fonts on first access. The default is true. - /// - /// - /// - /// When true (the default), - /// scans the platform font directories (and optionally native OS APIs) and loads - /// every discovered font. This is the expected behaviour for desktop and console - /// applications. - /// - /// - /// When false, contains only - /// the three generic fallback families (Sans Serif, Serif, - /// Monospace) with guessed metrics. Applications must load fonts manually - /// via . This is recommended for web and server - /// scenarios where: - /// - /// - /// Startup latency from scanning hundreds of system fonts is undesirable. - /// The server/container has no system fonts installed. - /// The application ships its own embedded fonts and wants deterministic behaviour. - /// File-system access to font directories is restricted by sandboxing. - /// - /// - /// This property must be set before the first access to - /// . Changes after the collection has - /// been created have no effect. - /// - /// - public static bool AutoLoadSystemFonts - { - get => _autoLoadSystemFonts; - set => _autoLoadSystemFonts = value; - } - - /// - /// Gets or sets a value indicating whether native operating-system APIs are used - /// for font discovery before falling back to directory scanning. The default is - /// true. - /// - /// - /// - /// When true (the default), the library queries the platform's native font - /// service first: - /// - /// - /// Windows: reads the font registry keys (HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts and the per-user equivalent) to resolve family names to file paths, including fonts installed outside the standard %SYSTEMROOT%\Fonts directory. - /// macOS: queries CoreText (CTFontManagerCopyAvailableFontFamilyNames) for the authoritative family list and file paths. - /// Linux: queries fontconfig (FcConfigGetFonts) for the authoritative family list and file paths, respecting fontconfig aliases and non-standard install locations. - /// - /// - /// When false, only directory scanning of the standard font directories is - /// used. This avoids any P/Invoke to native libraries and is useful in restricted - /// environments where native library loading is prohibited. - /// - /// - /// This property has no effect when is false. - /// - /// - public static bool UseNativeFontApis - { - get => _useNativeFontApis; - set => _useNativeFontApis = value; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/GenericFontFamilies.cs b/src/MiniPdf/Drawing/Text/GenericFontFamilies.cs deleted file mode 100644 index ad369f26..00000000 --- a/src/MiniPdf/Drawing/Text/GenericFontFamilies.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the generic font families. - /// - public enum GenericFontFamilies - { - /// - /// Serif font family (e.g., Times New Roman). - /// - Serif = 0, - - /// - /// Sans-serif font family (e.g., Arial). - /// - SansSerif = 1, - - /// - /// Monospace font family (e.g., Courier New). - /// - Monospace = 2 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/GlyphRasterizer.cs b/src/MiniPdf/Drawing/Text/GlyphRasterizer.cs deleted file mode 100644 index 18aae1e4..00000000 --- a/src/MiniPdf/Drawing/Text/GlyphRasterizer.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Collections.Generic; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Font.Rendering; -using MiniSoftware.Drawing.Font.Glyphs; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Implements to convert a glyph's vector outline - /// into a positioned at a given screen coordinate. - /// - /// Font design space: X increases rightward, Y increases upward. - /// Screen space: X increases rightward, Y increases downward. - /// The Y axis is therefore flipped: screenY = baselineY − fontY × emScale. - /// - /// - internal sealed class GlyphRasterizer : IGlyphOutlinePainter - { - private readonly List _pts = new List(); - private readonly List _types = new List(); - private float _scale; - private float _dx; - private float _dy; - - // ── Coordinate transforms ────────────────────────────────────────────── - - private float Sx(double fx) => _dx + (float)fx * _scale; - private float Sy(double fy) => _dy - (float)fy * _scale; - - // ── Public API ───────────────────────────────────────────────────────── - - /// - /// Decompose one glyph and return its outline as a . - /// - /// The wrapping the font. - /// Glyph identifier to render. - /// Ratio emSizePixels / unitsPerEm. - /// Left edge of the glyph origin on screen, in pixels. - /// Y of the text baseline on screen, in pixels. - public GraphicsPath RenderGlyph( - GlyphOutlineRenderer renderer, - GlyphId gid, - float emScale, - float glyphX, - float baselineY) - { - _pts.Clear(); - _types.Clear(); - _scale = emScale; - _dx = glyphX; - _dy = baselineY; - - renderer.RenderGlyph(gid, this); - - if (_pts.Count == 0) - return new GraphicsPath(); - - return new GraphicsPath(_pts.ToArray(), _types.ToArray()); - } - - // ── IGlyphOutlinePainter ─────────────────────────────────────────────── - - public void MoveTo(MoveTo cmd) - { - _pts.Add(new PointF(Sx(cmd.X), Sy(cmd.Y))); - _types.Add((byte)PathPointType.Start); - } - - public void LineTo(LineTo cmd) - { - if (_types.Count == 0) - { - // Well-formed glyph data always starts with MoveTo; guard anyway. - _pts.Add(new PointF(_dx, _dy)); - _types.Add((byte)PathPointType.Start); - } - _pts.Add(new PointF(Sx(cmd.X), Sy(cmd.Y))); - _types.Add((byte)PathPointType.Line); - } - - public void CurveTo(CurveTo cmd) - { - if (_types.Count == 0) - { - _pts.Add(new PointF(_dx, _dy)); - _types.Add((byte)PathPointType.Start); - } - _pts.Add(new PointF(Sx(cmd.X1), Sy(cmd.Y1))); _types.Add((byte)PathPointType.Bezier); - _pts.Add(new PointF(Sx(cmd.X2), Sy(cmd.Y2))); _types.Add((byte)PathPointType.Bezier); - _pts.Add(new PointF(Sx(cmd.X3), Sy(cmd.Y3))); _types.Add((byte)PathPointType.Bezier); - } - - public void ClosePath() - { - if (_types.Count > 0) - _types[_types.Count - 1] |= (byte)PathPointType.CloseSubpath; - } - } -} diff --git a/src/MiniPdf/Drawing/Text/HotkeyPrefix.cs b/src/MiniPdf/Drawing/Text/HotkeyPrefix.cs deleted file mode 100644 index 57c99b6f..00000000 --- a/src/MiniPdf/Drawing/Text/HotkeyPrefix.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the type of display for hotkey prefixes in text. - /// - public enum HotkeyPrefix - { - /// - /// No hotkey prefix display. - /// - None = 0, - - /// - /// Show hotkey prefixes. - /// - Show = 1, - - /// - /// Hide hotkey prefixes. - /// - Hide = 2 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/InstalledFontCollection.cs b/src/MiniPdf/Drawing/Text/InstalledFontCollection.cs deleted file mode 100644 index f2212ee2..00000000 --- a/src/MiniPdf/Drawing/Text/InstalledFontCollection.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Font.Sources; -using MiniSoftware.Drawing.Text.Native; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Represents the collection of fonts installed on the system. The collection is - /// populated on first use by querying the platform's native font service (Windows - /// registry, macOS CoreText, Linux fontconfig) and falling back to directory - /// scanning. The result is cached for the lifetime of the process. - /// - /// - /// The auto-loading behaviour can be controlled via . Set - /// to false before first access - /// to to disable system font scanning entirely (useful in web - /// and server scenarios). Set to - /// false to skip native API calls and use directory scanning only. - /// - public sealed class InstalledFontCollection : FontCollection - { - /// - /// The process-wide cached instance, created once on first access. The scan is - /// thread-safe and re-entrant. - /// - private static readonly Lazy LazyDefault = - new Lazy(CreateDefaultInstance, true); - - /// - /// Gets the process-wide default . The - /// system fonts are discovered once on first access and the result is cached for - /// subsequent calls. - /// - /// - /// The behaviour of this property is controlled by . - /// Changes to after first access have no effect. - /// - public static InstalledFontCollection Default => LazyDefault.Value; - - /// - /// The default font family name as reported by the operating system, or - /// null when the OS did not provide one. - /// - public string? DefaultFamilyName { get; private set; } - - /// - /// Initializes a new and discovers the - /// system fonts. This matches the GDI+ new InstalledFontCollection() - /// semantics where construction enumerates installed fonts. - /// - public InstalledFontCollection() - : this(scanSystem: true) - { - } - - /// - /// Initializes a new optionally - /// discovering the system fonts. - /// - /// - /// true to discover system fonts; false to create an empty - /// collection containing only the generic fallback families. - /// - private InstalledFontCollection(bool scanSystem) - { - // Always register the generic families first so that GenericSansSerif, - // GenericSerif and GenericMonospace resolve even when no system fonts are found. - AddOrMergeFamily(FontFamily.GenericSansSerif); - AddOrMergeFamily(FontFamily.GenericSerif); - AddOrMergeFamily(FontFamily.GenericMonospace); - - if (scanSystem) - DiscoverSystemFonts(); - } - - /// - /// Creates the default instance used by , respecting - /// the current . - /// - private static InstalledFontCollection CreateDefaultInstance() - { - if (!FontSettings.AutoLoadSystemFonts) - return new InstalledFontCollection(scanSystem: false); - - return new InstalledFontCollection(scanSystem: true); - } - - /// - /// Discovers system fonts using the configured strategy: native APIs first - /// (when enabled), then directory scanning as a fallback. - /// - private void DiscoverSystemFonts() - { - bool nativeSucceeded = false; - - if (FontSettings.UseNativeFontApis) - { - nativeSucceeded = TryDiscoverViaNativeApi(); - - // Query the OS default font family regardless of whether font discovery - // succeeded — the default family query is independent. - if (NativeFontDiscovery.TryGetDefaultFamilyName(out string? defaultName)) - DefaultFamilyName = defaultName; - } - - // Fall back to directory scanning when native APIs are disabled or returned - // no results. - if (!nativeSucceeded) - ScanSystemFontDirectories(); - } - - /// - /// Tries to discover fonts using the platform's native API. Returns - /// true when the native API was available and returned results. - /// - private bool TryDiscoverViaNativeApi() - { - if (!NativeFontDiscovery.TryDiscoverFonts(out IReadOnlyList fonts)) - return false; - - foreach (NativeFontInfo font in fonts) - { - try - { - AddFacesFromSource(new FileSystemStreamSource(font.FilePath)); - } - catch - { - // Skip corrupt, locked, or unsupported font files. - } - } - - return true; - } - - /// - /// Scans every platform-specific font directory and loads each supported font - /// file into this collection. This is the fallback when native APIs are - /// unavailable or disabled. - /// - private void ScanSystemFontDirectories() - { - foreach (string directory in SystemFontScanner.GetStandardFontDirectories()) - { - foreach (string file in SystemFontScanner.EnumerateFontFiles(directory)) - { - try - { - AddFacesFromSource(new FileSystemStreamSource(file)); - } - catch - { - // Skip corrupt, locked, or unsupported font files. - } - } - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Native/LinuxFontDiscovery.cs b/src/MiniPdf/Drawing/Text/Native/LinuxFontDiscovery.cs deleted file mode 100644 index afff3bc6..00000000 --- a/src/MiniPdf/Drawing/Text/Native/LinuxFontDiscovery.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; - -namespace MiniSoftware.Drawing.Text.Native -{ - /// - /// Discovers installed fonts on Linux using fontconfig. Fontconfig is the - /// authoritative font service on virtually all Linux desktop and server - /// distributions and respects aliases, non-standard install locations, and - /// per-user configuration. - /// - internal static class LinuxFontDiscovery - { - private const string FontconfigLibrary = "fontconfig"; - - /// FcSetSystem — the system-wide font set. - private const int FcSetSystem = 0; - - /// FcResultMatch — the pattern field was found. - private const int FcResultMatch = 0; - - [StructLayout(LayoutKind.Sequential)] - private struct FcFontSet - { - public int NFont; - public int SFont; - public IntPtr Fonts; // FcPattern** - } - - [DllImport(FontconfigLibrary)] - private static extern IntPtr FcInitLoadConfigAndFonts(); - - [DllImport(FontconfigLibrary)] - private static extern IntPtr FcConfigGetFonts(IntPtr config, int set); - - [DllImport(FontconfigLibrary)] - private static extern void FcFontSetDestroy(IntPtr fontSet); - - [DllImport(FontconfigLibrary)] - private static extern int FcPatternGetString(IntPtr pattern, string field, int id, out IntPtr result); - - [DllImport(FontconfigLibrary)] - private static extern void FcPatternDestroy(IntPtr pattern); - - /// - /// Tries to discover installed fonts using fontconfig. - /// - public static bool TryDiscoverFonts(out IReadOnlyList fonts) - { - var results = new List(); - - try - { - IntPtr config = FcInitLoadConfigAndFonts(); - if (config == IntPtr.Zero) - { - fonts = Array.Empty(); - return false; - } - - IntPtr fontSetPtr = FcConfigGetFonts(config, FcSetSystem); - if (fontSetPtr == IntPtr.Zero) - { - fonts = Array.Empty(); - return false; - } - - try - { - FcFontSet fontSet = Marshal.PtrToStructure(fontSetPtr); - IntPtr[] patternPtrs = new IntPtr[fontSet.NFont]; - Marshal.Copy(fontSet.Fonts, patternPtrs, 0, fontSet.NFont); - - for (int i = 0; i < fontSet.NFont; i++) - { - IntPtr pattern = patternPtrs[i]; - if (pattern == IntPtr.Zero) - continue; - - string? family = GetStringField(pattern, "family"); - string? file = GetStringField(pattern, "file"); - - if (!string.IsNullOrEmpty(family) && !string.IsNullOrEmpty(file)) - results.Add(new NativeFontInfo(family!, file!)); - } - } - finally - { - FcFontSetDestroy(fontSetPtr); - } - } - catch - { - // fontconfig may not be installed (minimal containers, Alpine without fontconfig). - fonts = Array.Empty(); - return false; - } - - if (results.Count == 0) - { - fonts = Array.Empty(); - return false; - } - - fonts = results; - return true; - } - - /// - /// Tries to get the Linux default UI font family name. There is no single - /// "default" font on Linux; fontconfig's monospace and sans-serif - /// aliases resolve to the desktop environment's preferred font. We return - /// "sans-serif" as the fontconfig alias that every conformant installation - /// resolves to a real family. - /// - public static bool TryGetDefaultFamilyName(out string? familyName) - { - // fontconfig guarantees that "sans-serif", "serif", and "monospace" aliases - // always resolve to an installed font. We return the generic alias; the caller - // can resolve it to a concrete family via the discovered font list. - familyName = "sans-serif"; - return true; - } - - private static string? GetStringField(IntPtr pattern, string field) - { - int result = FcPatternGetString(pattern, field, 0, out IntPtr stringPtr); - if (result != FcResultMatch || stringPtr == IntPtr.Zero) - return null; - - // fontconfig strings are null-terminated UTF-8. The pointer is owned by the - // pattern and must not be freed. - return PtrToUtf8String(stringPtr); - } - - private static string? PtrToUtf8String(IntPtr ptr) - { - // Read bytes until null terminator. - int length = 0; - while (Marshal.ReadByte(ptr, length) != 0) - length++; - - if (length == 0) - return null; - - byte[] buffer = new byte[length]; - Marshal.Copy(ptr, buffer, 0, length); - return Encoding.UTF8.GetString(buffer); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Native/MacFontDiscovery.cs b/src/MiniPdf/Drawing/Text/Native/MacFontDiscovery.cs deleted file mode 100644 index a77d9304..00000000 --- a/src/MiniPdf/Drawing/Text/Native/MacFontDiscovery.cs +++ /dev/null @@ -1,245 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Text; - -namespace MiniSoftware.Drawing.Text.Native -{ - /// - /// Discovers installed fonts on macOS using the CoreText framework. CoreText is the - /// authoritative source of font information on macOS and returns family names and - /// file paths that match what native macOS applications see. - /// - internal static class MacFontDiscovery - { - private const string CoreTextLibrary = "/System/Library/Frameworks/CoreText.framework/CoreText"; - private const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; - - /// kCFStringEncodingUTF8 - private const int KCFStringEncodingUTF8 = 0x08000100; - - /// kCTFontURLAttribute - private const string KCTFontURLAttribute = "CTFontURLAttribute"; - - [DllImport(CoreTextLibrary)] - private static extern IntPtr CTFontManagerCopyAvailableFontFamilyNames(); - - [DllImport(CoreTextLibrary)] - private static extern IntPtr CTFontCreateWithName(IntPtr name, double size, IntPtr matrix); - - [DllImport(CoreTextLibrary)] - private static extern IntPtr CTFontCopyAttribute(IntPtr font, IntPtr attribute); - - [DllImport(CoreFoundationLibrary)] - private static extern long CFArrayGetCount(IntPtr array); - - [DllImport(CoreFoundationLibrary)] - private static extern IntPtr CFArrayGetValueAtIndex(IntPtr array, long idx); - - [DllImport(CoreFoundationLibrary)] - private static extern long CFStringGetLength(IntPtr theString); - - [DllImport(CoreFoundationLibrary)] - private static extern byte CFStringGetCString(IntPtr theString, byte[] buffer, long bufferSize, int encoding); - - [DllImport(CoreFoundationLibrary)] - private static extern byte CFURLGetFileSystemRepresentation(IntPtr url, byte resolveAgainstBase, byte[] buffer, long bufferLength); - - [DllImport(CoreFoundationLibrary)] - private static extern void CFRelease(IntPtr cf); - - /// - /// Tries to discover installed fonts using CoreText. - /// - public static bool TryDiscoverFonts(out IReadOnlyList fonts) - { - var results = new List(); - - try - { - IntPtr familyNames = CTFontManagerCopyAvailableFontFamilyNames(); - if (familyNames == IntPtr.Zero) - { - fonts = Array.Empty(); - return false; - } - - try - { - long count = CFArrayGetCount(familyNames); - for (long i = 0; i < count; i++) - { - IntPtr familyNameRef = CFArrayGetValueAtIndex(familyNames, i); - string? familyName = CFStringToString(familyNameRef); - if (string.IsNullOrEmpty(familyName)) - continue; - - // Resolve the file path for the first face in this family. - string? filePath = ResolveFontPath(familyName); - if (!string.IsNullOrEmpty(filePath)) - results.Add(new NativeFontInfo(familyName!, filePath)); - } - } - finally - { - CFRelease(familyNames); - } - } - catch - { - // CoreText may be unavailable in some sandboxed environments. - fonts = Array.Empty(); - return false; - } - - if (results.Count == 0) - { - fonts = Array.Empty(); - return false; - } - - fonts = results; - return true; - } - - /// - /// Tries to get the macOS default UI font family name. On modern macOS this is - /// "SF Pro" (San Francisco); on older versions it is "Helvetica Neue". - /// - public static bool TryGetDefaultFamilyName(out string? familyName) - { - // CoreText does not expose a direct "system font" query via simple P/Invoke. - // The system font on macOS 10.11+ is ".AppleSystemUIFont" which resolves to - // "SF Pro Text"/"SF Pro Display". We try that alias first, then fall back to - // "Helvetica Neue". - try - { - IntPtr font = CTFontCreateWithName(CreateCFString(".AppleSystemUIFont"), 12.0, IntPtr.Zero); - if (font != IntPtr.Zero) - { - try - { - // The family name of the system font is "System Font" on recent macOS. - // We return a known-good default instead. - familyName = "Helvetica Neue"; - return true; - } - finally - { - CFRelease(font); - } - } - } - catch - { - // CoreText unavailable. - } - - familyName = null; - return false; - } - - private static string? ResolveFontPath(string familyName) - { - IntPtr nameRef = CreateCFString(familyName); - if (nameRef == IntPtr.Zero) - return null; - - try - { - IntPtr font = CTFontCreateWithName(nameRef, 12.0, IntPtr.Zero); - if (font == IntPtr.Zero) - return null; - - try - { - IntPtr attrNameRef = CreateCFString(KCTFontURLAttribute); - if (attrNameRef == IntPtr.Zero) - return null; - - try - { - IntPtr url = CTFontCopyAttribute(font, attrNameRef); - if (url == IntPtr.Zero) - return null; - - try - { - var buffer = new byte[1024]; - if (CFURLGetFileSystemRepresentation(url, 1, buffer, buffer.Length) != 0) - { - int nullIndex = Array.IndexOf(buffer, (byte)0); - int length = nullIndex >= 0 ? nullIndex : buffer.Length; - return Encoding.UTF8.GetString(buffer, 0, length); - } - } - finally - { - CFRelease(url); - } - } - finally - { - CFRelease(attrNameRef); - } - } - finally - { - CFRelease(font); - } - } - finally - { - CFRelease(nameRef); - } - - return null; - } - - private static string? CFStringToString(IntPtr cfString) - { - if (cfString == IntPtr.Zero) - return null; - - // Try a generous buffer first; CFStringGetCString truncates if too small. - var buffer = new byte[512]; - if (CFStringGetCString(cfString, buffer, buffer.Length, KCFStringEncodingUTF8) != 0) - { - int nullIndex = Array.IndexOf(buffer, (byte)0); - int length = nullIndex >= 0 ? nullIndex : buffer.Length; - return Encoding.UTF8.GetString(buffer, 0, length); - } - - // Fallback: allocate a larger buffer based on the string length. - long lengthInUTF16 = CFStringGetLength(cfString); - int maxBytes = (int)(lengthInUTF16 * 4) + 1; - if (maxBytes > 65536) - maxBytes = 65536; - - var bigBuffer = new byte[maxBytes]; - if (CFStringGetCString(cfString, bigBuffer, bigBuffer.Length, KCFStringEncodingUTF8) != 0) - { - int nullIndex = Array.IndexOf(bigBuffer, (byte)0); - int length = nullIndex >= 0 ? nullIndex : bigBuffer.Length; - return Encoding.UTF8.GetString(bigBuffer, 0, length); - } - - return null; - } - - /// - /// Creates a CoreFoundation CFString from a .NET string. The caller must - /// the result. - /// - private static IntPtr CreateCFString(string str) - { - // We use CFStringCreateWithBytes for reliable UTF-8 creation. - byte[] bytes = Encoding.UTF8.GetBytes(str); - return CFStringCreateWithBytes(IntPtr.Zero, bytes, bytes.Length, KCFStringEncodingUTF8, 0); - } - - [DllImport(CoreFoundationLibrary)] - private static extern IntPtr CFStringCreateWithBytes( - IntPtr alloc, byte[] bytes, long numBytes, int encoding, byte isExternalRepresentation); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Native/NativeFontDiscovery.cs b/src/MiniPdf/Drawing/Text/Native/NativeFontDiscovery.cs deleted file mode 100644 index b89c40cf..00000000 --- a/src/MiniPdf/Drawing/Text/Native/NativeFontDiscovery.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Text.Native -{ - /// - /// Dispatches font discovery to the platform-specific native implementation. When - /// the native API is unavailable or returns no results, the caller falls back to - /// directory scanning via . - /// - internal static class NativeFontDiscovery - { - /// - /// Tries to discover installed fonts using the platform's native font service. - /// - /// - /// When this method returns true, a list of discovered font faces with - /// their family names and file paths. When false, the list is empty and - /// the caller should fall back to directory scanning. - /// - /// - /// true if the native API was available and returned results; otherwise - /// false. - /// - public static bool TryDiscoverFonts(out IReadOnlyList fonts) - { - if (global::MiniSoftware.Compat.IsWindows()) - return WindowsFontDiscovery.TryDiscoverFonts(out fonts); - - if (global::MiniSoftware.Compat.IsMacOS()) - return MacFontDiscovery.TryDiscoverFonts(out fonts); - - if (global::MiniSoftware.Compat.IsLinux()) - return LinuxFontDiscovery.TryDiscoverFonts(out fonts); - - fonts = System.Array.Empty(); - return false; - } - - /// - /// Tries to get the operating system's default UI font family name. - /// - /// - /// When this method returns true, the default font family name. - /// - /// - /// true if the operating system returned a default family name. - /// - public static bool TryGetDefaultFamilyName(out string? familyName) - { - if (global::MiniSoftware.Compat.IsWindows()) - return WindowsFontDiscovery.TryGetDefaultFamilyName(out familyName); - - if (global::MiniSoftware.Compat.IsMacOS()) - return MacFontDiscovery.TryGetDefaultFamilyName(out familyName); - - if (global::MiniSoftware.Compat.IsLinux()) - return LinuxFontDiscovery.TryGetDefaultFamilyName(out familyName); - - familyName = null; - return false; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Native/NativeFontInfo.cs b/src/MiniPdf/Drawing/Text/Native/NativeFontInfo.cs deleted file mode 100644 index 6699964d..00000000 --- a/src/MiniPdf/Drawing/Text/Native/NativeFontInfo.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace MiniSoftware.Drawing.Text.Native -{ - /// - /// Describes a single font face discovered via a native operating-system API. - /// - internal readonly struct NativeFontInfo - { - /// - /// The font family name as reported by the operating system. - /// - public string FamilyName { get; } - - /// - /// The absolute file system path to the font file. - /// - public string FilePath { get; } - - public NativeFontInfo(string familyName, string filePath) - { - FamilyName = familyName; - FilePath = filePath; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/Native/WindowsFontDiscovery.cs b/src/MiniPdf/Drawing/Text/Native/WindowsFontDiscovery.cs deleted file mode 100644 index 58c495cc..00000000 --- a/src/MiniPdf/Drawing/Text/Native/WindowsFontDiscovery.cs +++ /dev/null @@ -1,260 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; - -namespace MiniSoftware.Drawing.Text.Native -{ - /// - /// Discovers installed fonts on Windows by reading the font registry keys via - /// raw P/Invoke to advapi32.dll. This avoids any NuGet dependency on - /// Microsoft.Win32.Registry while still resolving family names to file - /// paths — including fonts installed outside the standard - /// %SYSTEMROOT%\Fonts directory — and following font substitution rules - /// for the default UI font. - /// - internal static class WindowsFontDiscovery - { - private const string MachineFontsKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"; - private const string UserFontsKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"; - private const string FontSubstitutesKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes"; - - private const int HKEY_LOCAL_MACHINE = unchecked((int)0x80000002); - private const int HKEY_CURRENT_USER = unchecked((int)0x80000001); - - private const int ERROR_SUCCESS = 0; - private const int ERROR_NO_MORE_ITEMS = 259; - - // Registry value types - private const int REG_SZ = 1; - - /// - /// The suffixes that Windows appends to font family names in the registry value - /// names, e.g. "Arial (TrueType)" or "Arial Bold (OpenType)". - /// - private static readonly string[] StyleSuffixes = - { - " (TrueType)", - " (OpenType)", - " (VGA res)", - " (All res)", - }; - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int RegOpenKeyEx(int hKey, string subKey, int options, int samDesired, out IntPtr phkResult); - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int RegCloseKey(IntPtr hKey); - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int RegEnumValueW(IntPtr hKey, int dwIndex, StringBuilder lpValueName, ref int lpcchValueName, IntPtr lpReserved, ref int lpType, byte[] lpData, ref int lpcbData); - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int RegQueryValueExW(IntPtr hKey, string lpValueName, IntPtr lpReserved, ref int lpType, byte[] lpData, ref int lpcbData); - - private const int KEY_READ = 0x20019; - - /// - /// Tries to discover installed fonts by reading the Windows font registry keys. - /// - public static bool TryDiscoverFonts(out IReadOnlyList fonts) - { - var results = new List(); - string systemRoot = Environment.GetEnvironmentVariable("SYSTEMROOT"); - if (string.IsNullOrWhiteSpace(systemRoot)) - systemRoot = @"C:\Windows"; - - string fontsDir = Path.Combine(systemRoot, "Fonts"); - - // Machine-wide fonts (HKLM). - ReadRegistryFonts(HKEY_LOCAL_MACHINE, MachineFontsKey, fontsDir, results); - - // Per-user fonts (HKCU). - ReadRegistryFonts(HKEY_CURRENT_USER, UserFontsKey, fontsDir, results); - - if (results.Count == 0) - { - fonts = Array.Empty(); - return false; - } - - fonts = results; - return true; - } - - /// - /// Tries to get the Windows default UI font family name by resolving the - /// "MS Shell Dlg 2" font substitute (which maps to "Segoe UI" on modern Windows). - /// - public static bool TryGetDefaultFamilyName(out string? familyName) - { - IntPtr hKey = IntPtr.Zero; - try - { - int rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, FontSubstitutesKey, 0, KEY_READ, out hKey); - if (rc != ERROR_SUCCESS) - { - familyName = null; - return false; - } - - string? substitute = ReadStringValue(hKey, "MS Shell Dlg 2"); - if (!string.IsNullOrWhiteSpace(substitute)) - { - familyName = substitute; - return true; - } - } - catch - { - // Registry access may fail in restricted environments. - } - finally - { - if (hKey != IntPtr.Zero) - RegCloseKey(hKey); - } - - familyName = null; - return false; - } - - private static void ReadRegistryFonts( - int rootKey, - string subKey, - string fontsDir, - List results) - { - IntPtr hKey = IntPtr.Zero; - try - { - int rc = RegOpenKeyEx(rootKey, subKey, 0, KEY_READ, out hKey); - if (rc != ERROR_SUCCESS) - return; - - int index = 0; - while (true) - { - var valueNameBuilder = new StringBuilder(256); - int valueNameLen = valueNameBuilder.Capacity; - int type = 0; - int dataLen = 0; - - rc = RegEnumValueW(hKey, index, valueNameBuilder, ref valueNameLen, IntPtr.Zero, ref type, null, ref dataLen); - if (rc == ERROR_NO_MORE_ITEMS) - break; - if (rc != ERROR_SUCCESS) - break; - - index++; - - // Only interested in string values (REG_SZ). - if (type != REG_SZ) - continue; - - // Read the data. - byte[] data = new byte[dataLen]; - int dataLen2 = dataLen; - rc = RegEnumValueW(hKey, index - 1, valueNameBuilder, ref valueNameLen, IntPtr.Zero, ref type, data, ref dataLen2); - if (rc != ERROR_SUCCESS || type != REG_SZ) - continue; - - string valueName = valueNameBuilder.ToString(); - string filePath = ReadRegSzString(data, dataLen2); - - string familyName = ExtractFamilyName(valueName); - if (string.IsNullOrEmpty(familyName)) - continue; - - string resolvedPath = ResolveFilePath(filePath, fontsDir); - if (resolvedPath != null) - results.Add(new NativeFontInfo(familyName, resolvedPath)); - } - } - catch - { - // Registry access may fail due to permissions. - } - finally - { - if (hKey != IntPtr.Zero) - RegCloseKey(hKey); - } - } - - /// - /// Reads a REG_SZ value from an open registry key. - /// - private static string? ReadStringValue(IntPtr hKey, string valueName) - { - int type = 0; - int dataLen = 0; - - int rc = RegQueryValueExW(hKey, valueName, IntPtr.Zero, ref type, null, ref dataLen); - if (rc != ERROR_SUCCESS || type != REG_SZ || dataLen == 0) - return null; - - byte[] data = new byte[dataLen]; - rc = RegQueryValueExW(hKey, valueName, IntPtr.Zero, ref type, data, ref dataLen); - if (rc != ERROR_SUCCESS) - return null; - - return ReadRegSzString(data, dataLen); - } - - /// - /// Converts a REG_SZ byte buffer to a string, trimming the trailing null. - /// - private static string ReadRegSzString(byte[] data, int dataLen) - { - // REG_SZ is UTF-16LE, null-terminated. Trim trailing nulls. - int charCount = dataLen / 2; - if (charCount > 0 && data[dataLen - 1] == 0 && data[dataLen - 2] == 0) - charCount--; - - return Encoding.Unicode.GetString(data, 0, charCount * 2); - } - - /// - /// Extracts the font family name from a registry value name by stripping the - /// style suffix in parentheses, e.g. "Arial Bold (TrueType)" → "Arial Bold". - /// - private static string ExtractFamilyName(string valueName) - { - string name = valueName; - foreach (string suffix in StyleSuffixes) - { - if (name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) - { - name = name.Substring(0, name.Length - suffix.Length); - break; - } - } - return name.Trim(); - } - - /// - /// Resolves a font file path from the registry value. The value may be a bare - /// filename (relative to %SYSTEMROOT%\Fonts) or an absolute path. - /// - private static string? ResolveFilePath(string filePath, string fontsDir) - { - if (string.IsNullOrWhiteSpace(filePath)) - return null; - - // Per-user fonts may store absolute paths. - if (Path.IsPathRooted(filePath)) - return File.Exists(filePath) ? filePath : null; - - // Machine fonts are typically bare filenames relative to %SYSTEMROOT%\Fonts. - string combined = Path.Combine(fontsDir, filePath); - if (File.Exists(combined)) - return combined; - - // Some entries use relative paths with subdirectories. - combined = Path.GetFullPath(Path.Combine(fontsDir, filePath)); - return File.Exists(combined) ? combined : null; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/PathArcLength.cs b/src/MiniPdf/Drawing/Text/PathArcLength.cs deleted file mode 100644 index e603c4eb..00000000 --- a/src/MiniPdf/Drawing/Text/PathArcLength.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Arc-length parameterization of a flattened . - /// Builds a walkable map of cumulative segment lengths per subpath so that - /// a caller can ask "what point and tangent angle is at distance D along - /// the path?". - /// - internal sealed class PathArcLength - { - private readonly Subpath[] _subpaths; - private readonly float _totalLength; - - private PathArcLength(Subpath[] subpaths, float totalLength) - { - _subpaths = subpaths; - _totalLength = totalLength; - } - - /// Total arc length of the path, in path-local units. - public float TotalLength => _totalLength; - - /// Number of subpaths (figures) in the path. - public int SubpathCount => _subpaths.Length; - - // ── Construction ────────────────────────────────────────────────────── - - /// - /// Flattens (de Casteljau) and builds the - /// arc-length map. The input path is not modified (a flattened clone is - /// used internally). - /// - public static PathArcLength Build(GraphicsPath baseline) - { - if (baseline == null) throw new ArgumentNullException(nameof(baseline)); - if (baseline.PointCount == 0) - return new PathArcLength(Array.Empty(), 0f); - - GraphicsPath flat = baseline.Clone(); - flat.Flatten(); - - PointF[] pts = flat.PathPoints; - byte[] types = flat.PathTypes; - - var subpaths = new List(); - float totalLength = 0f; - - int i = 0; - while (i < pts.Length) - { - int start = i; - i++; - while (i < pts.Length && (types[i] & 0x07) != (byte)PathPointType.Start) - i++; - int end = i - 1; // inclusive - - int count = end - start + 1; - if (count < 2) - continue; // degenerate single-point figure - - bool closed = (types[end] & (byte)PathPointType.CloseSubpath) != 0; - - int segCount = count - 1 + (closed ? 1 : 0); - var segs = new Segment[segCount]; - var cum = new float[segCount + 1]; - cum[0] = 0f; - float length = 0f; - - int s = 0; - for (int j = 0; j < count - 1; j++) - { - PointF a = pts[start + j]; - PointF b = pts[start + j + 1]; - float d = Dist(a, b); - segs[s] = new Segment(a, b, d); - length += d; - cum[s + 1] = length; - s++; - } - if (closed) - { - PointF a = pts[start + count - 1]; - PointF b = pts[start]; - float d = Dist(a, b); - segs[s] = new Segment(a, b, d); - length += d; - cum[s + 1] = length; - } - - subpaths.Add(new Subpath(segs, cum, length, closed, totalLength)); - totalLength += length; - } - - return new PathArcLength(subpaths.ToArray(), totalLength); - } - - // ── Query ───────────────────────────────────────────────────────────── - - /// - /// Returns the point and tangent angle (degrees, screen space) at the - /// given arc-length . Distances outside - /// [0, TotalLength] are clamped. For a closed subpath, the local - /// distance wraps modulo the subpath length. - /// - /// false if the path is empty. - public bool GetPointAt(float distance, out PointF point, out float angleDegrees) - { - point = new PointF(float.NaN, float.NaN); - angleDegrees = 0f; - - if (_totalLength <= 0f || _subpaths.Length == 0) - return false; - - if (distance < 0f) distance = 0f; - if (distance > _totalLength) distance = _totalLength; - - // Find the subpath containing this distance. - Subpath sub = _subpaths[_subpaths.Length - 1]; - for (int k = 0; k < _subpaths.Length; k++) - { - if (distance <= _subpaths[k].StartOffset + _subpaths[k].Length) - { - sub = _subpaths[k]; - break; - } - } - - float localDist = distance - sub.StartOffset; - if (sub.Closed && sub.Length > 0f) - { - localDist = localDist % sub.Length; - if (localDist < 0f) localDist += sub.Length; - } - - Segment[] segs = sub.Segments; - float[] cum = sub.Cumulative; - if (segs.Length == 0) - return false; - - // Binary search: largest index where cum[index] <= localDist. - int lo = 0; - int hi = segs.Length - 1; - if (localDist >= cum[segs.Length]) - { - lo = segs.Length - 1; - } - else - { - while (lo < hi) - { - int mid = (lo + hi + 1) / 2; - if (cum[mid] <= localDist) - lo = mid; - else - hi = mid - 1; - } - } - - Segment seg = segs[lo]; - float segLen = seg.Length; - float t = segLen > 0f ? (localDist - cum[lo]) / segLen : 0f; - if (t < 0f) t = 0f; - if (t > 1f) t = 1f; - - point = new PointF( - seg.Start.X + (seg.End.X - seg.Start.X) * t, - seg.Start.Y + (seg.End.Y - seg.Start.Y) * t); - angleDegrees = (float)(Math.Atan2( - seg.End.Y - seg.Start.Y, - seg.End.X - seg.Start.X) * 180.0 / Math.PI); - return true; - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static float Dist(PointF a, PointF b) - { - float dx = b.X - a.X, dy = b.Y - a.Y; - return (float)Math.Sqrt(dx * dx + dy * dy); - } - - private readonly struct Segment - { - public readonly PointF Start; - public readonly PointF End; - public readonly float Length; - - public Segment(PointF start, PointF end, float length) - { - Start = start; - End = end; - Length = length; - } - } - - private readonly struct Subpath - { - public readonly Segment[] Segments; - public readonly float[] Cumulative; - public readonly float Length; - public readonly bool Closed; - public readonly float StartOffset; - - public Subpath(Segment[] segments, float[] cumulative, - float length, bool closed, float startOffset) - { - Segments = segments; - Cumulative = cumulative; - Length = length; - Closed = closed; - StartOffset = startOffset; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/PrivateFontCollection.cs b/src/MiniPdf/Drawing/Text/PrivateFontCollection.cs deleted file mode 100644 index 3839a6c6..00000000 --- a/src/MiniPdf/Drawing/Text/PrivateFontCollection.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.IO; -using System.Runtime.InteropServices; -using MiniSoftware.Drawing.Font.Sources; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Represents a collection of font families provided by the application. - /// - public sealed class PrivateFontCollection : FontCollection - { - /// - /// Adds a font from the specified file to the collection. - /// - /// The path to the font file. - public void AddFontFile(string filename) - { - if (string.IsNullOrWhiteSpace(filename)) - throw new ArgumentException("File path must not be empty.", nameof(filename)); - if (!File.Exists(filename)) - throw new FileNotFoundException("Font file was not found.", filename); - - AddFacesFromSource(new FileSystemStreamSource(filename)); - } - - /// - /// Adds a font from memory to the collection. - /// - /// A pointer to the memory block containing the font data. - /// The length of the font data in bytes. - public void AddMemoryFont(IntPtr memory, int length) - { - if (memory == IntPtr.Zero) - throw new ArgumentNullException(nameof(memory)); - if (length <= 0) - throw new ArgumentOutOfRangeException(nameof(length), "Length must be positive."); - - var bytes = new byte[length]; - Marshal.Copy(memory, bytes, 0, length); - AddFacesFromSource(new ByteContentStreamSource(bytes)); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/ResolvedRun.cs b/src/MiniPdf/Drawing/Text/ResolvedRun.cs deleted file mode 100644 index 83571582..00000000 --- a/src/MiniPdf/Drawing/Text/ResolvedRun.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MiniSoftware.Drawing.Brushes; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// A text run after rich-run, bidi, and fallback resolution. Each - /// has a single font, single brush, single - /// direction, and single bidi level. - /// - internal sealed class ResolvedRun - { - internal ResolvedRun( - string text, - Font font, - Brush? brush, - int bidiLevel, - int sourceStart) - { - Text = text; - Font = font; - Brush = brush; - BidiLevel = bidiLevel; - IsRTL = (bidiLevel & 1) == 1; - SourceStart = sourceStart; - } - - /// The characters in this run (a substring of the source text). - public string Text { get; } - - /// Font used for this run (may differ from the default when fallback or rich overrides apply). - public Font Font { get; } - - /// Foreground brush for this run, or null to use the default brush. - public Brush? Brush { get; } - - /// Unicode bidirectional embedding level (even = LTR, odd = RTL). - public int BidiLevel { get; } - - /// True when this run is right-to-left (bidiLevel is odd). - public bool IsRTL { get; } - - /// Start index of this run's text within the original source string. - public int SourceStart { get; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/RichTextOptions.cs b/src/MiniPdf/Drawing/Text/RichTextOptions.cs deleted file mode 100644 index 872d65ee..00000000 --- a/src/MiniPdf/Drawing/Text/RichTextOptions.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Enums; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Rich-text layout options for and - /// . Carries a list of - /// segments and default font properties. - /// - public sealed class RichTextOptions - { - /// - /// Initializes a new with the specified - /// default font family, size, and style. - /// - public RichTextOptions(FontFamily family, float emSize, FontStyle style = FontStyle.Regular) - { - FontFamily = family ?? throw new ArgumentNullException(nameof(family)); - EmSize = emSize; - FontStyle = style; - Unit = GraphicsUnit.Point; - } - - /// Default font family for runs without a override. - public FontFamily FontFamily { get; } - - /// Default em size for runs without a override. - public float EmSize { get; } - - /// Default font style for runs without a override. - public FontStyle FontStyle { get; } - - /// Unit for and . Default . - public GraphicsUnit Unit { get; set; } = GraphicsUnit.Point; - - /// - /// Rich text runs. Characters not covered by any run use the default - /// font/size/style. Runs may overlap; later runs win for overlapping - /// ranges (matches ImageSharp RichTextOptions.Runs semantics). - /// - public IList Runs { get; } = new List(); - - /// - /// Fallback font chain override for this rich-text operation, or null - /// to use (or the system default). - /// - public FontFallbackChain? Fallback { get; set; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/RichTextRun.cs b/src/MiniPdf/Drawing/Text/RichTextRun.cs deleted file mode 100644 index 0b5e7d1e..00000000 --- a/src/MiniPdf/Drawing/Text/RichTextRun.cs +++ /dev/null @@ -1,55 +0,0 @@ -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Enums; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Describes a contiguous range of characters within a rich-text string that - /// share font, style, size, and/or foreground brush overrides. Used with - /// . - /// - public sealed class RichTextRun - { - /// - /// Initializes a new for the specified range. - /// - /// Zero-based start index within the text. - /// Number of characters in the run. - public RichTextRun(int start, int length) - { - if (start < 0) throw new System.ArgumentOutOfRangeException(nameof(start)); - if (length < 0) throw new System.ArgumentOutOfRangeException(nameof(length)); - Start = start; - Length = length; - } - - /// Zero-based start index within the text. - public int Start { get; } - - /// Number of characters in the run. - public int Length { get; } - - /// - /// Font family override for this run, or null to use the default - /// family from . - /// - public FontFamily? FontFamily { get; set; } - - /// - /// Font style override for this run, or null to use the default style. - /// - public FontStyle? FontStyle { get; set; } - - /// - /// Em size override for this run (in the unit specified by - /// ), or null to use the default size. - /// - public float? EmSize { get; set; } - - /// - /// Foreground brush override for this run, or null to use the - /// defaultBrush passed to . - /// - public Brush? Brush { get; set; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/RunSegmenter.cs b/src/MiniPdf/Drawing/Text/RunSegmenter.cs deleted file mode 100644 index 9fe26a1d..00000000 --- a/src/MiniPdf/Drawing/Text/RunSegmenter.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Text.Bidi; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Orchestrates rich-run → bidi → fallback splitting to produce - /// objects for multi-run text layout. - /// - internal static class RunSegmenter - { - internal static List Segment( - string text, - Font defaultFont, - RichTextOptions? rich, - StringFormat sf, - FontFallbackChain? chain) - { - if (text == null) throw new ArgumentNullException(nameof(text)); - if (defaultFont == null) throw new ArgumentNullException(nameof(defaultFont)); - if (sf == null) throw new ArgumentNullException(nameof(sf)); - - bool fallbackEnabled = (sf.FormatFlags & StringFormatFlags.NoFontFallback) == 0; - - // ── 1. Rich runs (or one default run) ────────────────────────── - var rawRuns = new List<(string Text, Font Font, Brush? Brush, int Start)>(); - - if (rich != null && rich.Runs.Count > 0) - { - SplitByRichRuns(text, rich, defaultFont, rawRuns); - } - else - { - rawRuns.Add((text, defaultFont, null, 0)); - } - - // ── 2. Bidi on the full string ───────────────────────────────── - var paraDir = (sf.FormatFlags & StringFormatFlags.DirectionRightToLeft) != 0 - ? BidiParagraphDirection.RTL - : BidiParagraphDirection.Auto; - - int baseLevel = BidiAlgorithm.GetLevels(text, paraDir, out int[] levels); - - // Split each rich run at bidi-level boundaries - var bidiRuns = new List<(string Text, Font Font, Brush? Brush, int BidiLevel, int Start)>(); - foreach (var raw in rawRuns) - { - int segStart = 0; - for (int i = 1; i <= raw.Text.Length; i++) - { - int srcIdx = raw.Start + i - 1; - bool levelBoundary = (i >= raw.Text.Length) || - (raw.Start + i < levels.Length && - levels[raw.Start + i] != levels[srcIdx]); - if (levelBoundary) - { - int segEnd = i; - int srcStart = raw.Start + segStart; - bidiRuns.Add(( - raw.Text.Substring(segStart, segEnd - segStart), - raw.Font, - raw.Brush, - levels[srcStart], - srcStart)); - segStart = i; - } - } - } - - // ── 3. Fallback per visual segment ───────────────────────────── - var finalRuns = new List(); - - foreach (var br in bidiRuns) - { - var resolver = new FontFallbackResolver( - br.Font.FontFamily, br.Font.Style, chain, fallbackEnabled); - - var curFamily = br.Font.FontFamily; - int segStart = 0; - - for (int k = 0; k < br.Text.Length; k++) - { - uint cp = CodePointAt(br.Text, k); - var family = resolver.ResolveFamily(cp); - if (family != curFamily) - { - if (k > segStart) - { - finalRuns.Add(MakeRun(br, segStart, k, curFamily)); - } - curFamily = family; - segStart = k; - } - - // Advance past low surrogate - if (char.IsHighSurrogate(br.Text[k]) && k + 1 < br.Text.Length && char.IsLowSurrogate(br.Text[k + 1])) - k++; - } - - if (segStart < br.Text.Length) - { - finalRuns.Add(MakeRun(br, segStart, br.Text.Length, curFamily)); - } - } - - return finalRuns; - } - - internal static int GetBaseLevel(string text, StringFormat sf) - { - var paraDir = (sf.FormatFlags & StringFormatFlags.DirectionRightToLeft) != 0 - ? BidiParagraphDirection.RTL - : BidiParagraphDirection.Auto; - return BidiAlgorithm.GetLevels(text, paraDir, out _); - } - - private static void SplitByRichRuns( - string text, - RichTextOptions rich, - Font defaultFont, - List<(string Text, Font Font, Brush? Brush, int Start)> result) - { - var sortedRuns = new List(rich.Runs); - sortedRuns.Sort((a, b) => a.Start.CompareTo(b.Start)); - - int pos = 0; - foreach (var run in sortedRuns) - { - // Gap before this run uses default font - if (run.Start > pos) - { - int len = Math.Min(run.Start, text.Length) - pos; - if (len > 0) - result.Add((text.Substring(pos, len), defaultFont, null, pos)); - pos = Math.Min(run.Start, text.Length); - } - - int runEnd = Math.Min(run.Start + run.Length, text.Length); - if (runEnd <= pos) - continue; - - var family = run.FontFamily ?? rich.FontFamily; - var style = run.FontStyle ?? rich.FontStyle; - var emSize = run.EmSize ?? rich.EmSize; - - var font = new Font(family, emSize, style, rich.Unit); - result.Add((text.Substring(pos, runEnd - pos), font, run.Brush, pos)); - pos = runEnd; - } - - // Trailing gap - if (pos < text.Length) - result.Add((text.Substring(pos), defaultFont, null, pos)); - } - - private static ResolvedRun MakeRun( - (string Text, Font Font, Brush? Brush, int BidiLevel, int Start) br, - int segStart, int segEnd, FontFamily family) - { - var subText = br.Text.Substring(segStart, segEnd - segStart); - var font = family == br.Font.FontFamily - ? br.Font - : new Font(family, br.Font.Size, br.Font.Style, br.Font.Unit); - return new ResolvedRun( - subText, font, br.Brush, br.BidiLevel, br.Start + segStart); - } - - internal static uint CodePointAt(string text, int index) - { - char c = text[index]; - if (char.IsHighSurrogate(c) && index + 1 < text.Length && char.IsLowSurrogate(text[index + 1])) - return (uint)char.ConvertToUtf32(c, text[index + 1]); - return (uint)c; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/StringAlignment.cs b/src/MiniPdf/Drawing/Text/StringAlignment.cs deleted file mode 100644 index 06cc0132..00000000 --- a/src/MiniPdf/Drawing/Text/StringAlignment.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the alignment of a text string relative to a layout rectangle. - /// - public enum StringAlignment - { - /// - /// Align text near (left for horizontal, top for vertical). - /// - Near = 0, - - /// - /// Center-align the text. - /// - Center = 1, - - /// - /// Align text far (right for horizontal, bottom for vertical). - /// - Far = 2 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/StringDigitSubstitute.cs b/src/MiniPdf/Drawing/Text/StringDigitSubstitute.cs deleted file mode 100644 index 10c58580..00000000 --- a/src/MiniPdf/Drawing/Text/StringDigitSubstitute.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the substitution method for digit shapes in text. - /// - public enum StringDigitSubstitute - { - /// - /// User-defined digit substitution. - /// - User = 0, - - /// - /// No digit substitution. - /// - None = 1, - - /// - /// National digit substitution. - /// - National = 2, - - /// - /// Traditional digit substitution. - /// - Traditional = 3 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/StringFormat.cs b/src/MiniPdf/Drawing/Text/StringFormat.cs deleted file mode 100644 index e1588001..00000000 --- a/src/MiniPdf/Drawing/Text/StringFormat.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Encapsulates text layout information such as alignment, format flags, and tab stops. - /// - /// - /// A is used with to control - /// text alignment, line spacing, trimming, and other formatting options. - /// - public sealed class StringFormat : IDisposable - { - /// - /// Gets or sets the horizontal text alignment. - /// - public StringAlignment Alignment { get; set; } = StringAlignment.Near; - - /// - /// Gets or sets the vertical text alignment. - /// - public StringAlignment LineAlignment { get; set; } = StringAlignment.Near; - - /// - /// Gets or sets the trimming behavior for text that overflows the layout rectangle. - /// - public StringTrimming Trimming { get; set; } = StringTrimming.None; - - /// - /// Gets or sets the format flags that control text layout. - /// - public StringFormatFlags FormatFlags { get; set; } - - /// - /// Gets or sets the hotkey prefix handling for text. - /// - public HotkeyPrefix HotkeyPrefix { get; set; } = HotkeyPrefix.None; - - private float _firstTabOffset; - private float[] _tabStops = Array.Empty(); - private CharacterRange[] _measurableCharacterRanges = Array.Empty(); - - /// - /// Initializes a new with default settings. - /// - public StringFormat() { } - - /// - /// Initializes a new with the specified format flags. - /// - /// The format flags to apply. - public StringFormat(StringFormatFlags options) { FormatFlags = options; } - - /// - /// Initializes a new as a copy of an existing format. - /// - /// The format to copy. - public StringFormat(StringFormat format) - { - if (format == null) throw new ArgumentNullException(nameof(format)); - - Alignment = format.Alignment; - LineAlignment = format.LineAlignment; - Trimming = format.Trimming; - FormatFlags = format.FormatFlags; - HotkeyPrefix = format.HotkeyPrefix; - _firstTabOffset = format._firstTabOffset; - _tabStops = (float[])format._tabStops.Clone(); - _measurableCharacterRanges = (CharacterRange[])format._measurableCharacterRanges.Clone(); - } - - /// - /// Gets a with default settings. - /// - public static StringFormat GenericDefault => new StringFormat(); - - /// - /// Gets a with typographic settings. - /// - public static StringFormat GenericTypographic => new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoClip); - - /// - /// Sets the tab stops for this format. - /// - /// The offset of the first tab stop. - /// The array of tab stop positions. - public void SetTabStops(float firstTabOffset, float[] tabStops) - { - if (tabStops == null) throw new ArgumentNullException(nameof(tabStops)); - _firstTabOffset = firstTabOffset; - _tabStops = (float[])tabStops.Clone(); - } - - /// - /// Gets the tab stops for this format. - /// - /// The offset of the first tab stop. - /// An array of tab stop positions. - public float[] GetTabStops(out float firstTabOffset) - { - firstTabOffset = _firstTabOffset; - return (float[])_tabStops.Clone(); - } - - /// - /// Sets the character ranges that can be measured. - /// - /// The array of character ranges. - public void SetMeasurableCharacterRanges(CharacterRange[] ranges) - { - if (ranges == null) throw new ArgumentNullException(nameof(ranges)); - _measurableCharacterRanges = (CharacterRange[])ranges.Clone(); - } - - /// - /// Gets the character ranges that can be measured. - /// - /// An array of character ranges. - public CharacterRange[] GetMeasurableCharacterRanges() - => (CharacterRange[])_measurableCharacterRanges.Clone(); - - /// - /// Creates an exact copy of this . - /// - /// A new with the same settings. - public StringFormat Clone() => new StringFormat(this); - - /// - /// Releases all resources used by this format. - /// - public void Dispose() { } - } -} diff --git a/src/MiniPdf/Drawing/Text/StringFormatFlags.cs b/src/MiniPdf/Drawing/Text/StringFormatFlags.cs deleted file mode 100644 index 1285e9a6..00000000 --- a/src/MiniPdf/Drawing/Text/StringFormatFlags.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the display and layout information for text strings. - /// - [Flags] - public enum StringFormatFlags - { - /// - /// Text is displayed from right to left. - /// - DirectionRightToLeft = 1, - - /// - /// Text is displayed vertically. - /// - DirectionVertical = 2, - - /// - /// Text fits into the bounding box. - /// - FitBlackBox = 4, - - /// - /// Display format control characters. - /// - DisplayFormatControl = 0x20, - - /// - /// Disable font fallback. - /// - NoFontFallback = 0x400, - - /// - /// Include trailing spaces in measurement. - /// - MeasureTrailingSpaces = 0x800, - - /// - /// Disable text wrapping. - /// - NoWrap = 0x1000, - - /// - /// Limit text to a single line. - /// - LineLimit = 0x2000, - - /// - /// Disable text clipping. - /// - NoClip = 0x4000 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/StringTrimming.cs b/src/MiniPdf/Drawing/Text/StringTrimming.cs deleted file mode 100644 index 480a7afe..00000000 --- a/src/MiniPdf/Drawing/Text/StringTrimming.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies how to trim characters from a string that does not fit into a layout shape. - /// - public enum StringTrimming - { - /// - /// No trimming. - /// - None = 0, - - /// - /// Trim to the nearest character. - /// - Character = 1, - - /// - /// Trim to the nearest word. - /// - Word = 2, - - /// - /// Trim to the nearest character and append ellipsis. - /// - EllipsisCharacter = 3, - - /// - /// Trim to the nearest word and append ellipsis. - /// - EllipsisWord = 4, - - /// - /// Trim to the center of the word and append ellipsis. - /// - EllipsisPath = 5 - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/SystemFontScanner.cs b/src/MiniPdf/Drawing/Text/SystemFontScanner.cs deleted file mode 100644 index 070e7a8c..00000000 --- a/src/MiniPdf/Drawing/Text/SystemFontScanner.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Enumerates the platform-specific directories that hold installed fonts and - /// yields the font file paths within them. Used by - /// to populate the system font collection without any native API calls. - /// - internal static class SystemFontScanner - { - /// - /// File extensions recognised by the integrated font engine. The comparison is - /// case-insensitive (see ). - /// - private static readonly HashSet SupportedExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - ".ttf", - ".otf", - ".ttc", - ".otc", - ".woff", - ".woff2", - }; - - /// - /// Gets the platform-specific directories that conventionally hold installed fonts. - /// Only directories that exist on the current machine are returned. - /// - /// An enumerable of existing font directory paths. - public static IEnumerable GetStandardFontDirectories() - { - foreach (string candidate in GetCandidateDirectories()) - { - if (Directory.Exists(candidate)) - yield return candidate; - } - } - - /// - /// Enumerates every supported font file in , recursing - /// into subdirectories. Directories that cannot be read (permissions) are skipped - /// silently, mirroring the behaviour of SixLabors.Fonts. - /// - /// The directory to scan. - /// An enumerable of font file paths. - public static IEnumerable EnumerateFontFiles(string directory) - { - if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory)) - yield break; - - IEnumerable files; - try - { - files = Directory.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories); - } - catch - { - // Permissions / IO errors — skip this directory entirely. - yield break; - } - - foreach (string file in files) - { - string extension = Path.GetExtension(file); - if (extension.Length != 0 && SupportedExtensions.Contains(extension)) - yield return file; - } - } - - /// - /// Returns the platform-specific candidate font directories without checking - /// existence. The caller is expected to filter by existence. - /// - private static IEnumerable GetCandidateDirectories() - { - if (global::MiniSoftware.Compat.IsWindows()) - { - string systemRoot = Environment.GetEnvironmentVariable("SYSTEMROOT"); - if (string.IsNullOrWhiteSpace(systemRoot)) - systemRoot = @"C:\Windows"; - - yield return Path.Combine(systemRoot, "Fonts"); - - string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - if (!string.IsNullOrEmpty(appData)) - yield return Path.Combine(appData, "Microsoft", "Windows", "Fonts"); - - string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - if (!string.IsNullOrEmpty(localAppData)) - yield return Path.Combine(localAppData, "Microsoft", "Windows", "Fonts"); - } - else if (global::MiniSoftware.Compat.IsLinux()) - { - string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - if (!string.IsNullOrEmpty(home)) - { - yield return Path.Combine(home, ".fonts"); - yield return Path.Combine(home, ".local", "share", "fonts"); - } - - yield return "/usr/local/share/fonts"; - yield return "/usr/share/fonts"; - } - else if (global::MiniSoftware.Compat.IsMacOS()) - { - string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - if (!string.IsNullOrEmpty(home)) - yield return Path.Combine(home, "Library", "Fonts"); - - yield return "/Library/Fonts"; - yield return "/System/Library/Fonts"; - yield return "/Network/Library/Fonts"; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextLayoutEngine.cs b/src/MiniPdf/Drawing/Text/TextLayoutEngine.cs deleted file mode 100644 index d97321c4..00000000 --- a/src/MiniPdf/Drawing/Text/TextLayoutEngine.cs +++ /dev/null @@ -1,658 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Lays out text into a sequence of objects within a - /// pixel-space rectangle, applying word-wrap, tab expansion, and alignment. - /// All input coordinates and returned positions are in pixels. - /// - internal static class TextLayoutEngine - { - internal const float DefaultCharWidthFactor = 0.5f; - - // ── Single-run layout (preserved for backward compat) ──────────────── - - public static List Layout( - string text, - Font font, - RectangleF layoutRect, - StringFormat? sf, - float dpiX, - float dpiY) - { - if (string.IsNullOrEmpty(text)) - return new List(); - - sf = sf ?? StringFormat.GenericDefault; - - var metrics = font.FontFamily.GetMetricsData(font.Style); - float emPixels = FontSizeToPixels(font.Size, font.Unit, dpiY); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) - : 1f; - - double rawDesc = metrics.Descender <= 0 ? -metrics.Descender : metrics.Descender; - float ascender = (float)(metrics.Ascender * emScale); - float descender = (float)(rawDesc * emScale); - float lineGap = (float)(metrics.LineGap * emScale); - float lineHeight = ascender + descender + lineGap; - if (lineHeight < 1f) lineHeight = emPixels * 1.2f; - - IFont? fontFace = font.FontFamily.GetFontFace(font.Style); - float fallbackWidth = emPixels * DefaultCharWidthFactor; - - float firstTabOffset; - float[] tabStops = sf.GetTabStops(out firstTabOffset); - - bool noWrap = (sf.FormatFlags & StringFormatFlags.NoWrap) != 0; - float maxW = layoutRect.Width > 0f ? layoutRect.Width : float.MaxValue; - - var paragraphs = SplitOnHardBreaks(text); - var lines = new List(); - - foreach (string para in paragraphs) - { - IReadOnlyList segments = noWrap - ? (IReadOnlyList)new[] { para } - : WordWrap(para, fontFace, emScale, fallbackWidth, maxW, - firstTabOffset, tabStops, emPixels); - - foreach (string seg in segments) - { - float w = MeasureLineWidth(seg, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - var line = new TextLine { Width = w, LineHeight = lineHeight }; - line.Runs.Add(new TextRun(seg, font, 0f, 0f, w)); - lines.Add(line); - } - } - - if (lines.Count == 0) - return lines; - - float totalH = lines.Count * lineHeight; - float startBaseline; - - switch (sf.LineAlignment) - { - case StringAlignment.Center: - startBaseline = layoutRect.Y + (layoutRect.Height - totalH) / 2f + ascender; - break; - case StringAlignment.Far: - startBaseline = layoutRect.Y + layoutRect.Height - totalH + ascender; - break; - default: - startBaseline = layoutRect.Y + ascender; - break; - } - - for (int i = 0; i < lines.Count; i++) - { - float bl = startBaseline + i * lineHeight; - lines[i].Baseline = bl; - foreach (var run in lines[i].Runs) - run.Baseline = bl; - } - - foreach (var line in lines) - { - float lineX; - switch (sf.Alignment) - { - case StringAlignment.Center: - lineX = layoutRect.X + (layoutRect.Width - line.Width) / 2f; - break; - case StringAlignment.Far: - lineX = layoutRect.X + layoutRect.Width - line.Width; - break; - default: - lineX = layoutRect.X; - break; - } - - float curX = lineX; - foreach (var run in line.Runs) - { - run.X = curX; - curX += run.Width; - } - } - - return lines; - } - - // ── Multi-run layout (rich text / bidi / fallback) ────────────────── - - public static List Layout( - List runs, - RectangleF layoutRect, - StringFormat? sf, - float dpiX, - float dpiY) - { - if (runs == null || runs.Count == 0) - return new List(); - - sf = sf ?? StringFormat.GenericDefault; - - var runData = new List(runs.Count); - foreach (var run in runs) - { - var metrics = run.Font.FontFamily.GetMetricsData(run.Font.Style); - float emPixels = FontSizeToPixels(run.Font.Size, run.Font.Unit, dpiY); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) - : 1f; - - double rawDesc = metrics.Descender <= 0 ? -metrics.Descender : metrics.Descender; - float ascent = (float)(metrics.Ascender * emScale); - float descent = (float)(rawDesc * emScale); - float lineGap = (float)(metrics.LineGap * emScale); - - runData.Add(new RunMetrics - { - Font = run.Font, - FontFace = run.Font.FontFamily.GetFontFace(run.Font.Style), - EmScale = emScale, - EmPixels = emPixels, - Ascent = ascent, - Descent = descent, - LineGap = lineGap, - FallbackWidth = emPixels * DefaultCharWidthFactor, - Brush = run.Brush, - BidiLevel = run.BidiLevel, - IsRTL = run.IsRTL, - }); - } - - float firstTabOffset; - float[] tabStops = sf.GetTabStops(out firstTabOffset); - bool noWrap = (sf.FormatFlags & StringFormatFlags.NoWrap) != 0; - float maxW = layoutRect.Width > 0f ? layoutRect.Width : float.MaxValue; - - var lines = new List(); - - var flatChars = new List<(int RunIdx, int CharIdx, char C, float Advance, bool IsBreak)>(); - for (int ri = 0; ri < runs.Count; ri++) - { - var rd = runData[ri]; - var runText = runs[ri].Text; - for (int ci = 0; ci < runText.Length; ci++) - { - char c = runText[ci]; - float adv = GetCharAdvance(c, 0f, rd.FontFace, rd.EmScale, - rd.FallbackWidth, firstTabOffset, tabStops, rd.EmPixels); - bool isBreak = c == '\r' || c == '\n'; - flatChars.Add((ri, ci, c, adv, isBreak)); - } - } - - var paragraphs = new List>(); - var curPara = new List<(int, int, char, float, bool)>(); - bool skipNextLF = false; - foreach (var fc in flatChars) - { - if (fc.IsBreak) - { - if (fc.C == '\r') { skipNextLF = true; } - else if (fc.C == '\n' && skipNextLF) { skipNextLF = false; continue; } - skipNextLF = fc.C == '\r'; - paragraphs.Add(curPara); - curPara = new List<(int, int, char, float, bool)>(); - } - else - { - curPara.Add(fc); - skipNextLF = false; - } - } - paragraphs.Add(curPara); - - foreach (var para in paragraphs) - { - if (para.Count == 0) - { - var rd0 = runData[0]; - lines.Add(new TextLine - { - Width = 0, - LineHeight = rd0.Ascent + rd0.Descent + rd0.LineGap, - Ascent = rd0.Ascent, - Descent = rd0.Descent - }); - continue; - } - - if (noWrap || maxW <= 0f) - { - AddLineFromFlat(para, runs, runData, firstTabOffset, tabStops, lines); - continue; - } - - int start = 0; - while (start < para.Count) - { - int end = FindLineEndMulti(para, start, maxW); - var lineChars = para.GetRange(start, end - start); - if (end < para.Count && para[end].Item3 == ' ') - end++; - AddLineFromFlat(lineChars, runs, runData, firstTabOffset, tabStops, lines); - start = end; - } - } - - if (lines.Count == 0) - return lines; - - foreach (var line in lines) - ApplyBidiL2(line); - - foreach (var line in lines) - { - float maxA = 0, maxD = 0, maxG = 0; - foreach (var run in line.Runs) - { - var rd = FindRunMetrics(runData, run.Font); - if (rd != null) - { - var r = rd.Value; - if (r.Ascent > maxA) maxA = r.Ascent; - if (r.Descent > maxD) maxD = r.Descent; - if (r.LineGap > maxG) maxG = r.LineGap; - } - } - line.Ascent = maxA; - line.Descent = maxD; - line.LineHeight = maxA + maxD + maxG; - if (line.LineHeight < 1f) line.LineHeight = 12f; - } - - float totalH = 0; - foreach (var line in lines) - totalH += line.LineHeight; - - float startBaselineY; - switch (sf.LineAlignment) - { - case StringAlignment.Center: - startBaselineY = layoutRect.Y + (layoutRect.Height - totalH) / 2f + lines[0].Ascent; - break; - case StringAlignment.Far: - startBaselineY = layoutRect.Y + layoutRect.Height - totalH + lines[0].Ascent; - break; - default: - startBaselineY = layoutRect.Y + lines[0].Ascent; - break; - } - - float curY = startBaselineY; - for (int i = 0; i < lines.Count; i++) - { - lines[i].Baseline = curY; - foreach (var run in lines[i].Runs) - run.Baseline = curY; - curY += lines[i].LineHeight; - } - - bool paragraphRTL = (sf.FormatFlags & StringFormatFlags.DirectionRightToLeft) != 0; - foreach (var line in lines) - { - float lineX; - if (paragraphRTL) - { - switch (sf.Alignment) - { - case StringAlignment.Center: - lineX = layoutRect.X + (layoutRect.Width - line.Width) / 2f; - break; - case StringAlignment.Far: - lineX = layoutRect.X; - break; - default: - lineX = layoutRect.X + layoutRect.Width - line.Width; - break; - } - } - else - { - switch (sf.Alignment) - { - case StringAlignment.Center: - lineX = layoutRect.X + (layoutRect.Width - line.Width) / 2f; - break; - case StringAlignment.Far: - lineX = layoutRect.X + layoutRect.Width - line.Width; - break; - default: - lineX = layoutRect.X; - break; - } - } - - float curX = lineX; - foreach (var run in line.Runs) - { - run.X = curX; - curX += run.Width; - } - } - - return lines; - } - - private struct RunMetrics - { - public Font Font; - public IFont? FontFace; - public float EmScale; - public float EmPixels; - public float Ascent; - public float Descent; - public float LineGap; - public float FallbackWidth; - public Brush? Brush; - public int BidiLevel; - public bool IsRTL; - } - - private static RunMetrics? FindRunMetrics(List runData, Font font) - { - foreach (var rd in runData) - { - if (ReferenceEquals(rd.Font, font)) - return rd; - } - return null; - } - - private static int FindLineEndMulti( - List<(int RunIdx, int CharIdx, char C, float Advance, bool IsBreak)> para, - int startIdx, - float maxWidth) - { - float x = 0f; - int lastSpace = startIdx; - - for (int i = startIdx; i < para.Count; i++) - { - var (_, _, c, adv, _) = para[i]; - x += adv; - - if (c == ' ') - lastSpace = i; - - if (x > maxWidth && i > startIdx) - return lastSpace > startIdx ? lastSpace + 1 : i; - } - - return para.Count; - } - - private static void AddLineFromFlat( - List<(int RunIdx, int CharIdx, char C, float Advance, bool IsBreak)> lineChars, - List runs, - List runData, - float firstTabOffset, - float[] tabStops, - List lines) - { - var line = new TextLine(); - float lineW = 0f; - - int i = 0; - while (i < lineChars.Count) - { - int runIdx = lineChars[i].RunIdx; - int segStart = i; - while (i < lineChars.Count && lineChars[i].RunIdx == runIdx) - i++; - int segEnd = i; - - var runText = runs[runIdx].Text; - int charStart = lineChars[segStart].CharIdx; - int charLen = lineChars[segEnd - 1].CharIdx - charStart + 1; - - var subText = runText.Substring(charStart, charLen); - var rd = runData[runIdx]; - - float segW = 0f; - foreach (char c in subText) - segW += GetCharAdvance(c, 0f, rd.FontFace, rd.EmScale, - rd.FallbackWidth, firstTabOffset, tabStops, rd.EmPixels); - - line.Runs.Add(new TextRun( - subText, runs[runIdx].Font, rd.Brush, rd.BidiLevel, rd.IsRTL, - 0f, 0f, segW)); - lineW += segW; - } - - line.Width = lineW; - lines.Add(line); - } - - private static void ApplyBidiL2(TextLine line) - { - if (line.Runs.Count <= 1) - return; - - int maxLevel = 0; - int minLevel = int.MaxValue; - foreach (var run in line.Runs) - { - if (run.BidiLevel > maxLevel) maxLevel = run.BidiLevel; - if (run.BidiLevel < minLevel) minLevel = run.BidiLevel; - } - - for (int level = maxLevel; level > minLevel; level--) - { - int start = -1; - for (int i = 0; i < line.Runs.Count; i++) - { - if (line.Runs[i].BidiLevel >= level) - { - if (start < 0) start = i; - } - else - { - if (start >= 0) - { - ReverseRange(line.Runs, start, i - 1); - start = -1; - } - } - } - if (start >= 0) - ReverseRange(line.Runs, start, line.Runs.Count - 1); - } - } - - private static void ReverseRange(List runs, int lo, int hi) - { - while (lo < hi) - { - var tmp = runs[lo]; - runs[lo] = runs[hi]; - runs[hi] = tmp; - lo++; - hi--; - } - } - - // ── Advance-width helper ───────────────────────────────────────────── - - internal static float GetCharAdvance( - char c, - float currentX, - IFont? fontFace, - float emScale, - float fallbackWidth, - float firstTabOffset, - float[] tabStops, - float emPixels) - { - if (c == '\t') - return AdvanceToNextTabStop(currentX, firstTabOffset, tabStops, emPixels) - currentX; - - if (fontFace != null) - { - var gid = fontFace.Encoding.DecodeToGid(c); - if (gid != null) - return (float)(fontFace.Metrics.GetGlyphWidth(gid) * emScale); - } - - return fallbackWidth; - } - - // ── Font-size conversion ───────────────────────────────────────────── - - internal static float FontSizeToPixels(float size, GraphicsUnit unit, float dpi) - { - switch (unit) - { - case GraphicsUnit.Pixel: return size; - case GraphicsUnit.Point: return size * dpi / 72f; - case GraphicsUnit.Inch: return size * dpi; - case GraphicsUnit.Document: return size * dpi / 300f; - case GraphicsUnit.Millimeter: return size * dpi / 25.4f; - default: return size; - } - } - - // ── Private helpers ────────────────────────────────────────────────── - - private static List SplitOnHardBreaks(string text) - { - var result = new List(); - int start = 0; - for (int i = 0; i < text.Length; i++) - { - if (text[i] == '\r') - { - result.Add(text.Substring(start, i - start)); - if (i + 1 < text.Length && text[i + 1] == '\n') i++; - start = i + 1; - } - else if (text[i] == '\n') - { - result.Add(text.Substring(start, i - start)); - start = i + 1; - } - } - result.Add(text.Substring(start)); - return result; - } - - private static List WordWrap( - string text, - IFont? fontFace, - float emScale, - float fallbackWidth, - float maxWidth, - float firstTabOffset, - float[] tabStops, - float emPixels) - { - var lines = new List(); - if (maxWidth <= 0f || string.IsNullOrEmpty(text)) - { - lines.Add(text ?? string.Empty); - return lines; - } - - int start = 0; - while (start < text.Length) - { - int end = FindLineEnd(text, start, fontFace, emScale, fallbackWidth, - maxWidth, firstTabOffset, tabStops, emPixels); - lines.Add(text.Substring(start, end - start)); - start = end; - if (start < text.Length && text[start] == ' ') - start++; - } - - if (lines.Count == 0) - lines.Add(string.Empty); - - return lines; - } - - private static int FindLineEnd( - string text, - int startIdx, - IFont? fontFace, - float emScale, - float fallbackWidth, - float maxWidth, - float firstTabOffset, - float[] tabStops, - float emPixels) - { - float x = 0f; - int lastSpace = startIdx; - - for (int i = startIdx; i < text.Length; i++) - { - char c = text[i]; - float adv = GetCharAdvance(c, x, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - x += adv; - - if (c == ' ') lastSpace = i; - - if (x > maxWidth && i > startIdx) - return lastSpace > startIdx ? lastSpace : i; - } - - return text.Length; - } - - private static float MeasureLineWidth( - string text, - IFont? fontFace, - float emScale, - float fallbackWidth, - float firstTabOffset, - float[] tabStops, - float emPixels) - { - float x = 0f; - foreach (char c in text) - x += GetCharAdvance(c, x, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - return x; - } - - private static float AdvanceToNextTabStop( - float x, - float firstTabOffset, - float[] tabStops, - float emPixels) - { - float defaultInterval = emPixels * 4f; - if (defaultInterval <= 0f) defaultInterval = 48f; - - if (tabStops == null || tabStops.Length == 0) - return (float)(Math.Floor(x / defaultInterval) + 1.0) * defaultInterval; - - float pos = firstTabOffset; - if (x < pos) return pos; - - for (int i = 0; i < tabStops.Length; i++) - { - pos += tabStops[i]; - if (x < pos) return pos; - } - - float lastInterval = tabStops[tabStops.Length - 1]; - if (lastInterval <= 0f) lastInterval = defaultInterval; - float over = x - pos; - return pos + ((float)Math.Floor(over / lastInterval) + 1f) * lastInterval; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextLine.cs b/src/MiniPdf/Drawing/Text/TextLine.cs deleted file mode 100644 index 31b169de..00000000 --- a/src/MiniPdf/Drawing/Text/TextLine.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// One visual line of text made up of one or more objects. - /// - internal sealed class TextLine - { - public List Runs { get; } = new List(); - - public float Baseline { get; set; } - public float Width { get; set; } - public float LineHeight { get; set; } - - /// Maximum ascent across all runs (for mixed-size lines). - public float Ascent { get; set; } - - /// Maximum descent across all runs (for mixed-size lines). - public float Descent { get; set; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextOnPathLayout.cs b/src/MiniPdf/Drawing/Text/TextOnPathLayout.cs deleted file mode 100644 index 8d7ec551..00000000 --- a/src/MiniPdf/Drawing/Text/TextOnPathLayout.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Font.Core; -using MiniSoftware.Drawing.Font.Rendering; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// Core text-on-path layout engine. Renders a string along a baseline - /// , producing a fillable - /// whose glyphs are positioned and rotated to follow the baseline. - /// - internal static class TextOnPathLayout - { - /// - /// Build a containing the glyphs of - /// placed along . - /// - /// Text to place. Empty returns an empty path. - /// Font describing size, style, and family. - /// Baseline path in pixel coordinates. - /// String format (null → default). Only is used. - /// Placement options (null → defaults). - /// Horizontal DPI of the render target. - /// Vertical DPI of the render target. - public static GraphicsPath BuildPath( - string text, - Font font, - GraphicsPath baseline, - StringFormat? sf, - TextOnPathOptions? options, - float dpiX, - float dpiY) - { - var result = new GraphicsPath(); - if (string.IsNullOrEmpty(text)) return result; - if (baseline == null) throw new ArgumentNullException(nameof(baseline)); - if (font == null) throw new ArgumentNullException(nameof(font)); - if (baseline.PointCount == 0) return result; - - sf = sf ?? StringFormat.GenericDefault; - options = options ?? new TextOnPathOptions(); - - // ── 1. Font metrics in pixels ───────────────────────────────────── - var metrics = font.FontFamily.GetMetricsData(font.Style); - float emPixels = TextLayoutEngine.FontSizeToPixels(font.Size, font.Unit, dpiY); - float emScale = metrics.UnitsPerEm > 0 - ? (float)(emPixels / metrics.UnitsPerEm) - : 1f; - - IFont? fontFace = font.FontFamily.GetFontFace(font.Style); - if (fontFace == null) return result; // no outlines available - - // ── 2. Arc-length parameterize the baseline ─────────────────────── - var arc = PathArcLength.Build(baseline); - if (arc.TotalLength <= 0f) return result; - - // ── 3. Measure total text advance width ─────────────────────────── - float firstTabOffset; - float[] tabStops = sf.GetTabStops(out firstTabOffset); - float fallbackWidth = emPixels * TextLayoutEngine.DefaultCharWidthFactor; - - float textWidth = 0f; - foreach (char c in text) - { - textWidth += TextLayoutEngine.GetCharAdvance( - c, textWidth, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - } - - // ── 4. Compute start distance from alignment + StartOffset ──────── - float usableLength = arc.TotalLength - options.StartOffset; - StringAlignment alignment = options.Alignment ?? sf.Alignment; - float start; - switch (alignment) - { - case StringAlignment.Center: - start = options.StartOffset + Math.Max(0f, (usableLength - textWidth) / 2f); - break; - case StringAlignment.Far: - start = options.StartOffset + Math.Max(0f, usableLength - textWidth); - break; - default: // Near - start = options.StartOffset; - break; - } - if (start < 0f) start = 0f; - - // ── 5. Render glyphs ────────────────────────────────────────────── - var renderer = new GlyphOutlineRenderer(fontFace); - var rasterizer = new GlyphRasterizer(); - using var m = new Matrix(); - float currentDist = start; - - foreach (char c in text) - { - // Tab / CR / LF: advance width only, no glyph. - if (c == '\t' || c == '\r' || c == '\n') - { - currentDist += TextLayoutEngine.GetCharAdvance( - c, currentDist - start, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - continue; - } - - float adv = TextLayoutEngine.GetCharAdvance( - c, currentDist - start, fontFace, emScale, fallbackWidth, - firstTabOffset, tabStops, emPixels); - - // Overflow check. - if (currentDist > arc.TotalLength && options.Overflow == TextOnPathOverflow.Stop) - break; - - var gid = fontFace.Encoding.DecodeToGid(c); - if (gid != null) - { - bool ok = arc.GetPointAt(currentDist, out PointF pos, out float angle); - if (ok) - { - // Perpendicular offset: "above" = (sin, -cos) * offset. - float rad = angle * (float)(Math.PI / 180.0); - float perpX = (float)Math.Sin(rad) * options.PerpendicularOffset; - float perpY = -(float)Math.Cos(rad) * options.PerpendicularOffset; - - // Render glyph at local origin (0,0), baseline on X axis. - using var glyphPath = rasterizer.RenderGlyph( - renderer, gid, emScale, 0f, 0f); - if (glyphPath.PointCount > 0) - { - // Matrix = R * T (rotate around glyph origin, then translate). - m.Reset(); - m.Translate(pos.X + perpX, pos.Y + perpY, MatrixOrder.Append); - m.Rotate(angle, MatrixOrder.Prepend); - glyphPath.Transform(m); - result.AddPath(glyphPath, false); - } - } - } - - currentDist += adv; - } - - return result; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextOnPathOptions.cs b/src/MiniPdf/Drawing/Text/TextOnPathOptions.cs deleted file mode 100644 index 5b922ca0..00000000 --- a/src/MiniPdf/Drawing/Text/TextOnPathOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Options controlling text placement along a baseline path for - /// - /// and - /// . - /// - public sealed class TextOnPathOptions - { - /// - /// Distance along the path (in page units for - /// DrawStringOnPath, pixels for AddStringOnPath) at - /// which to start placing the first glyph's pen position. Default 0. - /// - public float StartOffset { get; set; } - - /// - /// Perpendicular offset of each glyph's baseline from the path. - /// Positive values place glyphs "above" the path (toward smaller Y - /// for a rightward-traveling path). In page units for - /// DrawStringOnPath, pixels for AddStringOnPath. - /// Default 0 (glyphs sit on the path). - /// - public float PerpendicularOffset { get; set; } - - /// - /// Controls alignment of the text block along the path, overriding - /// . When non-null, the text is - /// aligned within the usable path length (total length minus - /// ). Default null (use StringFormat.Alignment). - /// - public StringAlignment? Alignment { get; set; } - - /// - /// Behavior when the text is longer than the available path length. - /// Default (place glyphs until - /// the path ends, then stop). - /// - public TextOnPathOverflow Overflow { get; set; } = TextOnPathOverflow.Stop; - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextOnPathOverflow.cs b/src/MiniPdf/Drawing/Text/TextOnPathOverflow.cs deleted file mode 100644 index 389a3e6f..00000000 --- a/src/MiniPdf/Drawing/Text/TextOnPathOverflow.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Controls how text longer than the available path length is handled - /// by text-on-path layout. - /// - public enum TextOnPathOverflow - { - /// - /// Place glyphs until the path runs out, then stop. Remaining - /// characters are not rendered. - /// - Stop = 0, - - /// - /// Place glyphs until the path runs out, then clip. Identical - /// observable behavior to in the first cut - /// (reserved for future wrap-to-next-subpath behavior). - /// - Clip = 1, - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Text/TextRenderingHint.cs b/src/MiniPdf/Drawing/Text/TextRenderingHint.cs deleted file mode 100644 index e38bfecc..00000000 --- a/src/MiniPdf/Drawing/Text/TextRenderingHint.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace MiniSoftware.Drawing.Text -{ - /// - /// Specifies the text rendering hint for text quality. - /// - public enum TextRenderingHint - { - /// - /// Use the system default text rendering hint. - /// - SystemDefault = 0, - - /// - /// Use single bit per pixel with grid fit. - /// - SingleBitPerPixelGridFit = 1, - - /// - /// Use single bit per pixel. - /// - SingleBitPerPixel = 2, - - /// - /// Use anti-aliasing with grid fit. - /// - AntiAliasGridFit = 3, - - /// - /// Use anti-aliasing. - /// - AntiAlias = 4, - - /// - /// Use ClearType font rendering. - /// - ClearTypeGridFit = 5 - } -} diff --git a/src/MiniPdf/Drawing/Text/TextRun.cs b/src/MiniPdf/Drawing/Text/TextRun.cs deleted file mode 100644 index 602e2fcf..00000000 --- a/src/MiniPdf/Drawing/Text/TextRun.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MiniSoftware.Drawing.Brushes; - -namespace MiniSoftware.Drawing.Text -{ - /// - /// A positioned span of text within a . - /// - internal sealed class TextRun - { - internal TextRun(string text, Font font, float x, float baseline, float width) - : this(text, font, null, 0, false, x, baseline, width) - { - } - - internal TextRun( - string text, - Font font, - Brush? brush, - int bidiLevel, - bool isRTL, - float x, - float baseline, - float width) - { - Text = text; - Font = font; - Brush = brush; - BidiLevel = bidiLevel; - IsRTL = isRTL; - X = x; - Baseline = baseline; - Width = width; - } - - public string Text { get; } - public Font Font { get; } - public Brush? Brush { get; } - public int BidiLevel { get; } - public bool IsRTL { get; } - public float X { get; set; } - public float Baseline { get; set; } - public float Width { get; set; } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/ClearCommand.cs b/src/MiniPdf/Drawing/Vector/Commands/ClearCommand.cs deleted file mode 100644 index 80011f16..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/ClearCommand.cs +++ /dev/null @@ -1,32 +0,0 @@ -using MiniSoftware.Drawing.Colors; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Clears the entire drawing surface with the specified color. - /// - public sealed class ClearCommand : DrawingCommand - { - /// - /// Gets the color to clear with. - /// - public Color Color { get; } - - /// - /// Initializes a new . - /// - /// The color to clear with. - public ClearCommand(Color color) - { - Color = color; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.Clear(Color); - - /// - public override DrawingCommand Clone() - => new ClearCommand(Color); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/ClipCommands.cs b/src/MiniPdf/Drawing/Vector/Commands/ClipCommands.cs deleted file mode 100644 index 6228112d..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/ClipCommands.cs +++ /dev/null @@ -1,86 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Sets the clipping region to the specified region. The region captures - /// the resulting clip state; replay uses . - /// - public sealed class SetClipCommand : DrawingCommand - { - /// - /// Gets the clip region. - /// - public Region Clip { get; } - - /// - /// Gets the combine mode (always Replace for recorded resulting clips). - /// - public CombineMode Mode { get; } - - /// - /// Initializes a new , cloning the region. - /// - public SetClipCommand(Region clip, CombineMode mode) - { - Clip = clip.Clone(); - Mode = mode; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.SetClip(Clip, Mode); - - /// - public override DrawingCommand Clone() - => new SetClipCommand(Clip, Mode); - } - - /// - /// Resets the clipping region to the entire drawing surface. - /// - public sealed class ResetClipCommand : DrawingCommand - { - /// - internal override void Replay(IDrawingContext ctx) - => ctx.ResetClip(); - - /// - public override DrawingCommand Clone() - => new ResetClipCommand(); - } - - /// - /// Translates the clipping region by the specified amount. - /// - public sealed class TranslateClipCommand : DrawingCommand - { - /// - /// Gets the horizontal translation. - /// - public float Dx { get; } - - /// - /// Gets the vertical translation. - /// - public float Dy { get; } - - /// - /// Initializes a new . - /// - public TranslateClipCommand(float dx, float dy) - { - Dx = dx; - Dy = dy; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.TranslateClip(Dx, Dy); - - /// - public override DrawingCommand Clone() - => new TranslateClipCommand(Dx, Dy); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/ImageCommand.cs b/src/MiniPdf/Drawing/Vector/Commands/ImageCommand.cs deleted file mode 100644 index 7a748f2a..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/ImageCommand.cs +++ /dev/null @@ -1,111 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Draws an image scaled to fit a destination rectangle. - /// - public sealed class DrawImageCommand : DrawingCommand - { - /// - /// Gets the image to draw. - /// - public Image Image { get; } - - /// - /// Gets the destination rectangle. - /// - public RectangleF DestRect { get; } - - /// - /// Gets the source rectangle. - /// - public RectangleF SrcRect { get; } - - /// - /// Gets the source unit. - /// - public GraphicsUnit SrcUnit { get; } - - /// - /// Gets the image attributes, or null. - /// - public ImageAttributes? Attr { get; } - - /// - /// Initializes a new , cloning the image and attributes. - /// - public DrawImageCommand(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - Image = image.Clone(); - DestRect = destRect; - SrcRect = srcRect; - SrcUnit = srcUnit; - Attr = attr?.Clone(); - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.DrawImage(Image, DestRect, SrcRect, SrcUnit, Attr); - - /// - public override DrawingCommand Clone() - => new DrawImageCommand(Image, DestRect, SrcRect, SrcUnit, Attr); - } - - /// - /// Draws an image transformed to fit a parallelogram defined by destination points. - /// - public sealed class DrawImageAffineCommand : DrawingCommand - { - /// - /// Gets the image to draw. - /// - public Image Image { get; } - - /// - /// Gets the destination points defining a parallelogram. - /// - public PointF[] DestPoints { get; } - - /// - /// Gets the source rectangle. - /// - public RectangleF SrcRect { get; } - - /// - /// Gets the source unit. - /// - public GraphicsUnit SrcUnit { get; } - - /// - /// Gets the image attributes, or null. - /// - public ImageAttributes? Attr { get; } - - /// - /// Initializes a new , cloning the image and attributes. - /// - public DrawImageAffineCommand(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - Image = image.Clone(); - DestPoints = (PointF[])destPoints.Clone(); - SrcRect = srcRect; - SrcUnit = srcUnit; - Attr = attr?.Clone(); - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.DrawImage(Image, DestPoints, SrcRect, SrcUnit, Attr); - - /// - public override DrawingCommand Clone() - => new DrawImageAffineCommand(Image, DestPoints, SrcRect, SrcUnit, Attr); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/PathCommands.cs b/src/MiniPdf/Drawing/Vector/Commands/PathCommands.cs deleted file mode 100644 index bc3b3daf..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/PathCommands.cs +++ /dev/null @@ -1,83 +0,0 @@ -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Pens; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Draws (strokes) a graphics path with the specified pen. - /// - public sealed class DrawPathCommand : DrawingCommand - { - /// - /// Gets the pen used to stroke the path. - /// - public Pen Pen { get; } - - /// - /// Gets the path to draw. - /// - public GraphicsPath Path { get; } - - /// - /// Initializes a new , cloning the pen and path. - /// - /// The pen to stroke with. - /// The path to draw. - public DrawPathCommand(Pen pen, GraphicsPath path) - { - Pen = pen.Clone(); - Path = path.Clone(); - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.DrawPath(Pen, Path); - - /// - public override DrawingCommand Clone() - => new DrawPathCommand(Pen, Path); - } - - /// - /// Fills the interior of a graphics path with the specified brush. - /// - public sealed class FillPathCommand : DrawingCommand - { - /// - /// Gets the brush used to fill the path. - /// - public Brush Brush { get; } - - /// - /// Gets the path to fill. - /// - public GraphicsPath Path { get; } - - /// - /// Gets the fill mode. - /// - public FillMode FillMode { get; } - - /// - /// Initializes a new , cloning the brush and path. - /// - /// The brush to fill with. - /// The path to fill. - /// The fill mode. - public FillPathCommand(Brush brush, GraphicsPath path, FillMode fillMode) - { - Brush = brush.Clone(); - Path = path.Clone(); - FillMode = fillMode; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.FillPath(Brush, Path, FillMode); - - /// - public override DrawingCommand Clone() - => new FillPathCommand(Brush, Path, FillMode); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/StateCommands.cs b/src/MiniPdf/Drawing/Vector/Commands/StateCommands.cs deleted file mode 100644 index 42125ae5..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/StateCommands.cs +++ /dev/null @@ -1,183 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Rendering; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Sets a rendering hint property (SmoothingMode, InterpolationMode, etc.). - /// The value is boxed and dispatched by type on replay. - /// - public sealed class SetHintCommand : DrawingCommand - { - /// - /// Gets the hint value. - /// - public object Value { get; } - - /// - /// Initializes a new . - /// - /// The hint value (a rendering-hint enum). - public SetHintCommand(object value) - { - Value = value; - } - - /// - internal override void Replay(IDrawingContext ctx) - { - switch (Value) - { - case SmoothingMode v: ctx.SmoothingMode = v; break; - case InterpolationMode v: ctx.InterpolationMode = v; break; - case CompositingMode v: ctx.CompositingMode = v; break; - case CompositingQuality v: ctx.CompositingQuality = v; break; - case PixelOffsetMode v: ctx.PixelOffsetMode = v; break; - case Text.TextRenderingHint v: ctx.TextRenderingHint = v; break; - case GraphicsUnit v: ctx.PageUnit = v; break; - case float v: ctx.PageScale = v; break; - case Point v: ctx.RenderingOrigin = v; break; - } - } - - /// - public override DrawingCommand Clone() - => new SetHintCommand(Value); - } - - /// - /// Sets the page unit. - /// - public sealed class SetPageUnitCommand : DrawingCommand - { - /// - /// Gets the page unit. - /// - public GraphicsUnit PageUnit { get; } - - /// - /// Initializes a new . - /// - public SetPageUnitCommand(GraphicsUnit pageUnit) - { - PageUnit = pageUnit; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.PageUnit = PageUnit; - - /// - public override DrawingCommand Clone() - => new SetPageUnitCommand(PageUnit); - } - - /// - /// Sets the page scale. - /// - public sealed class SetPageScaleCommand : DrawingCommand - { - /// - /// Gets the page scale. - /// - public float PageScale { get; } - - /// - /// Initializes a new . - /// - public SetPageScaleCommand(float pageScale) - { - PageScale = pageScale; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.PageScale = PageScale; - - /// - public override DrawingCommand Clone() - => new SetPageScaleCommand(PageScale); - } - - /// - /// Sets the rendering origin. - /// - public sealed class SetRenderingOriginCommand : DrawingCommand - { - /// - /// Gets the rendering origin. - /// - public Point Origin { get; } - - /// - /// Initializes a new . - /// - public SetRenderingOriginCommand(Point origin) - { - Origin = origin; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.RenderingOrigin = Origin; - - /// - public override DrawingCommand Clone() - => new SetRenderingOriginCommand(Origin); - } - - /// - /// Saves the current graphics state. The token - /// is produced by the target at replay time and stored in - /// so the paired - /// can use it. This supports sequential multi-replay. - /// - public sealed class SaveStateCommand : DrawingCommand - { - /// - /// Gets or sets the state token produced during the most recent replay. - /// - internal GraphicsState? LastToken { get; set; } - - /// - internal override void Replay(IDrawingContext ctx) - => LastToken = ctx.Save(); - - /// - public override DrawingCommand Clone() - => new SaveStateCommand(); - } - - /// - /// Restores the graphics state to the state saved by the paired - /// . - /// - public sealed class RestoreStateCommand : DrawingCommand - { - private readonly SaveStateCommand _save; - - /// - /// Gets the save command this restore pairs with. - /// - public SaveStateCommand Save => _save; - - /// - /// Initializes a new . - /// - /// The paired save command. - public RestoreStateCommand(SaveStateCommand save) - { - _save = save; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.Restore(_save.LastToken!); - - /// - public override DrawingCommand Clone() - => new RestoreStateCommand(_save); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/TextCommand.cs b/src/MiniPdf/Drawing/Vector/Commands/TextCommand.cs deleted file mode 100644 index eefadf09..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/TextCommand.cs +++ /dev/null @@ -1,58 +0,0 @@ -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Draws a string with the specified font, brush, layout rectangle, and format. - /// - public sealed class DrawStringCommand : DrawingCommand - { - /// - /// Gets the text to draw. - /// - public string Text { get; } - - /// - /// Gets the font. - /// - public Text.Font Font { get; } - - /// - /// Gets the brush. - /// - public Brush Brush { get; } - - /// - /// Gets the layout rectangle. - /// - public RectangleF LayoutRect { get; } - - /// - /// Gets the string format, or null. - /// - public StringFormat? Format { get; } - - /// - /// Initializes a new , cloning the font, brush, and format. - /// - public DrawStringCommand(string text, Text.Font font, Brush brush, - RectangleF layoutRect, StringFormat? format) - { - Text = text; - Font = font.Clone(); - Brush = brush.Clone(); - LayoutRect = layoutRect; - Format = format?.Clone(); - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.DrawString(Text, Font, Brush, LayoutRect, Format); - - /// - public override DrawingCommand Clone() - => new DrawStringCommand(Text, Font, Brush, LayoutRect, Format); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Commands/TransformCommands.cs b/src/MiniPdf/Drawing/Vector/Commands/TransformCommands.cs deleted file mode 100644 index a657ac28..00000000 --- a/src/MiniPdf/Drawing/Vector/Commands/TransformCommands.cs +++ /dev/null @@ -1,189 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Vector.Commands -{ - /// - /// Sets the world transform to the specified matrix. - /// - public sealed class SetTransformCommand : DrawingCommand - { - /// - /// Gets the transform matrix. - /// - public Matrix Transform { get; } - - /// - /// Initializes a new , cloning the matrix. - /// - public SetTransformCommand(Matrix transform) - { - Transform = transform.Clone(); - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.Transform = Transform; - - /// - public override DrawingCommand Clone() - => new SetTransformCommand(Transform); - } - - /// - /// Resets the world transform to the identity matrix. - /// - public sealed class ResetTransformCommand : DrawingCommand - { - /// - internal override void Replay(IDrawingContext ctx) - => ctx.ResetTransform(); - - /// - public override DrawingCommand Clone() - => new ResetTransformCommand(); - } - - /// - /// Multiplies the world transform by the specified matrix. - /// - public sealed class MultiplyTransformCommand : DrawingCommand - { - /// - /// Gets the matrix to multiply by. - /// - public Matrix Matrix { get; } - - /// - /// Gets the multiplication order. - /// - public MatrixOrder Order { get; } - - /// - /// Initializes a new , cloning the matrix. - /// - public MultiplyTransformCommand(Matrix matrix, MatrixOrder order) - { - Matrix = matrix.Clone(); - Order = order; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.MultiplyTransform(Matrix, Order); - - /// - public override DrawingCommand Clone() - => new MultiplyTransformCommand(Matrix, Order); - } - - /// - /// Rotates the world transform by the specified angle. - /// - public sealed class RotateTransformCommand : DrawingCommand - { - /// - /// Gets the rotation angle in degrees. - /// - public float Angle { get; } - - /// - /// Gets the multiplication order. - /// - public MatrixOrder Order { get; } - - /// - /// Initializes a new . - /// - public RotateTransformCommand(float angle, MatrixOrder order) - { - Angle = angle; - Order = order; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.RotateTransform(Angle, Order); - - /// - public override DrawingCommand Clone() - => new RotateTransformCommand(Angle, Order); - } - - /// - /// Scales the world transform by the specified factors. - /// - public sealed class ScaleTransformCommand : DrawingCommand - { - /// - /// Gets the horizontal scale factor. - /// - public float Sx { get; } - - /// - /// Gets the vertical scale factor. - /// - public float Sy { get; } - - /// - /// Gets the multiplication order. - /// - public MatrixOrder Order { get; } - - /// - /// Initializes a new . - /// - public ScaleTransformCommand(float sx, float sy, MatrixOrder order) - { - Sx = sx; - Sy = sy; - Order = order; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.ScaleTransform(Sx, Sy, Order); - - /// - public override DrawingCommand Clone() - => new ScaleTransformCommand(Sx, Sy, Order); - } - - /// - /// Translates the world transform by the specified offsets. - /// - public sealed class TranslateTransformCommand : DrawingCommand - { - /// - /// Gets the horizontal translation. - /// - public float Dx { get; } - - /// - /// Gets the vertical translation. - /// - public float Dy { get; } - - /// - /// Gets the multiplication order. - /// - public MatrixOrder Order { get; } - - /// - /// Initializes a new . - /// - public TranslateTransformCommand(float dx, float dy, MatrixOrder order) - { - Dx = dx; - Dy = dy; - Order = order; - } - - /// - internal override void Replay(IDrawingContext ctx) - => ctx.TranslateTransform(Dx, Dy, Order); - - /// - public override DrawingCommand Clone() - => new TranslateTransformCommand(Dx, Dy, Order); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/DrawingCommand.cs b/src/MiniPdf/Drawing/Vector/DrawingCommand.cs deleted file mode 100644 index 00f6c71f..00000000 --- a/src/MiniPdf/Drawing/Vector/DrawingCommand.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace MiniSoftware.Drawing.Vector -{ - /// - /// Base class for one recorded drawing operation. Each subclass carries - /// immutable, cloned state and a that re-issues the - /// operation onto any . - /// - public abstract class DrawingCommand - { -/// - /// Replays this command onto the specified drawing context. - /// - /// The target drawing context. - internal abstract void Replay(IDrawingContext ctx); - - /// - /// Creates a deep copy of this command. - /// - /// A new with the same state. - public abstract DrawingCommand Clone(); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Emf/EmfDrawingContext.cs b/src/MiniPdf/Drawing/Vector/Emf/EmfDrawingContext.cs deleted file mode 100644 index c6ee52ae..00000000 --- a/src/MiniPdf/Drawing/Vector/Emf/EmfDrawingContext.cs +++ /dev/null @@ -1,414 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Metafile; -using MiniSoftware.Drawing.Metafile.Emf.Records; -using MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; -using MiniPdfFont = MiniSoftware.Drawing.Text.Font; -using DRegion = MiniSoftware.Drawing.Drawing2D.Region; -using DMatrix = MiniSoftware.Drawing.Drawing2D.Matrix; -using DGraphicsPath = MiniSoftware.Drawing.Drawing2D.GraphicsPath; -using EmfRecord = MiniSoftware.Drawing.Metafile.Emf.Records.Record; - -namespace MiniSoftware.Drawing.Vector.Emf -{ - /// - /// An implementation that accumulates EMF - /// records into a . This is the VDM->EMF - /// bridge: replay a onto this context to produce - /// EMF output. Manages the EMF object table (pen/brush/font handles), - /// world transforms, clip regions, state stack, and path records. - /// - internal sealed class EmfDrawingContext : IDrawingContext - { - private readonly int _width; - private readonly int _height; - private readonly EmfRecordMapper _mapper = new EmfRecordMapper(); - private readonly List _allRecords = new List(); - - private DMatrix _transform = new DMatrix(); - private DRegion _clip = new DRegion(); - private SmoothingMode _smoothingMode = SmoothingMode.None; - private InterpolationMode _interpolationMode = InterpolationMode.NearestNeighbor; - private CompositingMode _compositingMode = CompositingMode.SourceOver; - private CompositingQuality _compositingQuality = CompositingQuality.Default; - private PixelOffsetMode _pixelOffsetMode = PixelOffsetMode.Default; - private TextRenderingHint _textRenderingHint = TextRenderingHint.SystemDefault; - private GraphicsUnit _pageUnit = GraphicsUnit.Pixel; - private float _pageScale = 1f; - private Point _renderingOrigin = new Point(0, 0); - - private readonly Stack _stateStack = new Stack(); - private bool _disposed; - - public EmfDrawingContext(int width, int height) - { - _width = width; - _height = height; - _clip.MakeInfinite(); - } - - public int Width => _width; - public int Height => _height; - public float DpiX => 96f; - public float DpiY => 96f; - - public DMatrix Transform - { - get => _transform; - set - { - _transform = value ?? new DMatrix(); - _mapper.SetTransform(_transform); - } - } - - public DRegion Clip - { - get => _clip; - set => _clip = value ?? new DRegion(); - } - - public SmoothingMode SmoothingMode { get => _smoothingMode; set => _smoothingMode = value; } - public InterpolationMode InterpolationMode { get => _interpolationMode; set => _interpolationMode = value; } - public CompositingMode CompositingMode { get => _compositingMode; set => _compositingMode = value; } - public CompositingQuality CompositingQuality { get => _compositingQuality; set => _compositingQuality = value; } - public PixelOffsetMode PixelOffsetMode { get => _pixelOffsetMode; set => _pixelOffsetMode = value; } - public TextRenderingHint TextRenderingHint { get => _textRenderingHint; set => _textRenderingHint = value; } - public GraphicsUnit PageUnit { get => _pageUnit; set => _pageUnit = value; } - public float PageScale { get => _pageScale; set => _pageScale = value; } - public Point RenderingOrigin { get => _renderingOrigin; set => _renderingOrigin = value; } - - public void ResetTransform() - { - _transform.Reset(); - _mapper.SetTransform(_transform); - } - - public void MultiplyTransform(DMatrix m, MatrixOrder order = MatrixOrder.Prepend) - { - _transform.Multiply(m, order); - _mapper.SetTransform(_transform); - } - - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - { - _transform.Rotate(angle, order); - _mapper.SetTransform(_transform); - } - - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - { - _transform.Scale(sx, sy, order); - _mapper.SetTransform(_transform); - } - - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - { - _transform.Translate(dx, dy, order); - _mapper.SetTransform(_transform); - } - - public void SetClip(RectangleF rect, CombineMode mode = CombineMode.Replace) - { - _clip = new DRegion(rect); - _mapper.IntersectClipRect(rect); - } - - public void SetClip(DGraphicsPath path, CombineMode mode = CombineMode.Replace) - { - _clip = new DRegion(path); - } - -public void SetClip(DRegion region, CombineMode mode = CombineMode.Replace) - { - _clip = region.Clone(); - var rect = region.GetBounds(); - if (rect.Width > 0 && rect.Height > 0 && !float.IsInfinity(rect.Width) && !float.IsInfinity(rect.Height)) - _mapper.IntersectClipRect(rect); - } - - public void IntersectClip(RectangleF rect) - { - _clip.Intersect(rect); - _mapper.IntersectClipRect(rect); - } - - public void IntersectClip(DRegion region) - { - _clip.Intersect(region); - } - - public void ExcludeClip(Rectangle rect) => _clip.Exclude(rect); - public void ExcludeClip(DRegion region) => _clip.Exclude(region); - - public void ResetClip() - { - _clip = new DRegion(); - _clip.MakeInfinite(); - } - - public void TranslateClip(float dx, float dy) => _clip.Translate(dx, dy); - - private readonly Dictionary _stateDepths = new Dictionary(); - private readonly Dictionary _containerDepths = new Dictionary(); - - public GraphicsState Save() - { - _stateStack.Push(CaptureState()); - _mapper.SaveDC(); - var token = new GraphicsState(_transform.Clone(), _clip.Clone(), _pageUnit, _pageScale, - _smoothingMode, _interpolationMode, _compositingMode, _compositingQuality, - _pixelOffsetMode, _textRenderingHint, _renderingOrigin); - _stateDepths[token] = _stateStack.Count; - return token; - } - - public void Restore(GraphicsState state) - { - if (state == null) return; - if (!_stateDepths.TryGetValue(state, out int depth)) return; - while (_stateStack.Count >= depth && _stateStack.Count > 0) - RestoreState(_stateStack.Pop()); - _mapper.RestoreDC(); - } - - public GraphicsContainer BeginContainer() - { - _stateStack.Push(CaptureState()); - _mapper.SaveDC(); - var gs = new GraphicsState(_transform.Clone(), _clip.Clone(), _pageUnit, _pageScale, - _smoothingMode, _interpolationMode, _compositingMode, _compositingQuality, - _pixelOffsetMode, _textRenderingHint, _renderingOrigin); - var token = new GraphicsContainer(gs); - _containerDepths[token] = _stateStack.Count; - return token; - } - - public GraphicsContainer BeginContainer(RectangleF dst, RectangleF src, GraphicsUnit unit) - => BeginContainer(); - - public void EndContainer(GraphicsContainer container) - { - if (container == null) return; - if (!_containerDepths.TryGetValue(container, out int depth)) return; - while (_stateStack.Count >= depth && _stateStack.Count > 0) - RestoreState(_stateStack.Pop()); - _mapper.RestoreDC(); - } - - public void Clear(Color color) - { - var rect = new RectangleF(0, 0, _width, _height); - var path = new DGraphicsPath(); - path.AddRectangle(rect); - var brush = new SolidBrush(color); - _mapper.SelectBrush(brush); - _mapper.BuildPath(path); - _mapper.FillPath(rect); - brush.Dispose(); - } - - public void DrawPath(Pen pen, DGraphicsPath path) - { - if (pen == null || path == null || path.PointCount == 0) return; - _mapper.SelectPen(pen); - var bounds = GetPathBounds(path); - _mapper.BuildPath(path); - _mapper.StrokePath(bounds); - } - - public void FillPath(Brush brush, DGraphicsPath path) - => FillPath(brush, path, path?.FillMode ?? FillMode.Alternate); - - public void FillPath(Brush brush, DGraphicsPath path, FillMode fillMode) - { - if (brush == null || path == null || path.PointCount == 0) return; - _mapper.SelectBrush(brush); - _mapper.SetPolyFillMode(fillMode); - var bounds = GetPathBounds(path); - _mapper.BuildPath(path); - _mapper.FillPath(bounds); - } - - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (image == null) return; - if (image is Bitmap bmp) - { - _mapper.StretchDIBits(destRect, bmp); - } - else - { - using var rasterized = image.Clone() as Bitmap; - if (rasterized != null) - _mapper.StretchDIBits(destRect, rasterized); - } - } - - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (image == null || destPoints == null || destPoints.Length < 3) return; - float minX = float.MaxValue, minY = float.MaxValue; - float maxX = float.MinValue, maxY = float.MinValue; - foreach (var p in destPoints) - { - if (p.X < minX) minX = p.X; - if (p.Y < minY) minY = p.Y; - if (p.X > maxX) maxX = p.X; - if (p.Y > maxY) maxY = p.Y; - } - var destRect = new RectangleF(minX, minY, maxX - minX, maxY - minY); - DrawImage(image, destRect, srcRect, srcUnit, attr); - } - - public void DrawString(string s, MiniPdfFont font, Brush brush, - RectangleF layoutRect, StringFormat? format) - { - if (string.IsNullOrEmpty(s) || font == null || brush == null) return; - var color = brush is SolidBrush sb ? sb.Color : Color.Black; - _mapper.ExtTextOutW(s, font, color, layoutRect); - } - - /// - /// Builds a complete from the accumulated - /// records, including EMR_HEADER and EMR_EOF. - /// - public MetafileDocument ToDocument() - { - var records = new List(); - var header = CreateHeader(); - records.Add(header); - foreach (var r in _mapper.Records) - records.Add(r); - records.Add(new EMR_EOF - { - NumberOfHandles = _mapper.HandleCount, - NumberOfRecords = (ushort)records.Count, - }); - header.HeaderObject.Records = (uint)records.Count; - header.HeaderObject.Bytes = 0; - var hdr = header.Header; - hdr.Size = 0; - header.Header = hdr; - return new MetafileDocument - { - Format = MetafileFormat.Emf, - EmfRecords = records, - }; - } - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - } - - private EMR_HEADER CreateHeader() - { - return new EMR_HEADER - { - HeaderObject = new Metafile.Emf.Objects.Header - { - Bounds = new Metafile.Wmf.Objects.RectL - { - Left = 0, Top = 0, Right = _width, Bottom = _height, - }, - Frame = new Metafile.Wmf.Objects.RectL - { - Left = 0, Top = 0, Right = _width * 100, Bottom = _height * 100, - }, - RecordSignature = 0x464D4520, - Version = 0x00010000, - Bytes = 0, - Records = 0, - Handles = _mapper.HandleCount, - nDescription = 0, - offDescription = 0, - nPalEntries = 0, - Device = new Metafile.Wmf.Objects.SizeL - { - cx = (uint)_width, cy = (uint)_height, - }, - Millimeters = new Metafile.Wmf.Objects.SizeL - { - cx = (uint)Math.Max(1, _width * 3), - cy = (uint)Math.Max(1, _height * 3), - }, - }, - }; - } - - private static RectangleF GetPathBounds(DGraphicsPath path) - { - var pts = path.PathPoints; - if (pts.Length == 0) return RectangleF.Empty; - float minX = float.MaxValue, minY = float.MaxValue; - float maxX = float.MinValue, maxY = float.MinValue; - foreach (var p in pts) - { - if (p.X < minX) minX = p.X; - if (p.Y < minY) minY = p.Y; - if (p.X > maxX) maxX = p.X; - if (p.Y > maxY) maxY = p.Y; - } - return new RectangleF(minX, minY, maxX - minX, maxY - minY); - } - - private StateFrame CaptureState() => new StateFrame - { - Transform = _transform.Clone(), - Clip = _clip.Clone(), - SmoothingMode = _smoothingMode, - InterpolationMode = _interpolationMode, - CompositingMode = _compositingMode, - CompositingQuality = _compositingQuality, - PixelOffsetMode = _pixelOffsetMode, - TextRenderingHint = _textRenderingHint, - PageUnit = _pageUnit, - PageScale = _pageScale, - RenderingOrigin = _renderingOrigin, - }; - - private void RestoreState(StateFrame frame) - { - _transform = frame.Transform; - _clip = frame.Clip; - _smoothingMode = frame.SmoothingMode; - _interpolationMode = frame.InterpolationMode; - _compositingMode = frame.CompositingMode; - _compositingQuality = frame.CompositingQuality; - _pixelOffsetMode = frame.PixelOffsetMode; - _textRenderingHint = frame.TextRenderingHint; - _pageUnit = frame.PageUnit; - _pageScale = frame.PageScale; - _renderingOrigin = frame.RenderingOrigin; - } - - private sealed class StateFrame - { - public DMatrix Transform = null!; - public DRegion Clip = null!; - public SmoothingMode SmoothingMode; - public InterpolationMode InterpolationMode; - public CompositingMode CompositingMode; - public CompositingQuality CompositingQuality; - public PixelOffsetMode PixelOffsetMode; - public TextRenderingHint TextRenderingHint; - public GraphicsUnit PageUnit; - public float PageScale; - public Point RenderingOrigin; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Emf/EmfRecordMapper.cs b/src/MiniPdf/Drawing/Vector/Emf/EmfRecordMapper.cs deleted file mode 100644 index 43660f35..00000000 --- a/src/MiniPdf/Drawing/Vector/Emf/EmfRecordMapper.cs +++ /dev/null @@ -1,355 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Metafile.Emf.Enumerations; -using MiniSoftware.Drawing.Metafile.Emf.Objects; -using MiniSoftware.Drawing.Metafile.Emf.Records; -using MiniSoftware.Drawing.Metafile.Emf.Records.DrawingRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.ObjectRecordTypes; -using MiniSoftware.Drawing.Metafile.Emf.Records.StateRecordTypes; -using MiniSoftware.Drawing.Metafile.Wmf.Enumerations; -using MiniSoftware.Drawing.Metafile.Wmf.Objects; -using MiniSoftware.Drawing.Pens; -using Pen = MiniSoftware.Drawing.Pens.Pen; -using Brush = MiniSoftware.Drawing.Brushes.Brush; -using Color = MiniSoftware.Drawing.Colors.Color; -using DashStyle = MiniSoftware.Drawing.Drawing2D.DashStyle; -using EmfRecord = MiniSoftware.Drawing.Metafile.Emf.Records.Record; -using WmfHatchStyle = MiniSoftware.Drawing.Metafile.Wmf.Enumerations.HatchStyle; - -namespace MiniSoftware.Drawing.Vector.Emf -{ - /// - /// Maps state to EMF records. Manages the EMF - /// object table (pen/brush/font handle allocation and selection), world - /// transforms, clip regions, state stack, and path-to-records conversion. - /// Used by . - /// - internal sealed class EmfRecordMapper - { - private readonly List _records = new List(); - private readonly Dictionary _objectTable = new Dictionary(); - private uint _nextHandle = 1; - private uint _currentPenHandle; - private uint _currentBrushHandle; - private uint _currentFontHandle; - - public IReadOnlyList Records => _records; - public ushort HandleCount => (ushort)_nextHandle; - - // ── Object table management ──────────────────────────────────────────── - - private uint GetOrCreatePen(Pen pen) - { - if (pen == null) return 0; - var key = (pen.Color, pen.Width); - if (_objectTable.TryGetValue(key, out uint handle)) - return handle; - - handle = _nextHandle++; - var penStyle = pen.DashStyle == DashStyle.Solid ? PenStyle.PS_SOLID : PenStyle.PS_DASH; - var createPen = new EMR_CREATEPEN - { - IhPen = handle, - Pen = new Metafile.Wmf.Objects.Pen - { - PenStyle = penStyle, - Width = new PointS { x = (int)Math.Max(1, pen.Width), y = 0 }, - ColorRef = new ColorRef { Red = pen.Color.R, Green = pen.Color.G, Blue = pen.Color.B, Reserved = 0 }, - }, - }; - _records.Add(createPen); - _objectTable[key] = handle; - return handle; - } - - private uint GetOrCreateBrush(Brushes.Brush brush) - { - if (brush == null) return 0; - Color color = brush is Brushes.SolidBrush sb ? sb.Color : Color.Black; - var key = ("brush", color); - if (_objectTable.TryGetValue(key, out uint handle)) - return handle; - - handle = _nextHandle++; - var createBrush = new EMR_CREATEBRUSHINDIRECT - { - IhBrush = handle, - LogBrush = new LogBrush - { - BrushStyle = BrushStyle.BS_SOLID, - ColorRef = new ColorRef { Red = color.R, Green = color.G, Blue = color.B, Reserved = 0 }, - BrushHatch = WmfHatchStyle.HS_HORIZONTAL, - }, - }; - _records.Add(createBrush); - _objectTable[key] = handle; - return handle; - } - - private uint GetOrCreateFont(Text.Font font) - { - if (font == null) return 0; - var key = ("font", font.Name, font.Size, font.Style); - if (_objectTable.TryGetValue(key, out uint handle)) - return handle; - - handle = _nextHandle++; - short weight = font.Bold ? (short)700 : (short)400; - var createFont = new EMR_EXTCREATEFONTINDIRECTW - { - IhFont = handle, - Font = new Metafile.Wmf.Objects.Font - { - Height = (short)Math.Round(font.Size), - Width = 0, - Escapement = 0, - Orientation = 0, - Weight = weight, - Italic = (byte)(font.Italic ? 1 : 0), - Underline = (byte)(font.Underline ? 1 : 0), - StrikeOut = (byte)(font.Strikeout ? 1 : 0), - }, - }; - createFont.Font.Facename = font.Name; - _records.Add(createFont); - _objectTable[key] = handle; - return handle; - } - - public void SelectPen(Pen pen) - { - uint handle = GetOrCreatePen(pen); - if (handle == 0 || handle == _currentPenHandle) return; - _currentPenHandle = handle; - _records.Add(new EMR_SELECTOBJECT { ObjectIndex = handle }); - } - - public void SelectBrush(Brushes.Brush brush) - { - uint handle = GetOrCreateBrush(brush); - if (handle == 0 || handle == _currentBrushHandle) return; - _currentBrushHandle = handle; - _records.Add(new EMR_SELECTOBJECT { ObjectIndex = handle }); - } - - public void SelectFont(Text.Font font) - { - uint handle = GetOrCreateFont(font); - if (handle == 0 || handle == _currentFontHandle) return; - _currentFontHandle = handle; - _records.Add(new EMR_SELECTOBJECT { ObjectIndex = handle }); - } - - // ── State records ───────────────────────────────────────────────────── - - public void SetTransform(Matrix matrix) - { - var e = matrix.Elements; - _records.Add(new EMR_SETWORLDTRANSFORM - { - M11 = e[0], M12 = e[1], - M21 = e[2], M22 = e[3], - Dx = e[4], Dy = e[5], - }); - } - - public void SaveDC() => _records.Add(new EMR_SAVEDC()); - - public void RestoreDC() => _records.Add(new EMR_RESTOREDC { SavedDC = -1 }); - - public void SetPolyFillMode(FillMode fillMode) - { - _records.Add(new EMR_SETPOLYFILLMODE - { - PolyFillMode = fillMode == FillMode.Alternate - ? PolyFillMode.ALTERNATE - : PolyFillMode.WINDING, - }); - } - - public void SetTextColor(Color color) - { - _records.Add(new EMR_SETTEXTCOLOR - { - Color = new ColorRef { Red = color.R, Green = color.G, Blue = color.B, Reserved = 0 }, - }); - } - - public void IntersectClipRect(RectangleF rect) - { - _records.Add(new EMR_INTERSECTCLIPRECT { Clip = ToRectL(rect) }); - } - - // ── Path records ────────────────────────────────────────────────────── - - public void BuildPath(GraphicsPath path) - { - _records.Add(new EMR_BEGINPATH()); - - var points = path.PathPoints; - var types = path.PathTypes; - - bool firstPoint = true; - for (int i = 0; i < points.Length; i++) - { - byte type = types[i]; - PathPointType ptType = (PathPointType)(type & (byte)PathPointType.PathTypeMask); - bool closeSubpath = (type & (byte)PathPointType.CloseSubpath) != 0; - - if (ptType == PathPointType.Start) - { - _records.Add(new EMR_MOVETOEX { Offset = ToPointL(points[i]) }); - firstPoint = false; - } - else if (ptType == PathPointType.Line) - { - _records.Add(new EMR_LINETO { Point = ToPointL(points[i]) }); - } - else if (ptType == PathPointType.Bezier) - { - var bezierPoints = new List(); - while (i < points.Length && - (PathPointType)(types[i] & (byte)PathPointType.PathTypeMask) == PathPointType.Bezier) - { - bezierPoints.Add(ToPointL(points[i])); - i++; - } - i--; - - if (bezierPoints.Count >= 3) - { - _records.Add(new EMR_POLYBEZIERTO - { - Bounds = new RectL(), - Count = (uint)bezierPoints.Count, - Points = bezierPoints.ToArray(), - }); - } - } - - if (closeSubpath) - _records.Add(new EMR_CLOSEFIGURE()); - } - - _records.Add(new EMR_ENDPATH()); - } - - public void StrokePath(RectangleF bounds) - => _records.Add(new EMR_STROKEPATH { Bounds = ToRectL(bounds) }); - - public void FillPath(RectangleF bounds) - => _records.Add(new EMR_FILLPATH { Bounds = ToRectL(bounds) }); - - public void StrokeAndFillPath(RectangleF bounds) - => _records.Add(new EMR_STROKEANDFILLPATH { Bounds = ToRectL(bounds) }); - - // ── Drawing records ─────────────────────────────────────────────────── - - public void StretchDIBits(RectangleF destRect, Bitmap bitmap) - { - var (bmi, bits) = BitmapToDib(bitmap); - _records.Add(new EMR_STRETCHDIBITS - { - Bounds = ToRectL(destRect), - XDest = (int)destRect.X, - YDest = (int)destRect.Y, - XSrc = 0, - YSrc = 0, - CxSrc = bitmap.Width, - CySrc = bitmap.Height, - OffBmiSrc = 0, - CbBmiSrc = (uint)bmi.Length, - OffBitsSrc = 0, - CbBitsSrc = (uint)bits.Length, - UsageSrc = DIBColors.DibRgbColors, - BitBltRasterOperation = TernaryRasterOperation.SRCCOPY, - CxDest = (int)destRect.Width, - CyDest = (int)destRect.Height, - BmiSrc = bmi, - BitsSrc = bits, - }); - } - - public void ExtTextOutW(string text, Text.Font font, Color color, RectangleF layoutRect) - { - SelectFont(font); - SetTextColor(color); - - var outputString = System.Text.Encoding.Unicode.GetBytes(text); - var emrText = new EmrText - { - Reference = new PointL { x = (int)layoutRect.X, y = (int)layoutRect.Y }, - Chars = (uint)text.Length, - offString = 0, - Options = ExtTextOutOptions.ETO_OPAQUE, - Rectangle = ToRectL(layoutRect), - offDx = 0, - OutputString = outputString, - }; - - _records.Add(new EMR_EXTTEXTOUTW - { - Bounds = ToRectL(layoutRect), - IGraphicsMode = GraphicsMode.GM_COMPATIBLE, - ExScale = 1f, - EyScale = 1f, - EmrText = emrText, - }); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static PointL ToPointL(PointF p) - => new PointL { x = (int)Math.Round(p.X), y = (int)Math.Round(p.Y) }; - - private static RectL ToRectL(RectangleF r) - => new RectL - { - Left = (int)Math.Round(r.Left), - Top = (int)Math.Round(r.Top), - Right = (int)Math.Round(r.Right), - Bottom = (int)Math.Round(r.Bottom), - }; - - private static (byte[] bmi, byte[] bits) BitmapToDib(Bitmap bitmap) - { - int width = bitmap.Width; - int height = bitmap.Height; - PixelFormat format = bitmap.PixelFormat; - int bpp = format == PixelFormat.Format24bppRgb ? 24 : 32; - - int stride = ((width * bpp + 31) / 32) * 4; - int headerSize = 40; - int pixelDataSize = stride * height; - - var bmi = new byte[headerSize]; - BitConverter.GetBytes((uint)headerSize).CopyTo(bmi, 0); - BitConverter.GetBytes(width).CopyTo(bmi, 4); - BitConverter.GetBytes(height).CopyTo(bmi, 8); - BitConverter.GetBytes((ushort)1).CopyTo(bmi, 12); - BitConverter.GetBytes((ushort)bpp).CopyTo(bmi, 14); - BitConverter.GetBytes((uint)0).CopyTo(bmi, 16); - BitConverter.GetBytes((uint)pixelDataSize).CopyTo(bmi, 20); - for (int i = 24; i < headerSize; i++) - bmi[i] = 0; - - var bits = new byte[pixelDataSize]; - int srcStride = Bitmap.CalcStride(width, format); - int copyStride = Math.Min(srcStride, stride); - - for (int y = 0; y < height; y++) - { - int srcOffset = y * srcStride; - int dstOffset = (height - 1 - y) * stride; - Buffer.BlockCopy(bitmap._pixels, srcOffset, bits, dstOffset, copyStride); - } - - return (bmi, bits); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Emf/WmfDrawingContext.cs b/src/MiniPdf/Drawing/Vector/Emf/WmfDrawingContext.cs deleted file mode 100644 index 0448039a..00000000 --- a/src/MiniPdf/Drawing/Vector/Emf/WmfDrawingContext.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; -using MiniPdfFont = MiniSoftware.Drawing.Text.Font; - -namespace MiniSoftware.Drawing.Vector.Emf -{ - /// - /// An implementation that accumulates WMF - /// records. WMF lacks world transforms and path records, so many operations - /// fall back to raster. EMF is the recommended vector interchange target; - /// this context is provided for completeness but is lower priority. - /// - /// - /// WMF output is implemented as a raster fallback: each drawing operation - /// is rasterized to a bitmap and emitted as a stretch-blit. This guarantees - /// valid WMF output but does not preserve vector data. For true vector - /// output, use . - /// - internal sealed class WmfDrawingContext : IDrawingContext - { - private readonly int _width; - private readonly int _height; - private readonly Bitmap _rasterBuffer; - private readonly Graphics _rasterGraphics; - private bool _disposed; - - public WmfDrawingContext(int width, int height) - { - _width = width; - _height = height; - _rasterBuffer = new Bitmap(width, height, PixelFormat.Format32bppArgb); - _rasterGraphics = Graphics.FromImage(_rasterBuffer); - _rasterGraphics.Clear(Color.Transparent); - } - - public int Width => _width; - public int Height => _height; - public float DpiX => 96f; - public float DpiY => 96f; - - public Matrix Transform - { - get => _rasterGraphics.Transform; - set => _rasterGraphics.Transform = value; - } - - public Region Clip - { - get => _rasterGraphics.Clip; - set => _rasterGraphics.Clip = value; - } - - public SmoothingMode SmoothingMode { get => _rasterGraphics.SmoothingMode; set => _rasterGraphics.SmoothingMode = value; } - public InterpolationMode InterpolationMode { get => _rasterGraphics.InterpolationMode; set => _rasterGraphics.InterpolationMode = value; } - public CompositingMode CompositingMode { get => _rasterGraphics.CompositingMode; set => _rasterGraphics.CompositingMode = value; } - public CompositingQuality CompositingQuality { get => _rasterGraphics.CompositingQuality; set => _rasterGraphics.CompositingQuality = value; } - public PixelOffsetMode PixelOffsetMode { get => _rasterGraphics.PixelOffsetMode; set => _rasterGraphics.PixelOffsetMode = value; } - public TextRenderingHint TextRenderingHint { get => _rasterGraphics.TextRenderingHint; set => _rasterGraphics.TextRenderingHint = value; } - public GraphicsUnit PageUnit { get => _rasterGraphics.PageUnit; set => _rasterGraphics.PageUnit = value; } - public float PageScale { get => _rasterGraphics.PageScale; set => _rasterGraphics.PageScale = value; } - public Point RenderingOrigin { get => _rasterGraphics.RenderingOrigin; set => _rasterGraphics.RenderingOrigin = value; } - - public void ResetTransform() => _rasterGraphics.ResetTransform(); - public void MultiplyTransform(Matrix m, MatrixOrder order = MatrixOrder.Prepend) => _rasterGraphics.MultiplyTransform(m, order); - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) => _rasterGraphics.RotateTransform(angle, order); - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) => _rasterGraphics.ScaleTransform(sx, sy, order); - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) => _rasterGraphics.TranslateTransform(dx, dy, order); - - public void SetClip(RectangleF rect, CombineMode mode = CombineMode.Replace) => _rasterGraphics.SetClip(rect, mode); - public void SetClip(GraphicsPath path, CombineMode mode = CombineMode.Replace) => _rasterGraphics.SetClip(path, mode); - public void SetClip(Region region, CombineMode mode = CombineMode.Replace) => _rasterGraphics.SetClip(region, mode); - public void IntersectClip(RectangleF rect) => _rasterGraphics.IntersectClip(rect); - public void IntersectClip(Region region) => _rasterGraphics.IntersectClip(region); - public void ExcludeClip(Rectangle rect) => _rasterGraphics.ExcludeClip(rect); - public void ExcludeClip(Region region) => _rasterGraphics.ExcludeClip(region); - public void ResetClip() => _rasterGraphics.ResetClip(); - public void TranslateClip(float dx, float dy) => _rasterGraphics.TranslateClip(dx, dy); - - public GraphicsState Save() => _rasterGraphics.Save(); - public void Restore(GraphicsState state) => _rasterGraphics.Restore(state); - public GraphicsContainer BeginContainer() => _rasterGraphics.BeginContainer(); - public GraphicsContainer BeginContainer(RectangleF dst, RectangleF src, GraphicsUnit unit) => _rasterGraphics.BeginContainer(dst, src, unit); - public void EndContainer(GraphicsContainer container) => _rasterGraphics.EndContainer(container); - - public void Clear(Color color) => _rasterGraphics.Clear(color); - public void DrawPath(Pen pen, GraphicsPath path) => _rasterGraphics.DrawPath(pen, path); - public void FillPath(Brush brush, GraphicsPath path) => _rasterGraphics.FillPath(brush, path); - public void FillPath(Brush brush, GraphicsPath path, FillMode fillMode) => _rasterGraphics.FillPath(brush, path, fillMode); - - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? attr) - => _rasterGraphics.DrawImage(image, destRect, srcRect, srcUnit, attr); - - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? attr) - => _rasterGraphics.DrawImage(image, destPoints, srcRect, srcUnit, attr); - - public void DrawString(string s, MiniPdfFont font, Brush brush, RectangleF layoutRect, StringFormat? format) - => _rasterGraphics.DrawString(s, font, brush, layoutRect, format); - - /// - /// Returns the rasterized buffer as a WMF . - /// Since WMF lacks vector path records, the output is a raster-in-WMF - /// (a single STRETCHDIBITS record). - /// - public Metafile.MetafileDocument ToDocument() - { - throw new NotSupportedException( - "WMF vector output is not supported. Use EmfDrawingContext for EMF output. " + - "For WMF raster output, save the rasterized bitmap to WMF format."); - } - - /// - /// Gets the rasterized bitmap representation of this context. - /// - public Bitmap ToBitmap() => _rasterBuffer.Clone() as Bitmap ?? new Bitmap(_width, _height); - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - _rasterGraphics.Dispose(); - _rasterBuffer.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgBrushReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgBrushReader.cs deleted file mode 100644 index e7e90749..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgBrushReader.cs +++ /dev/null @@ -1,376 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Represents a parsed SVG gradient definition (linear or radial) stored in - /// the defs table, used to construct a MiniSoftware.Drawing brush on demand. - /// - internal sealed class SvgGradientDef - { - public string Id = ""; - public bool IsRadial; - // Linear - public float X1, Y1, X2, Y2; - // Radial - public float Cx, Cy, R, Fx, Fy; - // Common - public string GradientUnits = "objectBoundingBox"; - public string SpreadMethod = "pad"; - public Matrix? GradientTransform; - public List<(float Offset, Color Color)> Stops = new List<(float, Color)>(); - } - - /// - /// Parses SVG fill/stroke values (colors, url(#id) references) and - /// gradient/pattern def elements into MiniSoftware.Drawing brushes. - /// - internal static class SvgBrushReader - { - /// - /// Resolves a paint value (e.g. red, #ff0000, - /// rgb(255,0,0), url(#g1)) to a brush, or null for - /// "none"/"inherit". - /// - public static Brush? ResolveBrush(string? paint, Dictionary defs) - { - if (string.IsNullOrWhiteSpace(paint)) return null; - paint = paint.Trim(); - - if (paint.Equals("none", StringComparison.OrdinalIgnoreCase) || - paint.Equals("inherit", StringComparison.OrdinalIgnoreCase)) - return null; - - // url(#id) reference - if (paint.StartsWith("url(", StringComparison.OrdinalIgnoreCase)) - { - int start = paint.IndexOf('#'); - int end = paint.IndexOf(')', start); - if (start < 0 || end < 0) return null; - string id = paint.Substring(start + 1, end - start - 1).Trim(); - if (defs.TryGetValue(id, out var def)) - return BrushFromDef(def); - return null; - } - - // Named color, hex, rgb(), etc. - Color color = ParseColor(paint); - if (color.IsEmpty) return null; - return new SolidBrush(color); - } - - /// - /// Parses an SVG color string: named color, #rgb, #rrggbb, - /// rgb(r,g,b), or rgba(r,g,b,a). - /// - public static Color ParseColor(string? s) - { - if (string.IsNullOrWhiteSpace(s)) return Color.Empty; - s = s.Trim(); - - // Hex - if (s.StartsWith("#")) - { - string hex = s.Substring(1); - if (hex.Length == 3) - { - byte r = (byte)(HexVal(hex[0]) * 17); - byte g = (byte)(HexVal(hex[1]) * 17); - byte b = (byte)(HexVal(hex[2]) * 17); - return Color.FromArgb(255, r, g, b); - } - if (hex.Length == 6) - { - int r = HexVal(hex[0]) * 16 + HexVal(hex[1]); - int g = HexVal(hex[2]) * 16 + HexVal(hex[3]); - int b = HexVal(hex[4]) * 16 + HexVal(hex[5]); - return Color.FromArgb(255, r, g, b); - } - if (hex.Length == 8) - { - int a = HexVal(hex[0]) * 16 + HexVal(hex[1]); - int r = HexVal(hex[2]) * 16 + HexVal(hex[3]); - int g = HexVal(hex[4]) * 16 + HexVal(hex[5]); - int b = HexVal(hex[6]) * 16 + HexVal(hex[7]); - return Color.FromArgb(a, r, g, b); - } - return Color.Empty; - } - - // rgb(r,g,b) or rgba(r,g,b,a) - if (s.StartsWith("rgb(", StringComparison.OrdinalIgnoreCase)) - { - string inner = s.Substring(4).TrimEnd(')', ' '); - var parts = inner.Split(','); - if (parts.Length >= 3) - { - int r = ParseChannel(parts[0].Trim()); - int g = ParseChannel(parts[1].Trim()); - int b = ParseChannel(parts[2].Trim()); - int a = 255; - if (parts.Length >= 4) - a = (int)(ParseChannel(parts[3].Trim())); - return Color.FromArgb(a, r, g, b); - } - return Color.Empty; - } - - // Named color - Color named = Color.FromName(s); - if (!named.IsEmpty) - return named; - - // "currentColor" — default to black - if (s.Equals("currentColor", StringComparison.OrdinalIgnoreCase)) - return Color.Black; - - return Color.Empty; - } - - /// - /// Applies opacity to a brush by returning a new brush with modified alpha. - /// For solid brushes, scales the alpha channel. For gradient brushes, - /// scales all stop alphas. - /// - public static Brush? ApplyOpacity(Brush? brush, float opacity) - { - if (brush == null || opacity >= 1f) return brush; - if (opacity <= 0f) return new SolidBrush(Color.FromArgb(0, 0, 0, 0)); - - if (brush is SolidBrush sb) - { - int a = (int)(sb.Color.A * opacity); - return new SolidBrush(Color.FromArgb(a, sb.Color.R, sb.Color.G, sb.Color.B)); - } - - // For gradient brushes, we'd need to scale stop alphas. - // For now, return as-is (opacity is best-effort for complex brushes). - return brush; - } - - /// - /// Constructs a MiniSoftware.Drawing brush from a parsed gradient def. - /// - private static Brush? BrushFromDef(object def) - { - if (def is SvgGradientDef gd) - return GradientToBrush(gd); - // Patterns and other def types: return null for now - return null; - } - - /// - /// Converts a to a - /// or . - /// - public static Brush? GradientToBrush(SvgGradientDef gd) - { - if (gd.Stops.Count == 0) return null; - - if (!gd.IsRadial) - { - Color c1 = gd.Stops[0].Color; - Color c2 = gd.Stops[gd.Stops.Count - 1].Color; - var brush = new LinearGradientBrush( - new PointF(gd.X1, gd.Y1), - new PointF(gd.X2, gd.Y2), - c1, c2); - - if (gd.SpreadMethod.Equals("repeat", StringComparison.OrdinalIgnoreCase)) - brush.WrapMode = WrapMode.Tile; - else if (gd.SpreadMethod.Equals("reflect", StringComparison.OrdinalIgnoreCase)) - brush.WrapMode = WrapMode.TileFlipXY; - else - brush.WrapMode = WrapMode.Clamp; - - // Multi-stop interpolation - if (gd.Stops.Count > 2) - { - var blend = new ColorBlend(gd.Stops.Count); - for (int i = 0; i < gd.Stops.Count; i++) - { - blend.Colors[i] = gd.Stops[i].Color; - blend.Positions[i] = gd.Stops[i].Offset; - } - brush.InterpolationColors = blend; - } - - if (gd.GradientTransform != null && !gd.GradientTransform.IsIdentity) - brush.Transform = gd.GradientTransform.Clone(); - - return brush; - } - else - { - // Radial gradient → PathGradientBrush - float r = Math.Max(gd.R, 1f); - var center = new PointF(gd.Cx, gd.Cy); - var points = new PointF[] - { - new PointF(gd.Cx + r, gd.Cy), - new PointF(gd.Cx, gd.Cy + r), - new PointF(gd.Cx - r, gd.Cy), - new PointF(gd.Cx, gd.Cy - r), - }; - var brush = new PathGradientBrush(points) - { - CenterPoint = center, - CenterColor = gd.Stops[0].Color, - }; - var surround = new Color[gd.Stops.Count > 1 ? gd.Stops.Count - 1 : 1]; - if (gd.Stops.Count > 1) - { - for (int i = 1; i < gd.Stops.Count; i++) - surround[i - 1] = gd.Stops[i].Color; - } - else - { - surround[0] = gd.Stops[0].Color; - } - brush.SurroundColors = surround; - - // Focus point - if (gd.Fx != gd.Cx || gd.Fy != gd.Cy) - { - float fxOffset = gd.Fx - gd.Cx; - float fyOffset = gd.Fy - gd.Cy; - brush.FocusScales = new PointF(fxOffset / r, fyOffset / r); - } - - if (gd.GradientTransform != null && !gd.GradientTransform.IsIdentity) - brush.Transform = gd.GradientTransform.Clone(); - - return brush; - } - } - - /// - /// Parses a gradient element (linearGradient or radialGradient) from the - /// XmlReader into a . - /// The reader must be positioned on the gradient start element. - /// Reads through the end element. - /// - public static SvgGradientDef ReadGradient(System.Xml.XmlReader reader, bool isRadial) - { - var gd = new SvgGradientDef { IsRadial = isRadial }; - gd.Id = reader.GetAttribute("id") ?? ""; - - // Default values depend on gradientUnits (objectBoundingBox vs userSpaceOnUse) - bool userSpace = string.Equals(reader.GetAttribute("gradientUnits"), - "userSpaceOnUse", StringComparison.OrdinalIgnoreCase); - gd.GradientUnits = userSpace ? "userSpaceOnUse" : "objectBoundingBox"; - - if (isRadial) - { - gd.Cx = SvgStyleParser.ParseFloat(reader.GetAttribute("cx"), userSpace ? 0f : 0.5f); - gd.Cy = SvgStyleParser.ParseFloat(reader.GetAttribute("cy"), userSpace ? 0f : 0.5f); - gd.R = SvgStyleParser.ParseFloat(reader.GetAttribute("r"), userSpace ? 0f : 0.5f); - gd.Fx = SvgStyleParser.ParseFloat(reader.GetAttribute("fx"), gd.Cx); - gd.Fy = SvgStyleParser.ParseFloat(reader.GetAttribute("fy"), gd.Cy); - } - else - { - gd.X1 = SvgStyleParser.ParseFloat(reader.GetAttribute("x1"), userSpace ? 0f : 0f); - gd.Y1 = SvgStyleParser.ParseFloat(reader.GetAttribute("y1"), userSpace ? 0f : 0f); - gd.X2 = SvgStyleParser.ParseFloat(reader.GetAttribute("x2"), userSpace ? 0f : 1f); - gd.Y2 = SvgStyleParser.ParseFloat(reader.GetAttribute("y2"), userSpace ? 0f : 0f); - } - - string? spread = reader.GetAttribute("spreadMethod"); - if (!string.IsNullOrEmpty(spread)) gd.SpreadMethod = spread; - - string? transformAttr = reader.GetAttribute("gradientTransform"); - if (!string.IsNullOrWhiteSpace(transformAttr)) - gd.GradientTransform = SvgTransformParser.Parse(transformAttr); - - // Read stops - if (!reader.IsEmptyElement) - { - while (reader.Read()) - { - if (reader.NodeType == System.Xml.XmlNodeType.EndElement) break; - if (reader.NodeType == System.Xml.XmlNodeType.Element && - reader.LocalName == "stop") - { - float offset = ParseOffset(reader.GetAttribute("offset")); - Color color = ParseColor(reader.GetAttribute("stop-color")); - - string? stopOpacity = reader.GetAttribute("stop-opacity"); - if (!string.IsNullOrWhiteSpace(stopOpacity) && - float.TryParse(stopOpacity, NumberStyles.Float, - CultureInfo.InvariantCulture, out float op)) - { - int a = (int)(color.A * Math.Max(0f, Math.Min(1f, op))); - color = Color.FromArgb(a, color.R, color.G, color.B); - } - - // Also check style attribute - string? styleAttr = reader.GetAttribute("style"); - if (!string.IsNullOrWhiteSpace(styleAttr)) - { - foreach (var pair in styleAttr.Split(';')) - { - int colon = pair.IndexOf(':'); - if (colon < 0) continue; - string pname = pair.Substring(0, colon).Trim(); - string pval = pair.Substring(colon + 1).Trim(); - if (pname == "stop-color") - color = ParseColor(pval); - else if (pname == "stop-opacity" && - float.TryParse(pval, NumberStyles.Float, - CultureInfo.InvariantCulture, out float so)) - { - int a = (int)(color.A * Math.Max(0f, Math.Min(1f, so))); - color = Color.FromArgb(a, color.R, color.G, color.B); - } - else if (pname == "offset") - offset = ParseOffset(pval); - } - } - - gd.Stops.Add((offset, color)); - } - } - } - - return gd; - } - - // ── Helpers ──────────────────────────────────────────────────────────── - - private static int HexVal(char c) - { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return 0; - } - - private static int ParseChannel(string s) - { - s = s.Trim(); - if (s.EndsWith("%")) - { - float v = SvgStyleParser.ParseFloat(s.TrimEnd('%')); - return (int)Math.Round(v * 255f / 100f); - } - return (int)SvgStyleParser.ParseFloat(s); - } - - private static float ParseOffset(string? s) - { - if (string.IsNullOrWhiteSpace(s)) return 0f; - s = s.Trim(); - bool isPercent = s.EndsWith("%"); - if (isPercent) s = s.TrimEnd('%'); - float v = SvgStyleParser.ParseFloat(s); - return isPercent ? v / 100f : Math.Max(0f, Math.Min(1f, v)); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgBrushWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgBrushWriter.cs deleted file mode 100644 index f1ea6672..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgBrushWriter.cs +++ /dev/null @@ -1,328 +0,0 @@ -using System; -using System.Globalization; -using System.Text; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Writes SVG brush representations: inline color for solid brushes, and - /// <linearGradient>/<radialGradient>/ - /// <pattern> defs for gradient/hatch/texture brushes. - /// - internal static class SvgBrushWriter - { - // ── Inline fill/stroke color ────────────────────────────────────────── - - /// - /// Returns the inline fill or stroke value for a brush. - /// Solid brushes return rgb(r,g,b); non-solid brushes return - /// url(#id) (the def must already be registered). Null brush - /// returns none. - /// - public static string WriteFillRef(Brush? brush, SvgDefTable defs) - { - if (brush == null) return "none"; - if (brush is SolidBrush sb) - return ColorToCss(sb.Color); - - string? id = defs?.RegisterBrush(brush); - return id != null ? "url(#" + id + ")" : "none"; - } - - /// - /// Returns the opacity (0–1) for a brush, or "1" if fully opaque. - /// - public static string? WriteFillOpacity(Brush? brush) - { - if (brush is SolidBrush sb) - { - if (sb.Color.A < 255) - return Fmt(sb.Color.A / 255f); - } - return null; - } - - // ── Def emission ────────────────────────────────────────────────────── - - /// - /// Emits all registered defs as SVG <defs> children. - /// - public static void WriteDefs(SvgXmlWriter w, SvgDefTable defs) - { - if (defs == null || defs.Defs.Count == 0) return; - w.WriteStartElement("defs"); - foreach (var def in defs.Defs) - WriteDef(w, def); - w.WriteEndElement(); - } - - private static void WriteDef(SvgXmlWriter w, SvgDef def) - { - switch (def.Kind) - { - case SvgDefKind.LinearGradient: - WriteLinearGradient(w, (LinearGradientBrush)def.Source!, def.Id); - break; - case SvgDefKind.RadialGradient: - WriteRadialGradient(w, (PathGradientBrush)def.Source!, def.Id); - break; - case SvgDefKind.HatchPattern: - WriteHatchPattern(w, (HatchBrush)def.Source!, def.Id); - break; - case SvgDefKind.TexturePattern: - WriteTexturePattern(w, (TextureBrush)def.Source!, def.Id); - break; - case SvgDefKind.ClipPath: - WriteClipPath(w, def); - break; - } - } - - // ── Linear gradient ─────────────────────────────────────────────────── - - private static void WriteLinearGradient(SvgXmlWriter w, LinearGradientBrush lg, string id) - { - w.WriteStartElement("linearGradient"); - w.WriteAttribute("id", id); - w.WriteAttribute("x1", lg.Point1.X); - w.WriteAttribute("y1", lg.Point1.Y); - w.WriteAttribute("x2", lg.Point2.X); - w.WriteAttribute("y2", lg.Point2.Y); - w.WriteAttribute("gradientUnits", "userSpaceOnUse"); - WriteSpreadMethod(w, lg.WrapMode); - var matrix = lg.Transform; - if (matrix != null && !matrix.IsIdentity) - w.WriteAttribute("gradientTransform", SvgTransformWriter.WriteTransform(matrix)); - - var blend = lg.InterpolationColors; - if (blend != null && blend.Colors.Length >= 2) - { - for (int i = 0; i < blend.Colors.Length; i++) - WriteStop(w, blend.Positions[i], blend.Colors[i]); - } - else - { - var colors = lg.LinearColors; - WriteStop(w, 0f, colors[0]); - WriteStop(w, 1f, colors[1]); - } - w.WriteEndElement(); - } - - // ── Radial gradient ─────────────────────────────────────────────────── - - private static void WriteRadialGradient(SvgXmlWriter w, PathGradientBrush pg, string id) - { - w.WriteStartElement("radialGradient"); - w.WriteAttribute("id", id); - - var rect = pg.Rectangle; - float cx = pg.CenterPoint.X; - float cy = pg.CenterPoint.Y; - // radius = max distance from center to bounds edge - float r = Math.Max( - Math.Max(Math.Abs(rect.Right - cx), Math.Abs(cx - rect.X)), - Math.Max(Math.Abs(rect.Bottom - cy), Math.Abs(cy - rect.Y))); - if (r <= 0f) r = 1f; - - w.WriteAttribute("cx", cx); - w.WriteAttribute("cy", cy); - w.WriteAttribute("r", r); - // Focus point (fx, fy) — only emit if different from center - float fx = cx + pg.FocusScales.X; - float fy = cy + pg.FocusScales.Y; - if (Math.Abs(fx - cx) > 0.001f || Math.Abs(fy - cy) > 0.001f) - { - w.WriteAttribute("fx", fx); - w.WriteAttribute("fy", fy); - } - w.WriteAttribute("gradientUnits", "userSpaceOnUse"); - var matrix = pg.Transform; - if (matrix != null && !matrix.IsIdentity) - w.WriteAttribute("gradientTransform", SvgTransformWriter.WriteTransform(matrix)); - - WriteStop(w, 0f, pg.CenterColor); - var surround = pg.SurroundColors; - if (surround.Length > 0) - { - // Single surround color → stop at 1 - if (surround.Length == 1) - WriteStop(w, 1f, surround[0]); - else - for (int i = 0; i < surround.Length; i++) - WriteStop(w, (float)(i + 1) / surround.Length, surround[i]); - } - w.WriteEndElement(); - } - - // ── Hatch pattern ───────────────────────────────────────────────────── - - private static void WriteHatchPattern(SvgXmlWriter w, HatchBrush hb, string id) - { - w.WriteStartElement("pattern"); - w.WriteAttribute("id", id); - w.WriteAttribute("width", 8); - w.WriteAttribute("height", 8); - w.WriteAttribute("patternUnits", "userSpaceOnUse"); - - // Background rect - w.WriteStartElement("rect"); - w.WriteAttribute("x", 0); - w.WriteAttribute("y", 0); - w.WriteAttribute("width", 8); - w.WriteAttribute("height", 8); - w.WriteAttribute("fill", ColorToCss(hb.BackgroundColor)); - w.WriteEndElement(); - - // Foreground hatch geometry (simplified: a few common styles) - WriteHatchForeground(w, hb); - w.WriteEndElement(); - } - - private static void WriteHatchForeground(SvgXmlWriter w, HatchBrush hb) - { - string fg = ColorToCss(hb.ForegroundColor); - switch (hb.HatchStyle) - { - case HatchStyle.Horizontal: - WriteLine(w, 0, 0, 8, 0, fg); - break; - case HatchStyle.Vertical: - WriteLine(w, 0, 0, 0, 8, fg); - break; - case HatchStyle.ForwardDiagonal: - WriteLine(w, 0, 0, 8, 8, fg); - break; - case HatchStyle.BackwardDiagonal: - WriteLine(w, 0, 8, 8, 0, fg); - break; - case HatchStyle.Cross: - WriteLine(w, 0, 0, 8, 0, fg); - WriteLine(w, 0, 0, 0, 8, fg); - break; - case HatchStyle.DiagonalCross: - WriteLine(w, 0, 0, 8, 8, fg); - WriteLine(w, 0, 8, 8, 0, fg); - break; - default: - // Default: solid foreground fill for unknown styles - w.WriteStartElement("rect"); - w.WriteAttribute("x", 0); w.WriteAttribute("y", 0); - w.WriteAttribute("width", 8); w.WriteAttribute("height", 8); - w.WriteAttribute("fill", fg); - w.WriteEndElement(); - break; - } - } - - private static void WriteLine(SvgXmlWriter w, float x1, float y1, float x2, float y2, string stroke) - { - w.WriteStartElement("line"); - w.WriteAttribute("x1", x1); w.WriteAttribute("y1", y1); - w.WriteAttribute("x2", x2); w.WriteAttribute("y2", y2); - w.WriteAttribute("stroke", stroke); - w.WriteAttribute("stroke-width", 1); - w.WriteEndElement(); - } - - // ── Texture pattern ─────────────────────────────────────────────────── - - private static void WriteTexturePattern(SvgXmlWriter w, TextureBrush tb, string id) - { - w.WriteStartElement("pattern"); - w.WriteAttribute("id", id); - w.WriteAttribute("width", tb.Image.Width); - w.WriteAttribute("height", tb.Image.Height); - w.WriteAttribute("patternUnits", "userSpaceOnUse"); - var matrix = tb.Transform; - if (matrix != null && !matrix.IsIdentity) - w.WriteAttribute("patternTransform", SvgTransformWriter.WriteTransform(matrix)); - - // Embedded image - w.WriteStartElement("image"); - w.WriteAttribute("x", 0); - w.WriteAttribute("y", 0); - w.WriteAttribute("width", tb.Image.Width); - w.WriteAttribute("height", tb.Image.Height); - w.WriteXLinkHref(SvgImageWriter.EmbedImage(tb.Image)); - w.WriteEndElement(); - - w.WriteEndElement(); - } - - // ── Clip path ───────────────────────────────────────────────────────── - - private static void WriteClipPath(SvgXmlWriter w, SvgDef def) - { - w.WriteStartElement("clipPath"); - w.WriteAttribute("id", def.Id); - if (def.Source is Region region) - { - var scans = region.GetRegionScans(new Matrix()); - foreach (var r in scans) - { - w.WriteStartElement("rect"); - w.WriteAttribute("x", r.X); - w.WriteAttribute("y", r.Y); - w.WriteAttribute("width", r.Width); - w.WriteAttribute("height", r.Height); - w.WriteEndElement(); - } - } - else if (def.ClipPath != null) - { - w.WriteStartElement("path"); - w.WriteAttribute("d", SvgPathWriter.WritePathData(def.ClipPath)); - w.WriteEndElement(); - } - w.WriteEndElement(); - } - - // ── Helpers ─────────────────────────────────────────────────────────── - - private static void WriteStop(SvgXmlWriter w, float offset, Color color) - { - w.WriteStartElement("stop"); - w.WriteAttribute("offset", Fmt(offset)); - w.WriteAttribute("stop-color", ColorToCss(color)); - if (color.A < 255) - w.WriteAttribute("stop-opacity", Fmt(color.A / 255f)); - w.WriteEndElement(); - } - - private static void WriteSpreadMethod(SvgXmlWriter w, WrapMode wrap) - { - string s = wrap switch - { - WrapMode.Tile => "repeat", - WrapMode.Clamp => "pad", - WrapMode.TileFlipX => "repeat", - WrapMode.TileFlipY => "repeat", - WrapMode.TileFlipXY => "repeat", - _ => "pad", - }; - w.WriteAttribute("spreadMethod", s); - } - - /// Converts a Color to an SVG CSS color string: rgb(r,g,b). - public static string ColorToCss(Color color) - { - return string.Format(CultureInfo.InvariantCulture, - "rgb({0},{1},{2})", color.R, color.G, color.B); - } - - private static string Fmt(float v) - { - if (float.IsNaN(v) || float.IsInfinity(v)) v = 0f; - string s = v.ToString("F4", CultureInfo.InvariantCulture); - if (s.IndexOf('.') >= 0) - s = s.TrimEnd('0').TrimEnd('.'); - if (s.Length == 0 || s == "-") s = "0"; - return s; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgClipReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgClipReader.cs deleted file mode 100644 index 53c79899..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgClipReader.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Xml; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses SVG <clipPath> def elements into - /// objects for use as clipping regions. - /// - internal static class SvgClipReader - { - /// - /// Reads a <clipPath> element and returns the combined - /// clip path. The reader must be positioned on the clipPath start - /// element; reads through the end element. - /// - public static GraphicsPath ReadClipPath(XmlReader reader) - { - var combined = new GraphicsPath(); - - if (reader.IsEmptyElement) - return combined; - - string? clipRule = reader.GetAttribute("clip-rule"); - - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement) break; - if (reader.NodeType != XmlNodeType.Element) continue; - - string name = reader.LocalName; - var style = new SvgStyle(); - var attrs = SvgStyleParser.ApplyAttributes(reader, style); - - GraphicsPath? shape = SvgShapeReader.ReadShape(name, attrs, style); - if (shape != null && shape.PointCount > 0) - { - // Union the shape into the combined clip path - // (GraphicsPath doesn't have Union, so we just add the points) - var pts = shape.PathPoints; - var types = shape.PathTypes; - for (int i = 0; i < pts.Length; i++) - { - combined.AddLine(pts[i], pts[i]); - } - shape.Dispose(); - } - } - - return combined; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgClipWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgClipWriter.cs deleted file mode 100644 index 90504988..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgClipWriter.cs +++ /dev/null @@ -1,37 +0,0 @@ -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Registers clip regions/paths with the and - /// produces the clip-path="url(#id)" reference. - /// - internal static class SvgClipWriter - { - /// - /// Registers a region clip and returns the url(#id) reference, - /// or null if the region is null or infinite (no clip needed). - /// - public static string? WriteClipRef(SvgDefTable defs, Region? clip) - { - if (clip == null) return null; - if (clip.IsInfinite()) return null; - - string id = defs.RegisterClip(clip, null); - return "url(#" + id + ")"; - } - - /// - /// Registers a path clip and returns the url(#id) reference, - /// or null if the path is null. - /// - public static string? WriteClipRef(SvgDefTable defs, GraphicsPath? path) - { - if (path == null) return null; - if (path.PointCount == 0) return null; - - string id = defs.RegisterClip(null, path); - return "url(#" + id + ")"; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgDefCollector.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgDefCollector.cs deleted file mode 100644 index 7db7bf9a..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgDefCollector.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// A non-emitting used in the def-collection - /// pass. It traverses the same command stream as the emit pass, registering - /// every unique brush, pen, and clip with the so - /// that <defs> can be written before the body. - /// - internal sealed class SvgDefCollector : IDrawingContext - { - private readonly SvgDefTable _defs; - private readonly int _width; - private readonly int _height; - private Matrix _transform = new Matrix(); - private Region _clip; - private bool _disposed; - - public SvgDefCollector(SvgDefTable defs, int width, int height) - { - _defs = defs; - _width = width; - _height = height; - _clip = new Region(); - _clip.MakeInfinite(); - } - - public int Width => _width; - public int Height => _height; - public float DpiX => 96f; - public float DpiY => 96f; - - public Matrix Transform { get => _transform; set => _transform = value ?? new Matrix(); } - public Region Clip { get => _clip; set => _clip = value ?? new Region(); } - public SmoothingMode SmoothingMode { get; set; } - public InterpolationMode InterpolationMode { get; set; } - public CompositingMode CompositingMode { get; set; } - public CompositingQuality CompositingQuality { get; set; } - public PixelOffsetMode PixelOffsetMode { get; set; } - public TextRenderingHint TextRenderingHint { get; set; } - public GraphicsUnit PageUnit { get; set; } = GraphicsUnit.Pixel; - public float PageScale { get; set; } = 1f; - public Point RenderingOrigin { get; set; } - - public void ResetTransform() => _transform.Reset(); - public void MultiplyTransform(Matrix m, MatrixOrder order = MatrixOrder.Prepend) => _transform.Multiply(m, order); - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) => _transform.Rotate(angle, order); - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) => _transform.Scale(sx, sy, order); - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) => _transform.Translate(dx, dy, order); - - public void SetClip(RectangleF rect, CombineMode mode = CombineMode.Replace) => _clip = new Region(rect); - public void SetClip(GraphicsPath path, CombineMode mode = CombineMode.Replace) => _clip = new Region(path); - public void SetClip(Region region, CombineMode mode = CombineMode.Replace) => _clip = region.Clone(); - public void IntersectClip(RectangleF rect) => _clip.Intersect(rect); - public void IntersectClip(Region region) => _clip.Intersect(region); - public void ExcludeClip(Rectangle rect) => _clip.Exclude(rect); - public void ExcludeClip(Region region) => _clip.Exclude(region); - public void ResetClip() { _clip = new Region(); _clip.MakeInfinite(); } - public void TranslateClip(float dx, float dy) => _clip.Translate(dx, dy); - - public GraphicsState Save() - { - return new GraphicsState(_transform.Clone(), _clip.Clone(), PageUnit, PageScale, - SmoothingMode, InterpolationMode, CompositingMode, CompositingQuality, - PixelOffsetMode, TextRenderingHint, RenderingOrigin); - } - public void Restore(GraphicsState state) { } - public GraphicsContainer BeginContainer() - { - var gs = new GraphicsState(_transform.Clone(), _clip.Clone(), PageUnit, PageScale, - SmoothingMode, InterpolationMode, CompositingMode, CompositingQuality, - PixelOffsetMode, TextRenderingHint, RenderingOrigin); - return new GraphicsContainer(gs); - } - public GraphicsContainer BeginContainer(RectangleF dst, RectangleF src, GraphicsUnit unit) => BeginContainer(); - public void EndContainer(GraphicsContainer container) { } - - // ── Primitives: register brushes/pens/clips ──────────────────────────── - - public void Clear(Color color) { /* no def needed */ } - - public void DrawPath(Pen pen, GraphicsPath path) - { - if (pen != null && pen.PenType != PenType.SolidColor) - _defs.RegisterBrush(pen.Brush); - if (!_clip.IsInfinite()) - _defs.RegisterClip(_clip, null); - } - - public void FillPath(Brush brush, GraphicsPath path) - => FillPath(brush, path, path?.FillMode ?? FillMode.Alternate); - - public void FillPath(Brush brush, GraphicsPath path, FillMode fillMode) - { - if (brush != null) - _defs.RegisterBrush(brush); - if (!_clip.IsInfinite()) - _defs.RegisterClip(_clip, null); - } - - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (!_clip.IsInfinite()) - _defs.RegisterClip(_clip, null); - } - - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (!_clip.IsInfinite()) - _defs.RegisterClip(_clip, null); - } - - public void DrawString(string s, MiniSoftware.Drawing.Text.Font font, Brush brush, - RectangleF layoutRect, StringFormat? format) - { - if (brush != null) - _defs.RegisterBrush(brush); - if (!_clip.IsInfinite()) - _defs.RegisterClip(_clip, null); - } - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgDefTable.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgDefTable.cs deleted file mode 100644 index 22c28c06..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgDefTable.cs +++ /dev/null @@ -1,218 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Collects unique SVG definitions (gradients, patterns, clip paths) during - /// the def-collection pass and assigns stable ids. Brushes and clips are - /// deduplicated by value so identical objects share one def. - /// - internal sealed class SvgDefTable - { - private readonly List _defs = new List(); - private readonly Dictionary _byKey = new Dictionary(); - private int _gradientCounter; - private int _patternCounter; - private int _clipCounter; - - public IReadOnlyList Defs => _defs; - - /// - /// Registers a brush and returns the id to reference it (via - /// url(#id)). Solid brushes return null (inlined as a color). - /// - public string? RegisterBrush(Brush brush) - { - if (brush == null) return null; - - switch (brush) - { - case SolidBrush sb: - return null; // inline color, no def - - case LinearGradientBrush lg: - return RegisterGradient(lg); - - case PathGradientBrush pg: - return RegisterRadialGradient(pg); - - case HatchBrush hb: - return RegisterHatchPattern(hb); - - case TextureBrush tb: - return RegisterTexturePattern(tb); - - default: - return null; - } - } - - /// - /// Registers a clip path derived from a or - /// and returns the clip id. - /// - public string RegisterClip(Region? region, GraphicsPath? path) - { - string key = "clip:" + BuildClipKey(region, path); - if (_byKey.TryGetValue(key, out var existing)) - return existing.Id; - - string id = "clip" + (++_clipCounter); - var def = new SvgDef(id, SvgDefKind.ClipPath, key, region, path); - _byKey[key] = def; - _defs.Add(def); - return id; - } - - // ── Brush registration ──────────────────────────────────────────────── - - private string RegisterGradient(LinearGradientBrush lg) - { - string key = "lg:" + BuildLinearGradientKey(lg); - if (_byKey.TryGetValue(key, out var existing)) - return existing.Id; - - string id = "grad" + (++_gradientCounter); - var def = new SvgDef(id, SvgDefKind.LinearGradient, key, lg, null); - _byKey[key] = def; - _defs.Add(def); - return id; - } - - private string RegisterRadialGradient(PathGradientBrush pg) - { - string key = "rg:" + BuildRadialGradientKey(pg); - if (_byKey.TryGetValue(key, out var existing)) - return existing.Id; - - string id = "grad" + (++_gradientCounter); - var def = new SvgDef(id, SvgDefKind.RadialGradient, key, pg, null); - _byKey[key] = def; - _defs.Add(def); - return id; - } - - private string RegisterHatchPattern(HatchBrush hb) - { - string key = "hatch:" + (int)hb.HatchStyle + ":" + hb.ForegroundColor.ToArgb().ToString("X8") - + ":" + hb.BackgroundColor.ToArgb().ToString("X8"); - if (_byKey.TryGetValue(key, out var existing)) - return existing.Id; - - string id = "pat" + (++_patternCounter); - var def = new SvgDef(id, SvgDefKind.HatchPattern, key, hb, null); - _byKey[key] = def; - _defs.Add(def); - return id; - } - - private string RegisterTexturePattern(TextureBrush tb) - { - string key = "tex:" + tb.Image.GetHashCode().ToString(CultureInfo.InvariantCulture) - + ":" + (int)tb.WrapMode; - if (_byKey.TryGetValue(key, out var existing)) - return existing.Id; - - string id = "pat" + (++_patternCounter); - var def = new SvgDef(id, SvgDefKind.TexturePattern, key, tb, null); - _byKey[key] = def; - _defs.Add(def); - return id; - } - - // ── Key builders ────────────────────────────────────────────────────── - - private static string BuildLinearGradientKey(LinearGradientBrush lg) - { - var sb = new StringBuilder(); - sb.Append(lg.Point1.X).Append(',').Append(lg.Point1.Y).Append(';'); - sb.Append(lg.Point2.X).Append(',').Append(lg.Point2.Y).Append(';'); - sb.Append((int)lg.WrapMode).Append(';'); - foreach (var c in lg.LinearColors) - sb.Append(c.ToArgb().ToString("X8")).Append(','); - var blend = lg.InterpolationColors; - if (blend != null && blend.Colors.Length > 0) - { - for (int i = 0; i < blend.Colors.Length; i++) - { - sb.Append(blend.Positions[i]).Append(':'); - sb.Append(blend.Colors[i].ToArgb().ToString("X8")).Append(','); - } - } - AppendMatrixKey(sb, lg.Transform); - return sb.ToString(); - } - - private static string BuildRadialGradientKey(PathGradientBrush pg) - { - var sb = new StringBuilder(); - sb.Append(pg.CenterPoint.X).Append(',').Append(pg.CenterPoint.Y).Append(';'); - sb.Append(pg.CenterColor.ToArgb().ToString("X8")).Append(';'); - foreach (var c in pg.SurroundColors) - sb.Append(c.ToArgb().ToString("X8")).Append(','); - sb.Append(pg.FocusScales.X).Append(',').Append(pg.FocusScales.Y).Append(';'); - AppendMatrixKey(sb, pg.Transform); - return sb.ToString(); - } - - private static string BuildClipKey(Region? region, GraphicsPath? path) - { - var sb = new StringBuilder(); - if (region != null) - { - var scans = region.GetRegionScans(new Matrix()); - sb.Append("r:").Append(scans.Length).Append(';'); - foreach (var r in scans) - sb.Append(r.X).Append(',').Append(r.Y).Append(',').Append(r.Width).Append(',').Append(r.Height).Append(';'); - } - if (path != null) - { - var pts = path.PathPoints; - var types = path.PathTypes; - sb.Append("p:").Append(pts.Length).Append(';'); - for (int i = 0; i < pts.Length; i++) - sb.Append(pts[i].X).Append(',').Append(pts[i].Y).Append(',').Append(types[i]).Append(';'); - } - return sb.ToString(); - } - - private static void AppendMatrixKey(StringBuilder sb, Matrix m) - { - if (m == null) return; - var e = m.Elements; - for (int i = 0; i < e.Length; i++) - sb.Append(e[i]).Append(','); - } - } - - internal enum SvgDefKind - { - LinearGradient, - RadialGradient, - HatchPattern, - TexturePattern, - ClipPath, - } - - /// One registered SVG def entry. - internal sealed class SvgDef - { - public string Id { get; } - public SvgDefKind Kind { get; } - public string Key { get; } - public object? Source { get; } - public GraphicsPath? ClipPath { get; } - - public SvgDef(string id, SvgDefKind kind, string key, object? source, GraphicsPath? clipPath) - { - Id = id; Kind = kind; Key = key; Source = source; ClipPath = clipPath; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgDrawingContext.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgDrawingContext.cs deleted file mode 100644 index 0042c67e..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgDrawingContext.cs +++ /dev/null @@ -1,347 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// An implementation that emits SVG XML from - /// replayed s. Used as the emit-pass target in - /// the two-pass SVG writer pipeline. - /// - internal sealed class SvgDrawingContext : IDrawingContext - { - private readonly SvgXmlWriter _w; - private readonly SvgDefTable _defs; - private readonly SvgEncoderParameters _params; - private readonly int _width; - private readonly int _height; - - private Matrix _transform = new Matrix(); - private Region _clip = new Region(); - private SmoothingMode _smoothingMode = SmoothingMode.None; - private InterpolationMode _interpolationMode = InterpolationMode.NearestNeighbor; - private CompositingMode _compositingMode = CompositingMode.SourceOver; - private CompositingQuality _compositingQuality = CompositingQuality.Default; - private PixelOffsetMode _pixelOffsetMode = PixelOffsetMode.Default; - private TextRenderingHint _textRenderingHint = TextRenderingHint.SystemDefault; - private GraphicsUnit _pageUnit = GraphicsUnit.Pixel; - private float _pageScale = 1f; - private Point _renderingOrigin = new Point(0, 0); - - private readonly Stack _stateStack = new Stack(); - private bool _disposed; - - public SvgDrawingContext(SvgXmlWriter w, SvgDefTable defs, SvgEncoderParameters parameters, - int width, int height) - { - _w = w; - _defs = defs; - _params = parameters; - _width = width; - _height = height; - _clip.MakeInfinite(); - } - - // ── Dimensions / DPI ────────────────────────────────────────────────── - - public int Width => _width; - public int Height => _height; - public float DpiX => 96f; - public float DpiY => 96f; - - // ── Rendering state ─────────────────────────────────────────────────── - - public Matrix Transform - { - get => _transform; - set => _transform = value ?? new Matrix(); - } - - public Region Clip - { - get => _clip; - set => _clip = value ?? new Region(); - } - - public SmoothingMode SmoothingMode { get => _smoothingMode; set => _smoothingMode = value; } - public InterpolationMode InterpolationMode { get => _interpolationMode; set => _interpolationMode = value; } - public CompositingMode CompositingMode { get => _compositingMode; set => _compositingMode = value; } - public CompositingQuality CompositingQuality { get => _compositingQuality; set => _compositingQuality = value; } - public PixelOffsetMode PixelOffsetMode { get => _pixelOffsetMode; set => _pixelOffsetMode = value; } - public TextRenderingHint TextRenderingHint { get => _textRenderingHint; set => _textRenderingHint = value; } - public GraphicsUnit PageUnit { get => _pageUnit; set => _pageUnit = value; } - public float PageScale { get => _pageScale; set => _pageScale = value; } - public Point RenderingOrigin { get => _renderingOrigin; set => _renderingOrigin = value; } - - // ── Transform mutators ──────────────────────────────────────────────── - - public void ResetTransform() => _transform.Reset(); - - public void MultiplyTransform(Matrix m, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Multiply(m, order); - - public void RotateTransform(float angle, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Rotate(angle, order); - - public void ScaleTransform(float sx, float sy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Scale(sx, sy, order); - - public void TranslateTransform(float dx, float dy, MatrixOrder order = MatrixOrder.Prepend) - => _transform.Translate(dx, dy, order); - - // ── Clip mutators ───────────────────────────────────────────────────── - - public void SetClip(RectangleF rect, CombineMode mode = CombineMode.Replace) - { - _clip = new Region(rect); - } - - public void SetClip(GraphicsPath path, CombineMode mode = CombineMode.Replace) - { - _clip = new Region(path); - } - - public void SetClip(Region region, CombineMode mode = CombineMode.Replace) - { - _clip = region.Clone(); - } - - public void IntersectClip(RectangleF rect) => _clip.Intersect(rect); - public void IntersectClip(Region region) => _clip.Intersect(region); - public void ExcludeClip(Rectangle rect) => _clip.Exclude(rect); - public void ExcludeClip(Region region) => _clip.Exclude(region); - public void ResetClip() { _clip = new Region(); _clip.MakeInfinite(); } - public void TranslateClip(float dx, float dy) => _clip.Translate(dx, dy); - - // ── State stack ─────────────────────────────────────────────────────── - - private readonly Dictionary _stateDepths = new Dictionary(); - private readonly Dictionary _containerDepths = new Dictionary(); - - public GraphicsState Save() - { - _stateStack.Push(CaptureState()); - var token = new GraphicsState(_transform.Clone(), _clip.Clone(), _pageUnit, _pageScale, - _smoothingMode, _interpolationMode, _compositingMode, _compositingQuality, - _pixelOffsetMode, _textRenderingHint, _renderingOrigin); - _stateDepths[token] = _stateStack.Count; - return token; - } - - public void Restore(GraphicsState state) - { - if (state == null) return; - if (!_stateDepths.TryGetValue(state, out int depth)) return; - while (_stateStack.Count >= depth && _stateStack.Count > 0) - RestoreState(_stateStack.Pop()); - } - - public GraphicsContainer BeginContainer() - { - _stateStack.Push(CaptureState()); - var gs = new GraphicsState(_transform.Clone(), _clip.Clone(), _pageUnit, _pageScale, - _smoothingMode, _interpolationMode, _compositingMode, _compositingQuality, - _pixelOffsetMode, _textRenderingHint, _renderingOrigin); - var token = new GraphicsContainer(gs); - _containerDepths[token] = _stateStack.Count; - return token; - } - - public GraphicsContainer BeginContainer(RectangleF dst, RectangleF src, GraphicsUnit unit) - => BeginContainer(); - - public void EndContainer(GraphicsContainer container) - { - if (container == null) return; - if (!_containerDepths.TryGetValue(container, out int depth)) return; - while (_stateStack.Count >= depth && _stateStack.Count > 0) - RestoreState(_stateStack.Pop()); - } - - private StateFrame CaptureState() => new StateFrame - { - Transform = _transform.Clone(), - Clip = _clip.Clone(), - SmoothingMode = _smoothingMode, - InterpolationMode = _interpolationMode, - CompositingMode = _compositingMode, - CompositingQuality = _compositingQuality, - PixelOffsetMode = _pixelOffsetMode, - TextRenderingHint = _textRenderingHint, - PageUnit = _pageUnit, - PageScale = _pageScale, - RenderingOrigin = _renderingOrigin, - }; - - private void RestoreState(StateFrame frame) - { - _transform = frame.Transform; - _clip = frame.Clip; - _smoothingMode = frame.SmoothingMode; - _interpolationMode = frame.InterpolationMode; - _compositingMode = frame.CompositingMode; - _compositingQuality = frame.CompositingQuality; - _pixelOffsetMode = frame.PixelOffsetMode; - _textRenderingHint = frame.TextRenderingHint; - _pageUnit = frame.PageUnit; - _pageScale = frame.PageScale; - _renderingOrigin = frame.RenderingOrigin; - } - - // ── Primitives ──────────────────────────────────────────────────────── - - public void Clear(Color color) - { - // Emit a full-canvas background rect - _w.WriteStartElement("rect"); - _w.WriteAttribute("x", 0); - _w.WriteAttribute("y", 0); - _w.WriteAttribute("width", _width); - _w.WriteAttribute("height", _height); - _w.WriteAttribute("fill", SvgBrushWriter.ColorToCss(color)); - if (color.A < 255) - _w.WriteAttribute("fill-opacity", color.A / 255f); - _w.WriteEndElement(); - } - - public void DrawPath(Pen pen, GraphicsPath path) - { - if (pen == null || path == null || path.PointCount == 0) return; - - BeginGroup(); - string d = SvgPathWriter.WritePathData(path, _params.CoordinatePrecision); - _w.WriteStartElement("path"); - _w.WriteAttribute("d", d); - _w.WriteAttribute("fill", "none"); - SvgPenWriter.WriteStroke(_w, pen, _defs); - _w.WriteEndElement(); - EndGroup(); - } - - public void FillPath(Brush brush, GraphicsPath path) - => FillPath(brush, path, path?.FillMode ?? FillMode.Alternate); - - public void FillPath(Brush brush, GraphicsPath path, FillMode fillMode) - { - if (brush == null || path == null || path.PointCount == 0) return; - - BeginGroup(); - string d = SvgPathWriter.WritePathData(path, _params.CoordinatePrecision); - _w.WriteStartElement("path"); - _w.WriteAttribute("d", d); - _w.WriteAttribute("fill", SvgBrushWriter.WriteFillRef(brush, _defs)); - var opacity = SvgBrushWriter.WriteFillOpacity(brush); - if (opacity != null) - _w.WriteAttribute("fill-opacity", opacity); - // fill-rule: Alternate → evenodd, Winding → nonzero - _w.WriteAttributeOptional("fill-rule", - fillMode == FillMode.Alternate ? "evenodd" : "nonzero", "nonzero"); - _w.WriteAttribute("stroke", "none"); - _w.WriteEndElement(); - EndGroup(); - } - - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (image == null) return; - BeginGroup(); - SvgImageWriter.WriteImage(_w, image, destRect); - EndGroup(); - } - - public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, - GraphicsUnit srcUnit, ImageAttributes? attr) - { - if (image == null || destPoints == null || destPoints.Length < 3) return; - - // Approximate affine transform: compute dest rect from dest points - float minX = float.MaxValue, minY = float.MaxValue; - float maxX = float.MinValue, maxY = float.MinValue; - foreach (var p in destPoints) - { - if (p.X < minX) minX = p.X; - if (p.Y < minY) minY = p.Y; - if (p.X > maxX) maxX = p.X; - if (p.Y > maxY) maxY = p.Y; - } - var destRect = new RectangleF(minX, minY, maxX - minX, maxY - minY); - BeginGroup(); - SvgImageWriter.WriteImage(_w, image, destRect); - EndGroup(); - } - - public void DrawString(string s, MiniSoftware.Drawing.Text.Font font, Brush brush, - RectangleF layoutRect, StringFormat? format) - { - if (string.IsNullOrEmpty(s) || font == null || brush == null) return; - - BeginGroup(); - var textWriter = new SvgTextWriter(_w, _defs, _params); - textWriter.WriteText(s, font, brush, layoutRect, format); - EndGroup(); - } - - // ── Group wrapping (transform + clip) ───────────────────────────────── - - private void BeginGroup() - { - bool hasTransform = !_transform.IsIdentity; - bool hasClip = !_clip.IsInfinite(); - if (!hasTransform && !hasClip) return; - - _w.WriteStartElement("g"); - if (hasTransform) - { - string t = SvgTransformWriter.WriteTransform(_transform, _params.CoordinatePrecision); - if (!string.IsNullOrEmpty(t)) - _w.WriteAttribute("transform", t); - } - if (hasClip) - { - string? clipRef = SvgClipWriter.WriteClipRef(_defs, _clip); - if (clipRef != null) - _w.WriteAttribute("clip-path", clipRef); - } - } - - private void EndGroup() - { - if (!_transform.IsIdentity || !_clip.IsInfinite()) - _w.WriteEndElement(); - } - - // ── Dispose ─────────────────────────────────────────────────────────── - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - } - - private sealed class StateFrame - { - public Matrix Transform = null!; - public Region Clip = null!; - public SmoothingMode SmoothingMode; - public InterpolationMode InterpolationMode; - public CompositingMode CompositingMode; - public CompositingQuality CompositingQuality; - public PixelOffsetMode PixelOffsetMode; - public TextRenderingHint TextRenderingHint; - public GraphicsUnit PageUnit; - public float PageScale; - public Point RenderingOrigin; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgElementReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgElementReader.cs deleted file mode 100644 index 04ea32b9..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgElementReader.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Helper methods for parsing SVG structural elements (<g>, - /// <svg>, <defs>, <use>) and - /// resolving element attributes. The main orchestration lives in - /// ; this class provides reusable utilities. - /// - internal static class SvgElementReader - { - /// - /// Extracts the id from a url(#id) reference string. - /// Returns null if the string is not a url reference. - /// - public static string? ExtractUrlId(string? s) - { - if (string.IsNullOrWhiteSpace(s)) return null; - s = s.Trim(); - if (!s.StartsWith("url(", StringComparison.OrdinalIgnoreCase)) return null; - - int hash = s.IndexOf('#'); - int end = s.IndexOf(')', hash); - if (hash < 0 || end < 0) return null; - return s.Substring(hash + 1, end - hash - 1).Trim(); - } - - /// - /// Reads all attributes from the current element into a dictionary. - /// The reader should be positioned on an element start tag. - /// Returns to the element after reading. - /// - public static Dictionary ReadAllAttributes(XmlReader reader) - { - var attrs = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (reader.HasAttributes) - { - while (reader.MoveToNextAttribute()) - attrs[reader.Name] = reader.Value; - reader.MoveToElement(); - } - return attrs; - } - - /// - /// Skips all child content of the current element. - /// - public static void SkipChildren(XmlReader reader) - { - if (reader.IsEmptyElement) return; - int depth = reader.Depth; - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) - break; - } - } - - /// - /// Determines whether an SVG element name is a drawable shape. - /// - public static bool IsShape(string name) - { - switch (name) - { - case "rect": - case "circle": - case "ellipse": - case "line": - case "polyline": - case "polygon": - case "path": - return true; - default: - return false; - } - } - - /// - /// Determines whether an SVG element name is a structural element. - /// - public static bool IsStructural(string name) - { - switch (name) - { - case "svg": - case "g": - case "defs": - case "use": - case "symbol": - return true; - default: - return false; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgEncoderParameters.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgEncoderParameters.cs deleted file mode 100644 index 43ac35df..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgEncoderParameters.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Specifies how text is emitted in SVG output. - /// - public enum SvgTextMode - { - /// - /// Vectorize glyphs as <path> elements (default). - /// Pixel-identical fidelity; no font dependency on viewer. - /// - Path = 0, - - /// - /// Emit <text>/<tspan> elements with font - /// attributes. Editable/smaller but best-effort fidelity. - /// - Text = 1, - } - - /// - /// Encoder parameters controlling SVG output. - /// - public sealed class SvgEncoderParameters - { - /// - /// Gets or sets the text emission mode (default: Path). - /// - public SvgTextMode TextMode { get; set; } = SvgTextMode.Path; - - /// - /// Gets or sets whether to pretty-print with indentation (default: true). - /// - public bool Indent { get; set; } = true; - - /// - /// Gets or sets whether to embed images as inline base64 data URIs - /// (default: true). If false, images are referenced externally. - /// - public bool EmbedImages { get; set; } = true; - - /// - /// Gets or sets the number of decimal places for coordinate output - /// (default: 4). - /// - public int CoordinatePrecision { get; set; } = 4; - - /// - /// Gets the default encoder parameters. - /// - public static SvgEncoderParameters Default => new SvgEncoderParameters(); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgImageReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgImageReader.cs deleted file mode 100644 index 184f9842..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgImageReader.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses SVG <image> elements, resolving data URIs and - /// local file references into objects. - /// - internal static class SvgImageReader - { - /// - /// Reads an <image> element and returns the decoded image - /// plus its destination rectangle, or null if the image cannot be resolved. - /// - public static (Image? Image, RectangleF DestRect)? ReadImage( - Dictionary attrs) - { - string? href = GetValue(attrs, "href") ?? GetValue(attrs, "xlink:href"); - - if (string.IsNullOrWhiteSpace(href)) - return null; - - Image? image = ResolveHref(href); - if (image == null) - return null; - - float x = SvgShapeReader.GetFloat(attrs, "x"); - float y = SvgShapeReader.GetFloat(attrs, "y"); - float w = SvgShapeReader.GetFloat(attrs, "width", image.Width); - float h = SvgShapeReader.GetFloat(attrs, "height", image.Height); - - return (image, new RectangleF(x, y, w, h)); - } - - private static Image? ResolveHref(string href) - { - href = href.Trim(); - - // Data URI: data:image/png;base64,... - if (href.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) - { - return DecodeDataUri(href); - } - - // Local file reference - if (!href.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && - !href.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) - { - try - { - if (File.Exists(href)) - return new Bitmap(href); - } - catch - { - // Ignore file loading errors - } - } - - // Remote URLs are not fetched (security) - return null; - } - - private static Image? DecodeDataUri(string uri) - { - int comma = uri.IndexOf(','); - if (comma < 0) return null; - - string meta = uri.Substring(5, comma - 5); // after "data:" - string data = uri.Substring(comma + 1); - - bool isBase64 = meta.IndexOf("base64", StringComparison.OrdinalIgnoreCase) >= 0; - - byte[] bytes; - if (isBase64) - { - try - { - bytes = Convert.FromBase64String(data); - } - catch - { - return null; - } - } - else - { - // URL-encoded text data — not supported for images - return null; - } - - try - { - using var ms = new MemoryStream(bytes); - return new Bitmap(ms); - } - catch - { - return null; - } - } - - private static string? GetValue(Dictionary attrs, string name) - { - attrs.TryGetValue(name, out string? v); - return v; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgImageWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgImageWriter.cs deleted file mode 100644 index 7542555e..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgImageWriter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.IO; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Writes SVG <image> elements with embedded base64 PNG data. - /// - internal static class SvgImageWriter - { - /// - /// Writes an <image> element for a rect-based DrawImage. - /// - public static void WriteImage(SvgXmlWriter w, Image image, RectangleF destRect) - { - w.WriteStartElement("image"); - w.WriteAttribute("x", destRect.X); - w.WriteAttribute("y", destRect.Y); - w.WriteAttribute("width", destRect.Width); - w.WriteAttribute("height", destRect.Height); - w.WriteAttribute("preserveAspectRatio", "none"); - w.WriteXLinkHref(EmbedImage(image)); - w.WriteEndElement(); - } - - /// - /// Embeds an image as a base64 data URI. The image is encoded as PNG. - /// - public static string EmbedImage(Image image) - { - using var ms = new MemoryStream(); - image.Save(ms, ImageFormat.Png); - byte[] bytes = ms.ToArray(); - return "data:image/png;base64," + Convert.ToBase64String(bytes); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgPathParser.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgPathParser.cs deleted file mode 100644 index bf3c2ee3..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgPathParser.cs +++ /dev/null @@ -1,433 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses an SVG path d attribute (SVG 1.1 §8.3.9) into a - /// . Supports all commands: M/m, L/l, H/h, V/v, - /// C/c, S/s, Q/q, T/t, A/a, Z/z. Relative commands resolve to absolute - /// using the current point. Arcs are converted to cubic Bézier segments. - /// - internal static class SvgPathParser - { - /// - /// Parses the path data string and returns a . - /// - /// The path data string. - /// The fill mode for the resulting path. - /// A built from the parsed commands. - public static GraphicsPath Parse(string? d, FillMode fillMode = FillMode.Alternate) - { - if (string.IsNullOrWhiteSpace(d)) - return new GraphicsPath(fillMode); - - var points = new List(); - var types = new List(); - var tok = new Tokenizer(d); - - PointF cur = PointF.Empty; - PointF start = PointF.Empty; - PointF? prevCtrl = null; - char cmd = '\0'; - bool newSubpath = true; - - while (!tok.IsAtEnd) - { - char c = tok.PeekChar(); - - if (IsCommandLetter(c)) - { - cmd = tok.ReadChar(); - prevCtrl = null; - } - - if (cmd == '\0') - break; - - switch (char.ToUpperInvariant(cmd)) - { - case 'M': - { - bool rel = char.IsLower(cmd); - PointF p = ReadPoint(tok, cur, rel); - if (newSubpath) - { - AddPoint(points, types, p, PathPointType.Start); - start = p; - newSubpath = false; - } - else - { - AddPoint(points, types, p, PathPointType.Line); - } - cur = p; - // Subsequent pairs are implicit L - cmd = rel ? 'l' : 'L'; - prevCtrl = null; - break; - } - - case 'L': - { - bool rel = char.IsLower(cmd); - PointF p = ReadPoint(tok, cur, rel); - AddPoint(points, types, p, PathPointType.Line); - cur = p; - prevCtrl = null; - break; - } - - case 'H': - { - bool rel = char.IsLower(cmd); - float x = ReadNumber(tok); - float y = cur.Y; - float nx = rel ? cur.X + x : x; - AddPoint(points, types, new PointF(nx, y), PathPointType.Line); - cur = new PointF(nx, y); - prevCtrl = null; - break; - } - - case 'V': - { - bool rel = char.IsLower(cmd); - float y = ReadNumber(tok); - float x = cur.X; - float ny = rel ? cur.Y + y : y; - AddPoint(points, types, new PointF(x, ny), PathPointType.Line); - cur = new PointF(x, ny); - prevCtrl = null; - break; - } - - case 'C': - { - bool rel = char.IsLower(cmd); - PointF c1 = ReadPoint(tok, cur, rel); - PointF c2 = ReadPoint(tok, cur, rel); - PointF e = ReadPoint(tok, cur, rel); - AddBezier(points, types, c1, c2, e); - cur = e; - prevCtrl = c2; - break; - } - - case 'S': - { - bool rel = char.IsLower(cmd); - PointF c2 = ReadPoint(tok, cur, rel); - PointF e = ReadPoint(tok, cur, rel); - PointF c1 = prevCtrl.HasValue ? Reflect(prevCtrl.Value, cur) : cur; - AddBezier(points, types, c1, c2, e); - cur = e; - prevCtrl = c2; - break; - } - - case 'Q': - { - bool rel = char.IsLower(cmd); - PointF q1 = ReadPoint(tok, cur, rel); - PointF e = ReadPoint(tok, cur, rel); - // Degree-elevate quadratic to cubic - PointF c1 = Lerp(cur, q1, 2f / 3f); - PointF c2 = Lerp(e, q1, 2f / 3f); - AddBezier(points, types, c1, c2, e); - cur = e; - prevCtrl = q1; - break; - } - - case 'T': - { - bool rel = char.IsLower(cmd); - PointF e = ReadPoint(tok, cur, rel); - PointF q1 = prevCtrl.HasValue ? Reflect(prevCtrl.Value, cur) : cur; - PointF c1 = Lerp(cur, q1, 2f / 3f); - PointF c2 = Lerp(e, q1, 2f / 3f); - AddBezier(points, types, c1, c2, e); - cur = e; - prevCtrl = q1; - break; - } - - case 'A': - { - bool rel = char.IsLower(cmd); - float rx = ReadNumber(tok); - float ry = ReadNumber(tok); - float angle = ReadNumber(tok); - bool large = ReadFlag(tok); - bool sweep = ReadFlag(tok); - PointF p = ReadPoint(tok, cur, rel); - ArcToBezier(points, types, cur, p, rx, ry, angle, large, sweep); - cur = p; - prevCtrl = null; - break; - } - - case 'Z': - { - if (types.Count > 0) - types[types.Count - 1] |= (byte)PathPointType.CloseSubpath; - cur = start; - newSubpath = true; - prevCtrl = null; - tok.SkipSeparators(); - break; - } - - default: - // Unknown command: skip rest - goto done; - } - } - - done: - if (points.Count == 0) - return new GraphicsPath(fillMode); - - return new GraphicsPath(points.ToArray(), types.ToArray(), fillMode); - } - - // ── Helpers ──────────────────────────────────────────────────────────── - - private static bool IsCommandLetter(char c) - { - return "MmLlHhVvCcSsQqTtAaZz".IndexOf(c) >= 0; - } - - private static void AddPoint(List points, List types, PointF p, PathPointType type) - { - points.Add(p); - types.Add((byte)type); - } - - private static void AddBezier(List points, List types, - PointF c1, PointF c2, PointF e) - { - points.Add(c1); types.Add((byte)PathPointType.Bezier); - points.Add(c2); types.Add((byte)PathPointType.Bezier); - points.Add(e); types.Add((byte)PathPointType.Bezier); - } - - private static PointF Reflect(PointF ctrl, PointF pivot) - => new PointF(2f * pivot.X - ctrl.X, 2f * pivot.Y - ctrl.Y); - - private static PointF Lerp(PointF a, PointF b, float t) - => new PointF(a.X + t * (b.X - a.X), a.Y + t * (b.Y - a.Y)); - - private static PointF ReadPoint(Tokenizer tok, PointF cur, bool rel) - { - float x = ReadNumber(tok); - float y = ReadNumber(tok); - return rel ? new PointF(cur.X + x, cur.Y + y) : new PointF(x, y); - } - - private static float ReadNumber(Tokenizer tok) => tok.ReadNumber(); - - private static bool ReadFlag(Tokenizer tok) => tok.ReadFlag(); - - // ── Arc-to-Bézier conversion (SVG 1.1 impl. note F.6.5) ─────────────── - - private static void ArcToBezier(List points, List types, - PointF start, PointF end, float rx, float ry, float angleDeg, - bool largeArc, bool sweep) - { - if (rx == 0 || ry == 0) - { - AddPoint(points, types, end, PathPointType.Line); - return; - } - - // If endpoints are identical, arc is a no-op - if (start.X == end.X && start.Y == end.Y) - return; - - rx = Math.Abs(rx); - ry = Math.Abs(ry); - - double angle = angleDeg * Math.PI / 180.0; - double cosA = Math.Cos(angle); - double sinA = Math.Sin(angle); - - // Step 1: compute (x1', y1') - double dx = (start.X - end.X) / 2.0; - double dy = (start.Y - end.Y) / 2.0; - double x1p = cosA * dx + sinA * dy; - double y1p = -sinA * dx + cosA * dy; - - // Step 2: compute (cx', cy') - double rx2 = rx * rx; - double ry2 = ry * ry; - double x1p2 = x1p * x1p; - double y1p2 = y1p * y1p; - - double lambda = (x1p2 / rx2) + (y1p2 / ry2); - if (lambda > 1.0) - { - double s = Math.Sqrt(lambda); - rx *= (float)s; - ry *= (float)s; - rx2 = rx * rx; - ry2 = ry * ry; - } - - double sign = (largeArc != sweep) ? 1.0 : -1.0; - double num = rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2; - double den = rx2 * y1p2 + ry2 * x1p2; - den = Math.Max(den, 1e-12); - double coef = sign * Math.Sqrt(Math.Max(0.0, num / den)); - double cxp = coef * (rx * y1p / ry); - double cyp = -coef * (ry * x1p / rx); - - // Step 3: compute (cx, cy) - double cx = cosA * cxp - sinA * cyp + (start.X + end.X) / 2.0; - double cy = sinA * cxp + cosA * cyp + (start.Y + end.Y) / 2.0; - - // Step 4: compute theta1 and delta-theta - double ux = (x1p - cxp) / rx; - double uy = (y1p - cyp) / ry; - double vx = (-x1p - cxp) / rx; - double vy = (-y1p - cyp) / ry; - - double theta1 = VectorAngle(1, 0, ux, uy); - double delta = VectorAngle(ux, uy, vx, vy); - - if (!sweep && delta > 0) - delta -= 2 * Math.PI; - else if (sweep && delta < 0) - delta += 2 * Math.PI; - - // Split into segments of at most 90° - int segments = Math.Max(1, (int)Math.Ceiling(Math.Abs(delta) / (Math.PI / 2))); - double segAngle = delta / segments; - - for (int i = 0; i < segments; i++) - { - double a0 = theta1 + segAngle * i; - double a1 = theta1 + segAngle * (i + 1); - - // Bézier approximation of an elliptical arc segment - double t = 4.0 / 3.0 * Math.Tan(segAngle / 4.0); - - double cos0 = Math.Cos(a0), sin0 = Math.Sin(a0); - double cos1 = Math.Cos(a1), sin1 = Math.Sin(a1); - - // Points on the unit circle, then scale/rotate/translate - double p0x = cos0, p0y = sin0; - double p1x = cos0 + t * sin0, p1y = sin0 - t * cos0; - double p2x = cos1 - t * sin1, p2y = sin1 + t * cos1; - double p3x = cos1, p3y = sin1; - - // Scale by rx, ry - p0x *= rx; p0y *= ry; - p1x *= rx; p1y *= ry; - p2x *= rx; p2y *= ry; - p3x *= rx; p3y *= ry; - - // Rotate by angle - double rp0x = cosA * p0x - sinA * p0y; - double rp0y = sinA * p0x + cosA * p0y; - double rp1x = cosA * p1x - sinA * p1y; - double rp1y = sinA * p1x + cosA * p1y; - double rp2x = cosA * p2x - sinA * p2y; - double rp2y = sinA * p2x + cosA * p2y; - double rp3x = cosA * p3x - sinA * p3y; - double rp3y = sinA * p3x + cosA * p3y; - - // Translate by (cx, cy) - var c1 = new PointF((float)(rp1x + cx), (float)(rp1y + cy)); - var c2 = new PointF((float)(rp2x + cx), (float)(rp2y + cy)); - var ep = new PointF((float)(rp3x + cx), (float)(rp3y + cy)); - - AddBezier(points, types, c1, c2, ep); - } - } - - private static double VectorAngle(double ux, double uy, double vx, double vy) - { - double dot = ux * vx + uy * vy; - double len = Math.Sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); - if (len == 0) return 0; - double cos = Math.Max(-1.0, Math.Min(1.0, dot / len)); - double a = Math.Acos(cos); - if (ux * vy - uy * vx < 0) - a = -a; - return a; - } - - // ── Tokenizer ───────────────────────────────────────────────────────── - - private sealed class Tokenizer - { - private readonly string _s; - private int _i; - - public Tokenizer(string s) { _s = s; _i = 0; } - - public bool IsAtEnd => _i >= _s.Length; - - public char PeekChar() => _i < _s.Length ? _s[_i] : '\0'; - - public char ReadChar() => _s[_i++]; - - public void SkipSeparators() - { - while (_i < _s.Length && (char.IsWhiteSpace(_s[_i]) || _s[_i] == ',')) - _i++; - } - - public float ReadNumber() - { - SkipSeparators(); - int start = _i; - - if (_i < _s.Length && (_s[_i] == '+' || _s[_i] == '-')) _i++; - while (_i < _s.Length && char.IsDigit(_s[_i])) _i++; - if (_i < _s.Length && _s[_i] == '.') - { - _i++; - while (_i < _s.Length && char.IsDigit(_s[_i])) _i++; - } - if (_i < _s.Length && (_s[_i] == 'e' || _s[_i] == 'E')) - { - _i++; - if (_i < _s.Length && (_s[_i] == '+' || _s[_i] == '-')) _i++; - while (_i < _s.Length && char.IsDigit(_s[_i])) _i++; - } - - if (_i == start) - { - _i++; - return 0f; - } - - float.TryParse(_s.Substring(start, _i - start), NumberStyles.Float, - CultureInfo.InvariantCulture, out float val); - return val; - } - - public bool ReadFlag() - { - // Flags are exactly one character ('0' or '1') with no separators - // consumed before them; but whitespace between args is allowed. - SkipSeparators(); - if (_i >= _s.Length) return false; - char c = _s[_i]; - if (c == '0' || c == '1') - { - _i++; - return c == '1'; - } - // Tolerant: try reading a number - return ReadNumber() != 0f; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgPathWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgPathWriter.cs deleted file mode 100644 index 16f81d68..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgPathWriter.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Globalization; -using System.Text; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Converts a (points + PathPointType flags) into - /// SVG path data (M/L/C/Z). Arcs and ellipses are - /// already flattened to Béziers at path-build time, so only these commands - /// are needed for output. - /// - internal static class SvgPathWriter - { - /// - /// Writes the path data string for the given path, using up to - /// decimal places. - /// - public static string WritePathData(GraphicsPath path, int precision = 4) - { - if (path == null || path.PointCount == 0) - return string.Empty; - - var pts = path.PathPoints; - var types = path.PathTypes; - var sb = new StringBuilder(); - var fmt = new NumberFormat(precision); - int i = 0; - - while (i < pts.Length) - { - byte type = types[i]; - PathPointType baseType = (PathPointType)(type & (byte)PathPointType.PathTypeMask); - - switch (baseType) - { - case PathPointType.Start: - sb.Append('M').Append(fmt.Num(pts[i].X)).Append(' ').Append(fmt.Num(pts[i].Y)); - i++; - // Subsequent implicit lineto until next Start/Bezier/Close - while (i < pts.Length) - { - byte t2 = types[i]; - PathPointType bt2 = (PathPointType)(t2 & (byte)PathPointType.PathTypeMask); - if (bt2 == PathPointType.Start) break; - if (bt2 == PathPointType.Bezier) break; - if ((t2 & (byte)PathPointType.CloseSubpath) != 0 && bt2 == PathPointType.Line) - { - // last point of subpath, line-to then close - sb.Append('L').Append(fmt.Num(pts[i].X)).Append(' ').Append(fmt.Num(pts[i].Y)); - sb.Append('Z'); - i++; - break; - } - sb.Append('L').Append(fmt.Num(pts[i].X)).Append(' ').Append(fmt.Num(pts[i].Y)); - if ((t2 & (byte)PathPointType.CloseSubpath) != 0) - { - sb.Append('Z'); - i++; - break; - } - i++; - } - break; - - case PathPointType.Line: - sb.Append('L').Append(fmt.Num(pts[i].X)).Append(' ').Append(fmt.Num(pts[i].Y)); - if ((type & (byte)PathPointType.CloseSubpath) != 0) - sb.Append('Z'); - i++; - break; - - case PathPointType.Bezier: - // 3 points per cubic Bézier: ctrl1, ctrl2, end - if (i + 2 < pts.Length) - { - sb.Append('C') - .Append(fmt.Num(pts[i].X)).Append(' ').Append(fmt.Num(pts[i].Y)).Append(' ') - .Append(fmt.Num(pts[i + 1].X)).Append(' ').Append(fmt.Num(pts[i + 1].Y)).Append(' ') - .Append(fmt.Num(pts[i + 2].X)).Append(' ').Append(fmt.Num(pts[i + 2].Y)); - if ((types[i + 2] & (byte)PathPointType.CloseSubpath) != 0) - sb.Append('Z'); - i += 3; - } - else - { - i++; - } - break; - - default: - i++; - break; - } - } - - return sb.ToString(); - } - - /// Helper to format SVG path numbers compactly. - private readonly struct NumberFormat - { - private readonly int _precision; - public NumberFormat(int precision) { _precision = Math.Max(0, precision); } - - public string Num(float v) - { - if (float.IsNaN(v) || float.IsInfinity(v)) v = 0f; - string s = v.ToString("F" + _precision, CultureInfo.InvariantCulture); - if (s.IndexOf('.') >= 0) - { - s = s.TrimEnd('0').TrimEnd('.'); - if (s.Length == 0 || s == "-") s = "0"; - } - return s; - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgPenWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgPenWriter.cs deleted file mode 100644 index b7f65424..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgPenWriter.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Globalization; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Pens; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Writes SVG stroke attributes for a . - /// - internal static class SvgPenWriter - { - /// - /// Writes stroke-related attributes onto the current element. - /// Writes: stroke, stroke-width, stroke-opacity, stroke-linecap, - /// stroke-linejoin, stroke-miterlimit, stroke-dasharray, stroke-dashoffset. - /// - public static void WriteStroke(SvgXmlWriter w, Pen? pen, SvgDefTable defs) - { - if (pen == null) - { - w.WriteAttribute("stroke", "none"); - return; - } - - // stroke color or brush ref - if (pen.PenType == PenType.SolidColor) - { - w.WriteAttribute("stroke", SvgBrushWriter.ColorToCss(pen.Color)); - if (pen.Color.A < 255) - w.WriteAttribute("stroke-opacity", Fmt(pen.Color.A / 255f)); - } - else - { - string? id = defs?.RegisterBrush(pen.Brush); - w.WriteAttribute("stroke", id != null ? "url(#" + id + ")" : SvgBrushWriter.ColorToCss(pen.Color)); - } - - // stroke-width (emit only if non-default for compactness, but always - // emit to be safe since SVG default is 1) - w.WriteAttribute("stroke-width", Fmt(pen.Width)); - - // line caps - w.WriteAttributeOptional("stroke-linecap", LineCapToString(pen.StartCap), "butt"); - if (pen.StartCap != pen.EndCap) - w.WriteAttributeOptional("stroke-linecap", LineCapToString(pen.EndCap), "butt"); - - // line join - w.WriteAttributeOptional("stroke-linejoin", LineJoinToString(pen.LineJoin), "miter"); - - // miter limit (SVG default is 4; emit if different) - if (System.Math.Abs(pen.MiterLimit - 10f) > 0.001f && System.Math.Abs(pen.MiterLimit - 4f) > 0.001f) - w.WriteAttribute("stroke-miterlimit", Fmt(pen.MiterLimit)); - - // dash style - WriteDashStyle(w, pen); - - // dash offset - if (pen.DashOffset != 0f) - w.WriteAttribute("stroke-dashoffset", Fmt(pen.DashOffset)); - } - - private static void WriteDashStyle(SvgXmlWriter w, Pen pen) - { - switch (pen.DashStyle) - { - case DashStyle.Solid: - // default, no dasharray - break; - case DashStyle.Dash: - w.WriteAttribute("stroke-dasharray", "4 2"); - break; - case DashStyle.Dot: - w.WriteAttribute("stroke-dasharray", "1 2"); - break; - case DashStyle.DashDot: - w.WriteAttribute("stroke-dasharray", "4 2 1 2"); - break; - case DashStyle.DashDotDot: - w.WriteAttribute("stroke-dasharray", "4 2 1 2 1 2"); - break; - case DashStyle.Custom: - var pattern = pen.DashPattern; - if (pattern != null && pattern.Length > 0) - { - var sb = new System.Text.StringBuilder(); - for (int i = 0; i < pattern.Length; i++) - { - if (i > 0) sb.Append(' '); - sb.Append(Fmt(pattern[i] * pen.Width)); - } - w.WriteAttribute("stroke-dasharray", sb.ToString()); - } - break; - } - } - - private static string LineCapToString(LineCap cap) - { - return cap switch - { - LineCap.Flat => "butt", - LineCap.Round => "round", - LineCap.Square => "square", - LineCap.Triangle => "butt", // approximated - _ => "butt", - }; - } - - private static string LineJoinToString(LineJoin join) - { - return join switch - { - LineJoin.Miter => "miter", - LineJoin.Bevel => "bevel", - LineJoin.Round => "round", - _ => "miter", - }; - } - - private static string Fmt(float v) - { - if (float.IsNaN(v) || float.IsInfinity(v)) v = 0f; - string s = v.ToString("F4", CultureInfo.InvariantCulture); - if (s.IndexOf('.') >= 0) - s = s.TrimEnd('0').TrimEnd('.'); - if (s.Length == 0 || s == "-") s = "0"; - return s; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgReader.cs deleted file mode 100644 index f7ab9fbe..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgReader.cs +++ /dev/null @@ -1,615 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Colors; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Pens; -using MiniSoftware.Drawing.Rendering; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Top-level SVG reader: parses an SVG document from a stream using a - /// forward-only and produces a - /// by driving a . - /// - internal static class SvgReader - { - /// - /// Reads an SVG document from the specified stream and returns a - /// . - /// - public static VectorScene Read(Stream stream) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - - var settings = new XmlReaderSettings - { - DtdProcessing = DtdProcessing.Ignore, - IgnoreComments = true, - IgnoreWhitespace = true, - }; - - using var reader = XmlReader.Create(stream, settings); - var ctx = new SvgReadContext(); - ctx.Parse(reader); - return ctx.Scene; - } - - /// - /// Reads an SVG document from a string. - /// - public static VectorScene ReadString(string svg) - { - using var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(svg)); - return Read(ms); - } - } - - /// - /// Internal parsing context that maintains the state stack, defs table, - /// and the recording graphics surface. - /// - internal sealed class SvgReadContext : IDisposable - { - public VectorScene Scene { get; } = new VectorScene(); - public Dictionary Defs { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); - public SvgStyle CurrentStyle { get; private set; } = new SvgStyle(); - - private RecordingGraphics? _graphics; - private readonly Stack<(SvgStyle Style, GraphicsState? State)> _stateStack - = new Stack<(SvgStyle, GraphicsState?)>(); - - private bool _disposed; - - // ── Top-level parse ──────────────────────────────────────────────────── - - public void Parse(XmlReader reader) - { - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.Element) - { - string name = reader.LocalName; - if (name.Equals("svg", StringComparison.OrdinalIgnoreCase)) - { - ReadRootSvg(reader); - } - else if (_graphics != null) - { - ReadElement(reader, name); - } - } - } - } - - // ── Root ──────────────────────────────────────────────────────── - - private void ReadRootSvg(XmlReader reader) - { - var style = new SvgStyle(); - var attrs = SvgStyleParser.ApplyAttributes(reader, style); - - // Dimensions - int width = ResolveDimension(attrs, "width", 0); - int height = ResolveDimension(attrs, "height", 0); - - // If no width/height, use viewBox - if (width <= 0 || height <= 0) - { - string? viewBox = GetValue(attrs, "viewBox"); - if (!string.IsNullOrWhiteSpace(viewBox)) - { - var parts = viewBox.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length >= 4) - { - float vbW = SvgStyleParser.ParseFloat(parts[2]); - float vbH = SvgStyleParser.ParseFloat(parts[3]); - if (width <= 0) width = (int)Math.Round(vbW); - if (height <= 0) height = (int)Math.Round(vbH); - } - } - } - - if (width <= 0) width = 800; - if (height <= 0) height = 600; - - Scene.Width = width; - Scene.Height = height; - - _graphics = new RecordingGraphics(Scene, width, height); - CurrentStyle = style; - - // Root transform - string? transform = GetValue(attrs, "transform"); - if (!string.IsNullOrWhiteSpace(transform)) - { - var m = SvgTransformParser.Parse(transform); - _graphics.MultiplyTransform(m, MatrixOrder.Prepend); - m.Dispose(); - } - - // Process children - if (!reader.IsEmptyElement) - { - ReadChildren(reader); - } - } - - // ── Element dispatch ────────────────────────────────────────────────── - - private void ReadElement(XmlReader reader, string name) - { - // Save current style and apply this element's attributes - var savedStyle = CurrentStyle; - var style = savedStyle.Clone(); - var attrs = SvgStyleParser.ApplyAttributes(reader, style); - - // Check display/visibility - if (style.Display.Equals("none", StringComparison.OrdinalIgnoreCase)) - { - SkipChildren(reader); - CurrentStyle = savedStyle; - return; - } - - switch (name) - { - case "g": - PushGroup(reader, attrs, style, savedStyle); - break; - - case "defs": - ReadDefs(reader); - CurrentStyle = savedStyle; - break; - - case "linearGradient": - case "radialGradient": - ReadGradientDef(reader, name == "radialGradient"); - CurrentStyle = savedStyle; - break; - - case "clipPath": - ReadClipPathDef(reader); - CurrentStyle = savedStyle; - break; - - case "use": - ReadUse(reader, attrs, style); - CurrentStyle = savedStyle; - break; - - case "image": - ReadImageElement(attrs, style); - SkipChildren(reader); - CurrentStyle = savedStyle; - break; - - case "text": - ReadTextElement(reader, style); - CurrentStyle = savedStyle; - break; - - case "rect": - case "circle": - case "ellipse": - case "line": - case "polyline": - case "polygon": - case "path": - ReadShapeElement(name, attrs, style); - SkipChildren(reader); - CurrentStyle = savedStyle; - break; - - case "title": - case "desc": - case "metadata": - case "symbol": - case "mask": - // Skip non-rendering elements - SkipChildren(reader); - CurrentStyle = savedStyle; - break; - - default: - // Unknown element: skip gracefully - SkipChildren(reader); - CurrentStyle = savedStyle; - break; - } - } - - // ── group ──────────────────────────────────────────────────────── - - private void PushGroup(XmlReader reader, Dictionary attrs, - SvgStyle style, SvgStyle savedStyle) - { - GraphicsState? state = null; - - // Save graphics state for transform/clip - state = _graphics!.Save(); - CurrentStyle = style; - - // Apply transform - string? transform = GetValue(attrs, "transform"); - if (!string.IsNullOrWhiteSpace(transform)) - { - var m = SvgTransformParser.Parse(transform); - _graphics.MultiplyTransform(m, MatrixOrder.Prepend); - m.Dispose(); - } - - // Apply clip-path - ApplyClipPath(style.ClipPath); - - _stateStack.Push((savedStyle, state)); - - // Process children - if (!reader.IsEmptyElement) - { - ReadChildren(reader); - } - - // Pop: restore state - _stateStack.Pop(); - CurrentStyle = savedStyle; - _graphics.Restore(state!); - } - - // ── ──────────────────────────────────────────────────────────── - - private void ReadDefs(XmlReader reader) - { - if (reader.IsEmptyElement) return; - - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement) break; - if (reader.NodeType != XmlNodeType.Element) continue; - - string name = reader.LocalName; - switch (name) - { - case "linearGradient": - ReadGradientDef(reader, isRadial: false); - break; - case "radialGradient": - ReadGradientDef(reader, isRadial: true); - break; - case "clipPath": - ReadClipPathDef(reader); - break; - default: - // Store other defs (shapes for ) by id - string? id = reader.GetAttribute("id"); - if (!string.IsNullOrEmpty(id)) - { - StoreUseTarget(reader, id, name); - } - else - { - SkipChildren(reader); - } - break; - } - } - } - - private void ReadGradientDef(XmlReader reader, bool isRadial) - { - var gd = SvgBrushReader.ReadGradient(reader, isRadial); - if (!string.IsNullOrEmpty(gd.Id)) - Defs[gd.Id] = gd; - } - - private void ReadClipPathDef(XmlReader reader) - { - string? id = reader.GetAttribute("id"); - var clipPath = SvgClipReader.ReadClipPath(reader); - if (!string.IsNullOrEmpty(id)) - Defs[id] = clipPath; - } - - // ── ────────────────────────────────────────────────────────────── - - private void StoreUseTarget(XmlReader reader, string id, string elementName) - { - // For shapes in defs, parse and store the path + style - var style = new SvgStyle(); - var attrs = SvgStyleParser.ApplyAttributes(reader, style); - var path = SvgShapeReader.ReadShape(elementName, attrs, style); - if (path != null) - { - Defs[id] = (path, style); - } - SkipChildren(reader); - } - - private void ReadUse(XmlReader reader, Dictionary attrs, SvgStyle style) - { - string? href = GetValue(attrs, "href") ?? GetValue(attrs, "xlink:href"); - if (string.IsNullOrWhiteSpace(href)) return; - - // Extract id from url(#id) or #id - string id = href.Trim(); - if (id.StartsWith("#")) id = id.Substring(1); - - if (!Defs.TryGetValue(id, out var def)) - return; - - // Apply use's transform (x, y → translate, plus transform attr) - GraphicsState? state = _graphics!.Save(); - - float useX = SvgShapeReader.GetFloat(attrs, "x"); - float useY = SvgShapeReader.GetFloat(attrs, "y"); - if (useX != 0 || useY != 0) - _graphics.TranslateTransform(useX, useY, MatrixOrder.Prepend); - - string? transform = GetValue(attrs, "transform"); - if (!string.IsNullOrWhiteSpace(transform)) - { - var m = SvgTransformParser.Parse(transform); - _graphics.MultiplyTransform(m, MatrixOrder.Prepend); - m.Dispose(); - } - - if (def is ValueTuple shapeDef) - { - // Draw the referenced shape with the use's style (or the shape's style) - var effectiveStyle = style.Clone(); - // Use the shape's own style where the use doesn't override - // (simplified: use current style) - DrawShape(shapeDef.Item1, effectiveStyle); - } - else if (def is GraphicsPath clipPath) - { - DrawShape(clipPath, style); - } - - _graphics.Restore(state); - } - - // ── Shape elements ───────────────────────────────────────────────────── - - private void ReadShapeElement(string name, Dictionary attrs, SvgStyle style) - { - GraphicsPath? path = SvgShapeReader.ReadShape(name, attrs, style); - if (path == null || path.PointCount == 0) return; - - DrawShape(path, style); - } - - private void DrawShape(GraphicsPath path, SvgStyle style) - { - float fillOpacity = SvgStyleParser.ParseFloat(style.FillOpacity, 1f) * - SvgStyleParser.ParseFloat(style.Opacity, 1f); - float strokeOpacity = SvgStyleParser.ParseFloat(style.StrokeOpacity, 1f) * - SvgStyleParser.ParseFloat(style.Opacity, 1f); - - // Fill - if (style.HasFill) - { - Brush? fillBrush = SvgBrushReader.ResolveBrush(style.Fill, Defs); - fillBrush = SvgBrushReader.ApplyOpacity(fillBrush, fillOpacity); - if (fillBrush != null) - { - FillMode fillMode = string.Equals(style.FillRule, "evenodd", - StringComparison.OrdinalIgnoreCase) - ? FillMode.Alternate : FillMode.Winding; - _graphics!.FillPath(fillBrush, path, fillMode); - fillBrush.Dispose(); - } - } - - // Stroke - if (style.HasStroke) - { - Pen? pen = CreatePen(style, strokeOpacity); - if (pen != null) - { - _graphics!.DrawPath(pen, path); - pen.Dispose(); - } - } - } - - private Pen? CreatePen(SvgStyle style, float opacity) - { - Brush? strokeBrush = SvgBrushReader.ResolveBrush(style.Stroke, Defs); - strokeBrush = SvgBrushReader.ApplyOpacity(strokeBrush, opacity); - if (strokeBrush == null) return null; - - float width = SvgStyleParser.ParseFloat(style.StrokeWidth, 1f); - var pen = new Pen(strokeBrush, width); - - // Line cap - pen.StartCap = ParseLineCap(style.StrokeLinecap); - pen.EndCap = pen.StartCap; - - // Line join - pen.LineJoin = style.StrokeLinejoin.ToLowerInvariant() switch - { - "round" => LineJoin.Round, - "bevel" => LineJoin.Bevel, - _ => LineJoin.Miter, - }; - - // Miter limit - pen.MiterLimit = SvgStyleParser.ParseFloat(style.StrokeMiterlimit, 4f); - - // Dash array - if (!string.IsNullOrWhiteSpace(style.StrokeDashArray) && - !style.StrokeDashArray.Equals("none", StringComparison.OrdinalIgnoreCase)) - { - var dashParts = style.StrokeDashArray.Split(new[] { ' ', ',' }, - StringSplitOptions.RemoveEmptyEntries); - if (dashParts.Length > 0) - { - var pattern = new float[dashParts.Length]; - bool allZero = true; - for (int i = 0; i < dashParts.Length; i++) - { - pattern[i] = SvgStyleParser.ParseFloat(dashParts[i], 0f); - if (pattern[i] > 0) allZero = false; - } - if (!allZero) - { - pen.DashStyle = DashStyle.Custom; - pen.DashPattern = pattern; - } - } - } - - // Dash offset - float dashOffset = SvgStyleParser.ParseFloat(style.StrokeDashoffset, 0f); - if (dashOffset != 0f) - pen.DashOffset = dashOffset; - - strokeBrush.Dispose(); - return pen; - } - - private static LineCap ParseLineCap(string s) - { - return s.ToLowerInvariant() switch - { - "round" => LineCap.Round, - "square" => LineCap.Square, - _ => LineCap.Flat, - }; - } - - // ── ──────────────────────────────────────────────────────────── - - private void ReadImageElement(Dictionary attrs, SvgStyle style) - { - var result = SvgImageReader.ReadImage(attrs); - if (result == null) return; - - var (image, destRect) = result.Value; - if (image == null) return; - - GraphicsState? state = null; - bool needRestore = false; - - string? transform = GetValue(attrs, "transform"); - if (!string.IsNullOrWhiteSpace(transform)) - { - state = _graphics!.Save(); - needRestore = true; - var m = SvgTransformParser.Parse(transform); - _graphics.MultiplyTransform(m, MatrixOrder.Prepend); - m.Dispose(); - } - - var srcRect = new RectangleF(0, 0, image.Width, image.Height); - _graphics!.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel, null); - - if (needRestore) - _graphics.Restore(state!); - - image.Dispose(); - } - - // ── ───────────────────────────────────────────────────────────── - - private void ReadTextElement(XmlReader reader, SvgStyle style) - { - var textReader = new SvgTextReader(Defs); - var result = textReader.ReadText(reader, style); - if (result == null) return; - - var (text, font, brush, layoutRect, format) = result.Value; - if (brush != null) - { - _graphics!.DrawString(text, font, brush, layoutRect, format); - brush.Dispose(); - } - font.Dispose(); - format?.Dispose(); - } - - // ── Clip path ────────────────────────────────────────────────────────── - - private void ApplyClipPath(string? clipPathRef) - { - if (string.IsNullOrWhiteSpace(clipPathRef) || - clipPathRef.Equals("none", StringComparison.OrdinalIgnoreCase)) - return; - - // Extract id from url(#id) - string id = clipPathRef; - int hash = id.IndexOf('#'); - if (hash >= 0) - { - int end = id.IndexOf(')', hash); - id = end >= 0 - ? id.Substring(hash + 1, end - hash - 1) - : id.Substring(hash + 1); - } - - if (Defs.TryGetValue(id, out var def)) - { - if (def is GraphicsPath clipPath) - { - using var region = new Region(clipPath); - _graphics!.IntersectClip(region); - } - } - } - - // ── Children reading ─────────────────────────────────────────────────── - - private void ReadChildren(XmlReader reader) - { - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement) break; - if (reader.NodeType == XmlNodeType.Element) - { - ReadElement(reader, reader.LocalName); - } - } - } - - private static void SkipChildren(XmlReader reader) - { - if (reader.IsEmptyElement) return; - int depth = reader.Depth; - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) - break; - } - } - - // ── Helpers ──────────────────────────────────────────────────────────── - - private static int ResolveDimension(Dictionary attrs, string name, int defaultVal) - { - string? val = GetValue(attrs, name); - if (string.IsNullOrWhiteSpace(val)) return defaultVal; - return (int)Math.Round(SvgStyleParser.ParseLength(val, defaultVal)); - } - - private static string? GetValue(Dictionary attrs, string name) - { - attrs.TryGetValue(name, out string? v); - return v; - } - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - _graphics?.Dispose(); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgShapeReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgShapeReader.cs deleted file mode 100644 index ac466b26..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgShapeReader.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses SVG shape elements (<rect>, <circle>, - /// <ellipse>, <line>, <polyline>, - /// <polygon>, <path>) into - /// objects. - /// - internal static class SvgShapeReader - { - /// - /// Parses a shape element from its attributes and returns the - /// corresponding , or null if the element - /// is not a recognized shape. - /// - public static GraphicsPath? ReadShape(string elementName, - Dictionary attrs, SvgStyle style) - { - switch (elementName) - { - case "rect": return ReadRect(attrs); - case "circle": return ReadCircle(attrs); - case "ellipse": return ReadEllipse(attrs); - case "line": return ReadLine(attrs); - case "polyline": return ReadPolyline(attrs, close: false); - case "polygon": return ReadPolyline(attrs, close: true); - case "path": return ReadPath(attrs, style); - default: return null; - } - } - - /// - /// Parses <rect x y width height rx ry/>. - /// Rounded corners (rx/ry) are approximated with arcs. - /// - public static GraphicsPath ReadRect(Dictionary attrs) - { - float x = GetFloat(attrs, "x"); - float y = GetFloat(attrs, "y"); - float w = GetFloat(attrs, "width"); - float h = GetFloat(attrs, "height"); - float rx = GetFloat(attrs, "rx", 0f); - float ry = GetFloat(attrs, "ry", rx); - - var path = new GraphicsPath(); - - if (rx <= 0 && ry <= 0) - { - path.AddRectangle(new RectangleF(x, y, w, h)); - } - else - { - // Rounded rectangle using 4-point AddBezier (start, c1, c2, end) - float erx = Math.Min(rx, w / 2f); - float ery = Math.Min(ry, h / 2f); - float kappa = 0.5522847498f; - float kx = erx * kappa; - float ky = ery * kappa; - - // Top edge - path.AddLine(new PointF(x + erx, y), new PointF(x + w - erx, y)); - - // Top-right corner: start=(x+w-erx,y) → end=(x+w, y+ery) - path.AddBezier( - new PointF(x + w - erx, y), - new PointF(x + w - erx + kx, y), - new PointF(x + w, y + ery - ky), - new PointF(x + w, y + ery)); - - // Right edge - path.AddLine(new PointF(x + w, y + ery), new PointF(x + w, y + h - ery)); - - // Bottom-right corner: start=(x+w, y+h-ery) → end=(x+w-erx, y+h) - path.AddBezier( - new PointF(x + w, y + h - ery), - new PointF(x + w, y + h - ery + ky), - new PointF(x + w - erx + kx, y + h), - new PointF(x + w - erx, y + h)); - - // Bottom edge - path.AddLine(new PointF(x + w - erx, y + h), new PointF(x + erx, y + h)); - - // Bottom-left corner: start=(x+erx, y+h) → end=(x, y+h-ery) - path.AddBezier( - new PointF(x + erx, y + h), - new PointF(x + erx - kx, y + h), - new PointF(x, y + h - ery + ky), - new PointF(x, y + h - ery)); - - // Left edge - path.AddLine(new PointF(x, y + h - ery), new PointF(x, y + ery)); - - // Top-left corner: start=(x, y+ery) → end=(x+erx, y) - path.AddBezier( - new PointF(x, y + ery), - new PointF(x, y + ery - ky), - new PointF(x + erx - kx, y), - new PointF(x + erx, y)); - - path.CloseFigure(); - } - - return path; - } - - /// - /// Parses <circle cx cy r/>. - /// - public static GraphicsPath ReadCircle(Dictionary attrs) - { - float cx = GetFloat(attrs, "cx"); - float cy = GetFloat(attrs, "cy"); - float r = GetFloat(attrs, "r"); - - var path = new GraphicsPath(); - path.AddEllipse(cx - r, cy - r, r * 2, r * 2); - return path; - } - - /// - /// Parses <ellipse cx cy rx ry/>. - /// - public static GraphicsPath ReadEllipse(Dictionary attrs) - { - float cx = GetFloat(attrs, "cx"); - float cy = GetFloat(attrs, "cy"); - float rx = GetFloat(attrs, "rx"); - float ry = GetFloat(attrs, "ry"); - - var path = new GraphicsPath(); - path.AddEllipse(cx - rx, cy - ry, rx * 2, ry * 2); - return path; - } - - /// - /// Parses <line x1 y1 x2 y2/>. - /// - public static GraphicsPath ReadLine(Dictionary attrs) - { - float x1 = GetFloat(attrs, "x1"); - float y1 = GetFloat(attrs, "y1"); - float x2 = GetFloat(attrs, "x2"); - float y2 = GetFloat(attrs, "y2"); - - var path = new GraphicsPath(); - path.AddLine(new PointF(x1, y1), new PointF(x2, y2)); - return path; - } - - /// - /// Parses <polyline points="x1,y1 x2,y2 ..."/> or - /// <polygon> (same but closed). - /// - public static GraphicsPath ReadPolyline(Dictionary attrs, bool close) - { - string? pointsStr = GetValue(attrs, "points"); - var points = ParsePoints(pointsStr); - - var path = new GraphicsPath(); - if (points.Length >= 2) - { - path.AddLines(points); - if (close) - path.CloseFigure(); - } - return path; - } - - /// - /// Parses <path d="..."/>. - /// - public static GraphicsPath ReadPath(Dictionary attrs, SvgStyle style) - { - string? d = GetValue(attrs, "d"); - FillMode fillMode = string.Equals(GetValue(attrs, "fill-rule") ?? style.FillRule, - "evenodd", StringComparison.OrdinalIgnoreCase) - ? FillMode.Alternate - : FillMode.Winding; - return SvgPathParser.Parse(d, fillMode); - } - - // ── Helpers ──────────────────────────────────────────────────────────── - - internal static PointF[] ParsePoints(string? s) - { - if (string.IsNullOrWhiteSpace(s)) - return Array.Empty(); - - var list = new List(); - var tokens = s.Trim().Split(new[] { ' ', '\t', '\n', '\r', ',' }, - StringSplitOptions.RemoveEmptyEntries); - - // If even number of tokens, treat as x,y pairs - int i = 0; - while (i + 1 < tokens.Length) - { - if (float.TryParse(tokens[i], NumberStyles.Float, - CultureInfo.InvariantCulture, out float x) && - float.TryParse(tokens[i + 1], NumberStyles.Float, - CultureInfo.InvariantCulture, out float y)) - { - list.Add(new PointF(x, y)); - } - i += 2; - } - - return list.ToArray(); - } - - internal static float GetFloat(Dictionary attrs, string name, float defaultVal = 0f) - { - return SvgStyleParser.ParseFloat(GetValue(attrs, name), defaultVal); - } - - internal static string? GetValue(Dictionary attrs, string name) - { - attrs.TryGetValue(name, out string? v); - return v; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgStyleParser.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgStyleParser.cs deleted file mode 100644 index 168b3277..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgStyleParser.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Fully-resolved SVG presentation attributes for the current element. - /// All properties are concrete strings (SVG defaults applied). Null means - /// "not applicable" or "use default". - /// - internal sealed class SvgStyle - { - public string Fill = "black"; - public string Stroke = "none"; - public string StrokeWidth = "1"; - public string? StrokeDashArray; - public string StrokeLinecap = "butt"; - public string StrokeLinejoin = "miter"; - public string StrokeMiterlimit = "4"; - public string StrokeDashoffset = "0"; - public string FillRule = "nonzero"; - public string Opacity = "1"; - public string FillOpacity = "1"; - public string StrokeOpacity = "1"; - public string FontFamily = "Arial"; - public string FontSize = "16"; - public string FontWeight = "normal"; - public string FontStyleVal = "normal"; - public string TextAnchor = "start"; - public string Display = "inline"; - public string Visibility = "visible"; - public string ClipPath = "none"; - - /// Creates a shallow copy. - public SvgStyle Clone() => (SvgStyle)MemberwiseClone(); - - /// - /// Returns true if fill is not "none" and not "inherit". - /// - public bool HasFill => !IsNone(Fill) && !IsInherit(Fill); - - /// - /// Returns true if stroke is not "none" and not "inherit". - /// - public bool HasStroke => !IsNone(Stroke) && !IsInherit(Stroke); - - private static bool IsNone(string? s) => string.Equals(s, "none", StringComparison.OrdinalIgnoreCase); - private static bool IsInherit(string? s) => string.Equals(s, "inherit", StringComparison.OrdinalIgnoreCase); - } - - /// - /// Parses style="..." CSS property lists and individual SVG - /// presentation attributes, applying them onto a . - /// - internal static class SvgStyleParser - { - /// - /// Applies a CSS-style property string (e.g. fill:red;stroke:blue) - /// to the given style. - /// - public static void ApplyStyleString(SvgStyle style, string? styleAttr) - { - if (string.IsNullOrWhiteSpace(styleAttr)) return; - - foreach (string pair in styleAttr.Split(';')) - { - int colon = pair.IndexOf(':'); - if (colon < 0) continue; - string name = pair.Substring(0, colon).Trim(); - string value = pair.Substring(colon + 1).Trim(); - if (name.Length > 0 && value.Length > 0) - ApplyProperty(style, name, value); - } - } - - /// - /// Applies a single SVG presentation attribute (e.g. - /// fill="red") to the given style. - /// - public static void ApplyAttribute(SvgStyle style, string name, string value) - { - ApplyProperty(style, name, value); - } - - /// - /// Reads all attributes from the current XmlReader position, applies - /// style-related ones to the style, and returns a dictionary of all - /// attributes for further processing (e.g. geometry attributes). - /// - public static Dictionary ApplyAttributes( - System.Xml.XmlReader reader, SvgStyle style) - { - var attrs = new Dictionary(StringComparer.OrdinalIgnoreCase); - - if (reader.HasAttributes) - { - while (reader.MoveToNextAttribute()) - { - string name = reader.Name; - string value = reader.Value; - attrs[name] = value; - - if (name.Equals("style", StringComparison.OrdinalIgnoreCase)) - ApplyStyleString(style, value); - else - ApplyAttribute(style, name, value); - } - reader.MoveToElement(); - } - - return attrs; - } - - private static void ApplyProperty(SvgStyle style, string name, string value) - { - switch (name.ToLowerInvariant()) - { - case "fill": style.Fill = value; break; - case "stroke": style.Stroke = value; break; - case "stroke-width": style.StrokeWidth = value; break; - case "stroke-dasharray": style.StrokeDashArray = value; break; - case "stroke-linecap": style.StrokeLinecap = value; break; - case "stroke-linejoin": style.StrokeLinejoin = value; break; - case "stroke-miterlimit": style.StrokeMiterlimit = value; break; - case "stroke-dashoffset": style.StrokeDashoffset = value; break; - case "fill-rule": style.FillRule = value; break; - case "opacity": style.Opacity = value; break; - case "fill-opacity": style.FillOpacity = value; break; - case "stroke-opacity": style.StrokeOpacity = value; break; - case "font-family": style.FontFamily = value; break; - case "font-size": style.FontSize = value; break; - case "font-weight": style.FontWeight = value; break; - case "font-style": style.FontStyleVal = value; break; - case "text-anchor": style.TextAnchor = value; break; - case "display": style.Display = value; break; - case "visibility": style.Visibility = value; break; - case "clip-path": style.ClipPath = value; break; - } - } - - /// - /// Parses a length value (e.g. "10", "10px", "50%") to a float, - /// stripping units. Percentages return NaN (caller must handle). - /// - public static float ParseLength(string? s, float defaultValue = 0f) - { - if (string.IsNullOrWhiteSpace(s)) return defaultValue; - s = s.Trim(); - - // Strip common unit suffixes - string[] units = { "px", "pt", "em", "ex", "%", "pc", "in", "cm", "mm" }; - bool isPercent = false; - foreach (var u in units) - { - if (s.EndsWith(u, StringComparison.OrdinalIgnoreCase)) - { - if (u == "%") isPercent = true; - s = s.Substring(0, s.Length - u.Length).Trim(); - break; - } - } - - if (float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float val)) - return isPercent ? float.NaN : val; - return defaultValue; - } - - /// - /// Parses a float value, returning the default on failure. - /// - public static float ParseFloat(string? s, float defaultValue = 0f) - { - if (string.IsNullOrWhiteSpace(s)) return defaultValue; - if (float.TryParse(s.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float val)) - return val; - return defaultValue; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgTextReader.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgTextReader.cs deleted file mode 100644 index 9f6f5955..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgTextReader.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Text; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses SVG <text> and <tspan> elements into - /// text rendering information (best-effort). Complex text flow features - /// (textLength, writing-mode, complex BiDi) fall back to approximate positioning. - /// - internal sealed class SvgTextReader - { - private readonly Dictionary _defs; - - public SvgTextReader(Dictionary defs) - { - _defs = defs; - } - - /// - /// Reads a <text> element and returns the text content, - /// font, brush, and layout rectangle for a DrawString call. - /// The reader must be positioned on the text start element; reads - /// through the end element. - /// - public (string Text, MiniSoftware.Drawing.Text.Font Font, Brush? Brush, RectangleF LayoutRect, StringFormat? Format)? - ReadText(XmlReader reader, SvgStyle style) - { - var attrs = SvgStyleParser.ApplyAttributes(reader, style); - - float x = SvgShapeReader.GetFloat(attrs, "x"); - float y = SvgShapeReader.GetFloat(attrs, "y"); - float dx = SvgShapeReader.GetFloat(attrs, "dx"); - float dy = SvgShapeReader.GetFloat(attrs, "dy"); - - // Font - float fontSize = SvgStyleParser.ParseLength(style.FontSize, 16f); - FontStyle fontStyle = ParseFontStyle(style.FontStyleVal, style.FontWeight); - var font = new MiniSoftware.Drawing.Text.Font(style.FontFamily, fontSize, fontStyle, GraphicsUnit.Pixel); - - // Brush - float fillOpacity = SvgStyleParser.ParseFloat(style.FillOpacity, 1f) * - SvgStyleParser.ParseFloat(style.Opacity, 1f); - Brush? brush = SvgBrushReader.ResolveBrush(style.Fill, _defs); - brush = SvgBrushReader.ApplyOpacity(brush, fillOpacity); - - // String format from text-anchor - var format = new StringFormat - { - Alignment = style.TextAnchor.ToLowerInvariant() switch - { - "middle" => StringAlignment.Center, - "end" => StringAlignment.Far, - _ => StringAlignment.Near, - }, - }; - - // Read text content (including tspans) - float textX = x + dx; - float textY = y + dy; - var sb = new System.Text.StringBuilder(); - float curX = textX; - - if (!reader.IsEmptyElement) - { - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement) break; - - if (reader.NodeType == XmlNodeType.Text || - reader.NodeType == XmlNodeType.Whitespace || - reader.NodeType == XmlNodeType.SignificantWhitespace) - { - sb.Append(reader.Value); - } - else if (reader.NodeType == XmlNodeType.Element && - reader.LocalName == "tspan") - { - var tspanAttrs = SvgStyleParser.ApplyAttributes(reader, style.Clone()); - float tsX = tspanAttrs.TryGetValue("x", out var xVal) - ? SvgStyleParser.ParseFloat(xVal) : curX; - float tsY = tspanAttrs.TryGetValue("y", out var yVal) - ? SvgStyleParser.ParseFloat(yVal) : textY; - - if (sb.Length > 0 && !sb[sb.Length - 1].Equals(' ')) - sb.Append(' '); - - string tspanText = ReadElementText(reader); - sb.Append(tspanText); - // Approximate advance width - curX = tsX + tspanText.Length * fontSize * 0.5f; - } - } - } - - string text = sb.ToString().Trim(); - if (string.IsNullOrEmpty(text) || brush == null) - { - font.Dispose(); - brush?.Dispose(); - return null; - } - - // Layout rect: start at (textX, textY), wide enough for the text - var layoutRect = new RectangleF(textX, textY - font.Height, 10000f, font.Height); - - return (text, font, brush, layoutRect, format); - } - - private static string ReadElementText(XmlReader reader) - { - if (reader.IsEmptyElement) return ""; - var sb = new System.Text.StringBuilder(); - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.EndElement) break; - if (reader.NodeType == XmlNodeType.Text || - reader.NodeType == XmlNodeType.Whitespace || - reader.NodeType == XmlNodeType.SignificantWhitespace) - { - sb.Append(reader.Value); - } - } - return sb.ToString(); - } - - private static FontStyle ParseFontStyle(string fontStyle, string fontWeight) - { - var result = FontStyle.Regular; - if (fontStyle.Equals("italic", StringComparison.OrdinalIgnoreCase) || - fontStyle.Equals("oblique", StringComparison.OrdinalIgnoreCase)) - result |= FontStyle.Italic; - if (fontWeight.Equals("bold", StringComparison.OrdinalIgnoreCase) || - (int.TryParse(fontWeight, out int w) && w >= 600)) - result |= FontStyle.Bold; - return result; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgTextWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgTextWriter.cs deleted file mode 100644 index d587e2b8..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgTextWriter.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System; -using System.Collections.Generic; -using MiniSoftware.Drawing.Brushes; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Enums; -using MiniSoftware.Drawing.Geometry; -using MiniSoftware.Drawing.Imaging; -using MiniSoftware.Drawing.Pens; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Writes SVG text in two modes: - /// - /// Path mode (default): vectorizes glyphs via - /// into <path> elements. - /// Pixel-identical to the rasterizer; no font dependency on viewer. - /// Text mode (opt-in): emits <text>/<tspan> - /// with font attributes. Editable but best-effort fidelity. - /// - /// - internal sealed class SvgTextWriter - { - private readonly SvgXmlWriter _w; - private readonly SvgDefTable _defs; - private readonly SvgEncoderParameters _params; - - public SvgTextWriter(SvgXmlWriter w, SvgDefTable defs, SvgEncoderParameters parameters) - { - _w = w; - _defs = defs; - _params = parameters; - } - - /// - /// Writes text for a DrawString command. Dispatches to path or text - /// mode based on . - /// - public void WriteText(string text, MiniSoftware.Drawing.Text.Font font, Brush brush, - RectangleF layoutRect, MiniSoftware.Drawing.Text.StringFormat? format) - { - if (string.IsNullOrEmpty(text)) return; - - if (_params.TextMode == SvgTextMode.Text) - WriteTextMode(text, font, brush, layoutRect, format); - else - WritePathMode(text, font, brush, layoutRect, format); - } - - // ── Path mode: vectorize glyphs ─────────────────────────────────────── - - /// - /// Path mode: replays DrawString onto a capture Graphics that intercepts - /// FillPath calls (which the rasterizer uses for each glyph outline), - /// then emits each captured path as an SVG <path>. - /// - private void WritePathMode(string text, MiniSoftware.Drawing.Text.Font font, Brush brush, - RectangleF layoutRect, MiniSoftware.Drawing.Text.StringFormat? format) - { - var capturedPaths = new List(); - using var capture = new GlyphCaptureGraphics(capturedPaths); - capture.DrawString(text, font, brush, layoutRect, format); - - string fill = SvgBrushWriter.WriteFillRef(brush, _defs); - string? opacity = SvgBrushWriter.WriteFillOpacity(brush); - - foreach (var path in capturedPaths) - { - using (path) - { - if (path.PointCount == 0) continue; - WriteFillPath(path, fill, opacity); - } - } - } - - private void WriteFillPath(GraphicsPath path, string fill, string? opacity) - { - string d = SvgPathWriter.WritePathData(path, _params.CoordinatePrecision); - if (string.IsNullOrEmpty(d)) return; - - _w.WriteStartElement("path"); - _w.WriteAttribute("d", d); - _w.WriteAttribute("fill", fill); - if (opacity != null) - _w.WriteAttribute("fill-opacity", opacity); - _w.WriteAttribute("stroke", "none"); - _w.WriteEndElement(); - } - - // ── Text mode: / ───────────────────────────────────────── - - private void WriteTextMode(string text, MiniSoftware.Drawing.Text.Font font, Brush brush, - RectangleF layoutRect, MiniSoftware.Drawing.Text.StringFormat? format) - { - var lines = MiniSoftware.Drawing.Text.TextLayoutEngine.Layout(text, font, layoutRect, format, 96f, 96f); - if (lines.Count == 0) return; - - string fill = SvgBrushWriter.WriteFillRef(brush, _defs); - string? opacity = SvgBrushWriter.WriteFillOpacity(brush); - - _w.WriteStartElement("text"); - _w.WriteAttribute("font-family", font.FontFamily.Name ?? "Arial"); - _w.WriteAttribute("font-size", font.Size); - if ((font.Style & FontStyle.Bold) != 0) - _w.WriteAttribute("font-weight", "bold"); - if ((font.Style & FontStyle.Italic) != 0) - _w.WriteAttribute("font-style", "italic"); - _w.WriteAttribute("fill", fill); - if (opacity != null) - _w.WriteAttribute("fill-opacity", opacity); - - var sf = format ?? MiniSoftware.Drawing.Text.StringFormat.GenericDefault; - string anchor = sf.Alignment switch - { - MiniSoftware.Drawing.Text.StringAlignment.Near => "start", - MiniSoftware.Drawing.Text.StringAlignment.Center => "middle", - MiniSoftware.Drawing.Text.StringAlignment.Far => "end", - _ => "start", - }; - _w.WriteAttributeOptional("text-anchor", anchor, "start"); - - string baseline = sf.LineAlignment switch - { - MiniSoftware.Drawing.Text.StringAlignment.Near => "text-before-edge", - MiniSoftware.Drawing.Text.StringAlignment.Center => "central", - MiniSoftware.Drawing.Text.StringAlignment.Far => "text-after-edge", - _ => "text-before-edge", - }; - _w.WriteAttributeOptional("dominant-baseline", baseline, "text-before-edge"); - - foreach (var line in lines) - { - foreach (var run in line.Runs) - { - _w.WriteStartElement("tspan"); - _w.WriteAttribute("x", run.X); - _w.WriteAttribute("y", run.Baseline); - _w.Underlying.WriteString(run.Text); - _w.WriteEndElement(); - } - } - - _w.WriteEndElement(); - } - - /// - /// A Graphics subclass that intercepts FillPathCore to capture glyph - /// outline paths during DrawString rendering. - /// - private sealed class GlyphCaptureGraphics : Graphics - { - private readonly List _captured; - - public GlyphCaptureGraphics(List captured) - : base(CreateBlankBitmap()) - { - _captured = captured; - } - - private static MiniSoftware.Drawing.Imaging.Bitmap CreateBlankBitmap() - { - return new MiniSoftware.Drawing.Imaging.Bitmap(1, 1, PixelFormat.Format32bppArgb); - } - - protected override void FillPathCore(Brush brush, GraphicsPath path, FillMode fillMode) - { - _captured.Add(path.Clone()); - } - - protected override void DrawPathCore(Pen pen, GraphicsPath path) - { - } - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgTransformParser.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgTransformParser.cs deleted file mode 100644 index 0efaebb1..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgTransformParser.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using MiniSoftware.Drawing.Drawing2D; -using MiniSoftware.Drawing.Geometry; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Parses an SVG transform attribute value (e.g. - /// translate(10,20) scale(2)) into a . - /// Supports matrix, translate, scale, rotate, skewX, and skewY. - /// - internal static class SvgTransformParser - { - /// - /// Parses the transform list and returns the combined matrix. - /// For a list T1 T2 T3 the combined matrix is T1 * T2 * T3 - /// (SVG convention: rightmost applied first to points). - /// - public static Matrix Parse(string? transform) - { - var result = new Matrix(); - if (string.IsNullOrWhiteSpace(transform)) - return result; - - int i = 0; - int len = transform.Length; - - while (i < len) - { - // Skip whitespace and commas - SkipSeparators(transform, ref i, len); - if (i >= len) break; - - // Read function name - int start = i; - while (i < len && (char.IsLetter(transform[i]) || transform[i] == '_')) - i++; - - if (i == start) { i++; continue; } - - string name = transform.Substring(start, i - start); - - // Skip whitespace and '(' - SkipSeparators(transform, ref i, len); - if (i < len && transform[i] == '(') i++; - SkipSeparators(transform, ref i, len); - - // Read arguments - var args = new List(); - while (i < len && transform[i] != ')') - { - if (TryReadNumber(transform, ref i, len, out float val)) - args.Add(val); - else - i++; - - SkipSeparators(transform, ref i, len); - } - - // Skip ')' - if (i < len && transform[i] == ')') i++; - - // Apply transform (Append = SVG left-multiply, so T1 then T2 gives T1*T2) - Matrix m = CreateTransform(name, args); - result.Multiply(m, MatrixOrder.Append); - m.Dispose(); - } - - return result; - } - - private static Matrix CreateTransform(string name, List args) - { - switch (name) - { - case "matrix": - if (args.Count >= 6) - return new Matrix(args[0], args[1], args[2], args[3], args[4], args[5]); - break; - - case "translate": - { - float tx = args.Count > 0 ? args[0] : 0f; - float ty = args.Count > 1 ? args[1] : 0f; - var m = new Matrix(); - m.Translate(tx, ty); - return m; - } - - case "scale": - { - float sx = args.Count > 0 ? args[0] : 1f; - float sy = args.Count > 1 ? args[1] : sx; - var m = new Matrix(); - m.Scale(sx, sy); - return m; - } - - case "rotate": - { - float angle = args.Count > 0 ? args[0] : 0f; - var m = new Matrix(); - if (args.Count >= 3) - m.RotateAt(angle, new PointF(args[1], args[2])); - else - m.Rotate(angle); - return m; - } - - case "skewX": - { - float angle = args.Count > 0 ? args[0] : 0f; - float t = (float)Math.Tan(angle * Math.PI / 180.0); - var m = new Matrix(); - m.Shear(t, 0f); - return m; - } - - case "skewY": - { - float angle = args.Count > 0 ? args[0] : 0f; - float t = (float)Math.Tan(angle * Math.PI / 180.0); - var m = new Matrix(); - m.Shear(0f, t); - return m; - } - } - - return new Matrix(); - } - - private static void SkipSeparators(string s, ref int i, int len) - { - while (i < len && (char.IsWhiteSpace(s[i]) || s[i] == ',')) - i++; - } - - private static bool TryReadNumber(string s, ref int i, int len, out float value) - { - int start = i; - - // Optional sign - if (i < len && (s[i] == '+' || s[i] == '-')) i++; - - // Integer part - while (i < len && char.IsDigit(s[i])) i++; - - // Fractional part - if (i < len && s[i] == '.') - { - i++; - while (i < len && char.IsDigit(s[i])) i++; - } - - // Exponent - if (i < len && (s[i] == 'e' || s[i] == 'E')) - { - i++; - if (i < len && (s[i] == '+' || s[i] == '-')) i++; - while (i < len && char.IsDigit(s[i])) i++; - } - - if (i == start) - { - value = 0; - return false; - } - - string numStr = s.Substring(start, i - start); - return float.TryParse(numStr, NumberStyles.Float, CultureInfo.InvariantCulture, out value); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgTransformWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgTransformWriter.cs deleted file mode 100644 index 7fe4cb70..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgTransformWriter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Globalization; -using MiniSoftware.Drawing.Drawing2D; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Converts a to an SVG transform attribute - /// value. Always emits the matrix form for lossless round-tripping. - /// - internal static class SvgTransformWriter - { - /// - /// Returns matrix(a b c d e f) for the given matrix, or an empty - /// string if the matrix is the identity. - /// - public static string WriteTransform(Matrix matrix, int precision = 4) - { - if (matrix == null || matrix.IsIdentity) return string.Empty; - - var e = matrix.Elements; - // SVG matrix(a b c d e f) maps to GDI+ [M11 M12 M21 M22 DX DY] - return string.Format(CultureInfo.InvariantCulture, - "matrix({0} {1} {2} {3} {4} {5})", - Fmt(e[0], precision), Fmt(e[1], precision), - Fmt(e[2], precision), Fmt(e[3], precision), - Fmt(e[4], precision), Fmt(e[5], precision)); - } - - private static string Fmt(float v, int precision) - { - if (float.IsNaN(v) || float.IsInfinity(v)) v = 0f; - string s = v.ToString("F" + precision, CultureInfo.InvariantCulture); - if (s.IndexOf('.') >= 0) - s = s.TrimEnd('0').TrimEnd('.'); - if (s.Length == 0 || s == "-") s = "0"; - return s; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgWriter.cs deleted file mode 100644 index 1efd9030..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgWriter.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.IO; -using System.Xml; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Top-level SVG writer: serializes a to an SVG - /// document using a two-pass pipeline: - /// - /// Def-collection pass: replay onto - /// to gather unique brushes/clips. - /// Emit pass: write <svg> root, <defs>, - /// then replay onto for the body. - /// - /// - internal static class SvgWriter - { - /// - /// Writes the specified scene as an SVG document to the given stream. - /// - public static void Write(Stream stream, VectorScene scene, SvgEncoderParameters? parameters = null) - { - if (stream == null) throw new ArgumentNullException(nameof(stream)); - if (scene == null) throw new ArgumentNullException(nameof(scene)); - - var p = parameters ?? SvgEncoderParameters.Default; - - var settings = new XmlWriterSettings - { - Encoding = System.Text.Encoding.UTF8, - Indent = p.Indent, - IndentChars = " ", - OmitXmlDeclaration = false, - }; - - using var xmlWriter = XmlWriter.Create(stream, settings); - Write(xmlWriter, scene, p); - } - - /// - /// Writes the specified scene as an SVG document to the given - /// . - /// - public static void Write(XmlWriter xmlWriter, VectorScene scene, SvgEncoderParameters? parameters = null) - { - if (xmlWriter == null) throw new ArgumentNullException(nameof(xmlWriter)); - if (scene == null) throw new ArgumentNullException(nameof(scene)); - - var p = parameters ?? SvgEncoderParameters.Default; - - // ── Pass 1: def collection ────────────────────────────────────── - var defs = new SvgDefTable(); - using (var collector = new SvgDefCollector(defs, scene.Width, scene.Height)) - { - VectorScenePlayer.Play(scene, collector); - } - - // ── Pass 2: emit ──────────────────────────────────────────────── - using var w = new SvgXmlWriter(xmlWriter, p.CoordinatePrecision); - w.WriteStartDocument(); - - w.WriteStartElement("svg"); - w.WriteAttribute("width", scene.Width); - w.WriteAttribute("height", scene.Height); - w.WriteAttribute("viewBox", "0 0 " + scene.Width + " " + scene.Height); - - // Write defs (gradients, patterns, clip paths) - SvgBrushWriter.WriteDefs(w, defs); - - // Write body: replay scene onto SvgDrawingContext - using (var ctx = new SvgDrawingContext(w, defs, p, scene.Width, scene.Height)) - { - VectorScenePlayer.Play(scene, ctx); - } - - w.WriteEndElement(); // - w.WriteEndDocument(); - xmlWriter.Flush(); - } - - /// - /// Returns the SVG document as a string. - /// - public static string WriteToString(VectorScene scene, SvgEncoderParameters? parameters = null) - { - using var ms = new MemoryStream(); - Write(ms, scene, parameters); - ms.Position = 0; - using var reader = new StreamReader(ms); - return reader.ReadToEnd(); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/Svg/SvgXmlWriter.cs b/src/MiniPdf/Drawing/Vector/Svg/SvgXmlWriter.cs deleted file mode 100644 index c9cbeed2..00000000 --- a/src/MiniPdf/Drawing/Vector/Svg/SvgXmlWriter.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Globalization; -using System.Xml; - -namespace MiniSoftware.Drawing.Vector.Svg -{ - /// - /// Thin wrapper over providing SVG-friendly - /// helpers: invariant number formatting with bounded precision, attribute - /// escaping, and element emission shortcuts. - /// - internal sealed class SvgXmlWriter : IDisposable - { - internal const string SvgNamespace = "http://www.w3.org/2000/svg"; - internal const string XLinkNamespace = "http://www.w3.org/1999/xlink"; - - private readonly XmlWriter _writer; - private readonly int _precision; - private bool _rootWritten; - - public SvgXmlWriter(XmlWriter writer, int precision = 4) - { - _writer = writer ?? throw new ArgumentNullException(nameof(writer)); - _precision = Math.Max(0, precision); - } - - public XmlWriter Underlying => _writer; - - // ── Element shortcuts ────────────────────────────────────────────────── - - /// - /// Writes a start element in the SVG namespace. On the first call - /// (the root <svg>), also emits the xmlns:xlink declaration. - /// - public void WriteStartElement(string name) - { - _writer.WriteStartElement(name, SvgNamespace); - if (!_rootWritten) - { - _writer.WriteAttributeString("xmlns", "xlink", null, XLinkNamespace); - _rootWritten = true; - } - } - - public void WriteEndElement() => _writer.WriteEndElement(); - public void WriteStartDocument() => _writer.WriteStartDocument(true); - public void WriteEndDocument() => _writer.WriteEndDocument(); - public void WriteComment(string text) => _writer.WriteComment(text); - - public void WriteElementString(string name, string value) - => _writer.WriteElementString(name, value, SvgNamespace); - - // ── Attribute helpers ─────────────────────────────────────────────────── - - public void WriteAttribute(string name, string value) - => _writer.WriteAttributeString(name, value); - - /// - /// Writes an xlink:href attribute (e.g. for <image> elements). - /// - public void WriteXLinkHref(string value) - => _writer.WriteAttributeString("xlink", "href", XLinkNamespace, value); - - public void WriteAttribute(string name, float value) - => _writer.WriteAttributeString(name, FormatNumber(value)); - - public void WriteAttribute(string name, double value) - => _writer.WriteAttributeString(name, FormatNumber(value)); - - public void WriteAttribute(string name, int value) - => _writer.WriteAttributeString(name, value.ToString(CultureInfo.InvariantCulture)); - - public void WriteAttribute(string name, bool value) - => _writer.WriteAttributeString(name, value ? "true" : "false"); - - public void WriteAttributeOptional(string name, string? value) - { - if (!string.IsNullOrEmpty(value)) - _writer.WriteAttributeString(name, value); - } - - public void WriteAttributeOptional(string name, string? value, string? omitIfEqual) - { - if (!string.IsNullOrEmpty(value) && value != omitIfEqual) - _writer.WriteAttributeString(name, value); - } - - public void WriteAttributeOptional(string name, float value, float omitIfEqual) - { - if (value != omitIfEqual) - WriteAttribute(name, value); - } - - // ── Number formatting ─────────────────────────────────────────────────── - - /// - /// Formats a number for SVG output: up to decimal - /// places, trailing zeros stripped, invariant culture. Infinity and NaN - /// are clamped to 0. - /// - public string FormatNumber(float value) - { - if (float.IsNaN(value) || float.IsInfinity(value)) value = 0f; - return FormatNumber((double)value); - } - - public string FormatNumber(double value) - { - if (double.IsNaN(value) || double.IsInfinity(value)) value = 0d; - string s = value.ToString("F" + _precision, CultureInfo.InvariantCulture); - if (s.IndexOf('.') >= 0) - { - s = s.TrimEnd('0').TrimEnd('.'); - if (s.Length == 0 || s == "-") s = "0"; - } - return s; - } - - public void Dispose() => _writer.Dispose(); - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/VectorScene.cs b/src/MiniPdf/Drawing/Vector/VectorScene.cs deleted file mode 100644 index 8a94dcc0..00000000 --- a/src/MiniPdf/Drawing/Vector/VectorScene.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Collections.Generic; - -namespace MiniSoftware.Drawing.Vector -{ - /// - /// Format-agnostic recording of a sequence of drawing operations. - /// Producers (RecordingGraphics, EmfPlayer, SvgReader) append commands; - /// consumers (VectorScenePlayer, SvgWriter, EmfDrawingContext) read them. - /// - public sealed class VectorScene - { - /// - /// Gets or sets the canvas width in pixels. - /// - public int Width { get; set; } - - /// - /// Gets or sets the canvas height in pixels. - /// - public int Height { get; set; } - - /// - /// Gets or sets the horizontal resolution in dots per inch. - /// - public float DpiX { get; set; } = 96f; - - /// - /// Gets or sets the vertical resolution in dots per inch. - /// - public float DpiY { get; set; } = 96f; - - /// - /// Gets the ordered list of recorded drawing commands. - /// - public List Commands { get; } = new List(); - - /// - /// Appends a drawing command to the scene. - /// - /// The command to append. - internal void Add(DrawingCommand cmd) - { - if (cmd != null) - Commands.Add(cmd); - } - - /// - /// Creates a deep copy of this scene, including cloned commands. - /// - /// A new with the same content. - public VectorScene Clone() - { - var clone = new VectorScene - { - Width = Width, - Height = Height, - DpiX = DpiX, - DpiY = DpiY, - }; - foreach (var cmd in Commands) - clone.Commands.Add(cmd.Clone()); - return clone; - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/Drawing/Vector/VectorScenePlayer.cs b/src/MiniPdf/Drawing/Vector/VectorScenePlayer.cs deleted file mode 100644 index 649707f8..00000000 --- a/src/MiniPdf/Drawing/Vector/VectorScenePlayer.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace MiniSoftware.Drawing.Vector -{ - /// - /// Replays a onto any . - /// One replay engine, three outputs: raster (Bitmap), SVG, EMF. - /// - internal static class VectorScenePlayer - { - /// - /// Replays each command in the scene in order onto the specified target. - /// State commands mutate target state; primitives draw. - /// Save/Restore use the target's own state stack. - /// - /// The scene to replay. - /// The target drawing context. - public static void Play(VectorScene scene, IDrawingContext target) - { - if (scene == null) return; - if (target == null) return; - - foreach (var cmd in scene.Commands) - cmd.Replay(target); - } - } -} \ No newline at end of file diff --git a/src/MiniPdf/EmfVectorRenderer.cs b/src/MiniPdf/EmfVectorRenderer.cs new file mode 100644 index 00000000..0a93251f --- /dev/null +++ b/src/MiniPdf/EmfVectorRenderer.cs @@ -0,0 +1,1449 @@ +using System.IO.Compression; + +namespace MiniSoftware; + +// Owned MS-EMF subset used by portable conversion. Unsupported records fail explicitly. +internal sealed class EmfVectorRenderer +{ + private readonly byte[] source; + private readonly int width; + private readonly int height; + private readonly byte[] pixels; + private readonly Dictionary objects = new(); + private readonly Dictionary fonts = new(); + private readonly Func? fontResolver; + private readonly List savedStates = new(); + private readonly double left; + private readonly double top; + private readonly double scaleX; + private readonly double scaleY; + private readonly int handleCount; + private DeviceState state; + private List? path; + private PathFigure? activeFigure; + private bool buildingPath; + private int pathPointCount; + private int recordEnd; + private int commentGroups; + private bool plusStarted, plusEnded, plusDc, plusUsedDc; + private WorldTransform plusWorld = WorldTransform.Identity; + private long remainingWork = 64_000_000; + + private readonly struct DrawingObject + { + internal readonly bool IsPen; + internal readonly bool IsNull; + internal readonly uint Color; + internal readonly int Width; + + internal DrawingObject(bool isPen, uint color, bool isNull = false, int width = 0) + { + IsPen = isPen; + Color = color; + IsNull = isNull; + Width = width; + } + } + + private sealed class DeviceState + { + internal DrawingObject Pen = new(true, 0); + internal DrawingObject Brush = new(false, 0xFFFFFF); + internal int MapMode = 1; + internal int StretchMode = 1; + internal uint RasterOperation = 13; + internal int WindowX, WindowY, ViewportX, ViewportY; + internal int WindowWidth = 1, WindowHeight = 1, ViewportWidth = 1, ViewportHeight = 1; + internal int CurrentX, CurrentY; + internal int ClipLeft, ClipTop, ClipRight, ClipBottom; + internal bool Winding; + internal WorldTransform World = WorldTransform.Identity; + internal MetafileFont? Font; + internal uint TextColor, BackgroundColor = 0xFFFFFF; + internal int BackgroundMode = 2; + internal uint TextAlignment; + internal DeviceState Copy() => (DeviceState)MemberwiseClone(); + } + + private sealed class MetafileFont + { + internal readonly string Name; + internal readonly double Height; + internal readonly int Width; + internal readonly bool Bold, Italic; + internal TrueTypeGlyphReader? Outlines; + internal MetafileFont(string name, double height, int width, bool bold, bool italic) + { + Name = name; Height = height; Width = width; Bold = bold; Italic = italic; + } + } + + private readonly struct WorldTransform + { + internal readonly double M11, M12, M21, M22, X, Y; + internal static WorldTransform Identity => new(1, 0, 0, 1, 0, 0); + + internal WorldTransform(double m11, double m12, double m21, double m22, double x, double y) + { + var determinant = m11 * m22 - m12 * m21; + if (double.IsNaN(determinant) || double.IsInfinity(determinant) || determinant == 0 || + double.IsNaN(x) || double.IsInfinity(x) || double.IsNaN(y) || double.IsInfinity(y)) + throw new InvalidDataException("Invalid or singular EMF world transform."); + M11 = m11; M12 = m12; M21 = m21; M22 = m22; X = x; Y = y; + } + + internal static WorldTransform Multiply(WorldTransform a, WorldTransform b) => new( + a.M11 * b.M11 + a.M12 * b.M21, a.M11 * b.M12 + a.M12 * b.M22, + a.M21 * b.M11 + a.M22 * b.M21, a.M21 * b.M12 + a.M22 * b.M22, + a.X * b.M11 + a.Y * b.M21 + b.X, a.X * b.M12 + a.Y * b.M22 + b.Y); + } + + private sealed class PathFigure + { + internal readonly List<(double X, double Y)> Points; + internal bool Closed; + + internal PathFigure(IReadOnlyList<(double X, double Y)> points, bool closed) + { + Points = new List<(double X, double Y)>(points); + Closed = closed; + } + } + + private EmfVectorRenderer(byte[] source, int width, int height, Func? fontResolver) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (width < 1 || width > 4096) throw new ArgumentOutOfRangeException(nameof(width)); + if (height < 1 || height > 4096) throw new ArgumentOutOfRangeException(nameof(height)); + this.source = source; + this.width = width; + this.height = height; + this.fontResolver = fontResolver; + recordEnd = source.Length; + if (source.Length < 88 || U32(0) != 1 || U32(40) != 0x464D4520 || U32(44) != 0x10000) + throw new InvalidDataException("Invalid EMF header."); + if (U32(48) != source.Length || U32(4) < 88 || U32(4) > source.Length) + throw new InvalidDataException("Invalid EMF byte count or header size."); + left = I32(8); + top = I32(12); + var boundsWidth = (long)I32(16) - left; + var boundsHeight = (long)I32(20) - top; + var frameWidth = (long)I32(32) - I32(24); + var frameHeight = (long)I32(36) - I32(28); + var deviceWidth = I32(72); + var deviceHeight = I32(76); + var millimetersWidth = I32(80); + var millimetersHeight = I32(84); + if (frameWidth > 0 && frameHeight > 0 && deviceWidth > 0 && deviceHeight > 0 && + millimetersWidth > 0 && millimetersHeight > 0) + { + if (boundsWidth < 0 || boundsHeight < 0) + throw new InvalidDataException("EMF drawing bounds are inverted."); + // The physical frame defines placement; sparse ink bounds are not the canvas. + var frameUnitsPerPixelX = millimetersWidth * 100d / deviceWidth; + var frameUnitsPerPixelY = millimetersHeight * 100d / deviceHeight; + left = I32(24) / frameUnitsPerPixelX; + top = I32(28) / frameUnitsPerPixelY; + scaleX = width * frameUnitsPerPixelX / frameWidth; + scaleY = height * frameUnitsPerPixelY / frameHeight; + } + else + { + if (boundsWidth <= 0 || boundsHeight <= 0) + throw new InvalidDataException("EMF bounds must have positive dimensions when reference device metrics are unavailable."); + scaleX = width / (double)boundsWidth; + scaleY = height / (double)boundsHeight; + } + handleCount = U16(56); + if (handleCount < 1) throw new InvalidDataException("Invalid EMF handle count."); + if (U32(68) != 0) throw new NotSupportedException("EMF palettes are not supported."); + pixels = new byte[checked(width * height * 4)]; + state = new DeviceState { ClipRight = width, ClipBottom = height }; + } + + internal static byte[] Render(byte[] source, int width, int height, Func? fontResolver = null) + => RenderCropped(source, width, height, fontResolver, 0, 0, 0, 0); + + internal static byte[] RenderCropped(byte[] source, int width, int height, Func? fontResolver, + float cropLeft, float cropTop, float cropRight, float cropBottom) + { + if (float.IsNaN(cropLeft) || float.IsInfinity(cropLeft) || float.IsNaN(cropTop) || float.IsInfinity(cropTop) || + float.IsNaN(cropRight) || float.IsInfinity(cropRight) || float.IsNaN(cropBottom) || float.IsInfinity(cropBottom)) + throw new ArgumentException("Metafile crop values must be finite."); + var renderer = new EmfVectorRenderer(source, width, height, fontResolver); + renderer.Play(); + return renderer.EncodePng(cropLeft, cropTop, cropRight, cropBottom); + } + + private void Play() + { + var offset = 0; + var count = 0u; + while (offset < source.Length) + { + recordEnd = source.Length; + var type = U32(offset); + var size = U32(offset + 4); + if (size < 8 || size % 4 != 0 || size > source.Length - offset) + throw new InvalidDataException($"Invalid EMF record size at {offset}."); + recordEnd = offset + (int)size; + count++; + if (offset == 0) + { + if (type != 1) throw new InvalidDataException("EMF must begin with a header."); + } + else + { + if (plusStarted && !plusDc && type != 70 && type != 14) + { + offset = recordEnd; + continue; + } + switch (type) + { + case 14: + Require(offset, 20); + if (plusStarted && !plusEnded) + throw new InvalidDataException("Missing EMF+ EOF record."); + if (commentGroups != 0) + throw new InvalidDataException("Unclosed EMF comment group."); + if (U32(offset + 8) != 0) + throw new NotSupportedException("EMF EOF palettes are not supported."); + if (recordEnd != source.Length || count != U32(52)) + throw new InvalidDataException("Invalid EMF EOF or record count."); + return; + case 9: + state.WindowWidth = Nonzero(I32(offset + 8)); + state.WindowHeight = Nonzero(I32(offset + 12)); + break; + case 10: + state.WindowX = I32(offset + 8); + state.WindowY = I32(offset + 12); + break; + case 11: + state.ViewportWidth = Nonzero(I32(offset + 8)); + state.ViewportHeight = Nonzero(I32(offset + 12)); + break; + case 12: + state.ViewportX = I32(offset + 8); + state.ViewportY = I32(offset + 12); + break; + case 15: + var point = Map(I32(offset + 8), I32(offset + 12)); + var color = U32(offset + 16); + CheckColor(color); + if (point.X >= state.ClipLeft && point.X < state.ClipRight && + point.Y >= state.ClipTop && point.Y < state.ClipBottom && state.RasterOperation != 11) + PutPixel((int)Math.Floor(point.X), (int)Math.Floor(point.Y), RasterColor(color)); + break; + case 17: + var mode = I32(offset + 8); + if (mode != 1 && mode != 8) + throw new NotSupportedException($"EMF mapping mode {mode} is not supported."); + state.MapMode = mode; + break; + case 19: + var fillMode = I32(offset + 8); + if (fillMode != 1 && fillMode != 2) + throw new InvalidDataException("Invalid EMF polygon fill mode."); + state.Winding = fillMode == 2; + break; + case 18: + var backgroundMode = I32(offset + 8); + if (backgroundMode != 1 && backgroundMode != 2) + throw new InvalidDataException("Invalid EMF background mode."); + state.BackgroundMode = backgroundMode; + break; + case 20: + var rasterOperation = U32(offset + 8); + // Native EMF playback treats the recorded zero ROP2 as white, not as a no-op. + if (rasterOperation == 0) rasterOperation = 16; + if (rasterOperation is not (1 or 4 or 11 or 13 or 16)) + throw new NotSupportedException("This EMF raster operation is not supported."); + state.RasterOperation = rasterOperation; + break; + case 21: + var stretchMode = I32(offset + 8); + if (stretchMode < 1 || stretchMode > 4) + throw new InvalidDataException("Invalid EMF bitmap stretch mode."); + state.StretchMode = stretchMode; + break; + case 22: + var alignment = U32(offset + 8); + if ((alignment & ~0x11Fu) != 0 || (alignment & 6) == 4 || (alignment & 24) == 16) + throw new InvalidDataException("Invalid EMF text alignment."); + state.TextAlignment = alignment; + break; + case 24: + case 25: + var textColor = U32(offset + 8); + CheckColor(textColor); + if (type == 24) state.TextColor = textColor; + else state.BackgroundColor = textColor; + break; + case 27: + state.CurrentX = I32(offset + 8); + state.CurrentY = I32(offset + 12); + if (buildingPath) activeFigure = null; + break; + case 30: + IntersectClip(offset); + break; + case 33: + if (path != null) + throw new NotSupportedException("Saving a device context with a pending EMF path is not supported."); + if (savedStates.Count >= 1024) + throw new InvalidDataException("EMF saved device context limit exceeded."); + savedStates.Add(state.Copy()); + break; + case 34: + Restore(I32(offset + 8)); + break; + case 35: + state.World = ReadWorldTransform(offset + 8); + break; + case 36: + ModifyWorldTransform(offset); + break; + case 37: + Select(U32(offset + 8)); + break; + case 38: + var penStyle = U32(offset + 12); + var penWidth = I32(offset + 16); + Require(offset, 28); + if (penStyle != 0 && penStyle != 5) + throw new NotSupportedException("Only solid or null EMF pens are supported."); + if (penWidth < 0) + throw new InvalidDataException("Negative EMF pen width."); + if (penWidth > 1) + throw new NotSupportedException("Wide EMF pens are not supported."); + AddObject(U32(offset + 8), new DrawingObject(true, U32(offset + 24), penStyle == 5, penWidth)); + break; + case 39: + var brushStyle = U32(offset + 12); + Require(offset, 24); + if (brushStyle != 0 && brushStyle != 1) + throw new NotSupportedException("Only solid or null EMF brushes are supported."); + AddObject(U32(offset + 8), new DrawingObject(false, U32(offset + 16), brushStyle == 1)); + break; + case 40: + var deletedHandle = U32(offset + 8); + if (!objects.Remove(deletedHandle) && !fonts.Remove(deletedHandle)) + throw new InvalidDataException("Deleting an unknown EMF object."); + break; + case 82: + CreateFont(offset); + break; + case 84: + DrawText(offset); + break; + case 43: + Rectangle(offset); + break; + case 48: + if (U32(offset + 8) != 0x8000000F) + throw new NotSupportedException("Only the stock default EMF palette is supported."); + break; + case 54: + var x = I32(offset + 8); + var y = I32(offset + 12); + EmitFigure(new[] { CurrentPathPoint(), Map(x, y) }, false, true); + state.CurrentX = x; + state.CurrentY = y; + break; + case 59: + path = new List(); + activeFigure = null; + pathPointCount = 0; + buildingPath = true; + break; + case 60: + RequireOpenPath(); + buildingPath = false; + activeFigure = null; + break; + case 61: + RequireOpenPath(); + if (activeFigure == null) throw new InvalidDataException("No open EMF path figure to close."); + activeFigure.Closed = true; + activeFigure = null; + break; + case 62: + case 63: + case 64: + Require(offset, 24); + PaintPath(type != 64, type != 62); + break; + case 68: + ClearPath(); + break; + case 70: + ReadComment(offset); + break; + case 75: + SelectClipRegion(offset); + break; + case 2: + case 3: + case 4: + case 5: + case 6: + case 85: + case 86: + case 87: + case 88: + case 89: + Poly(offset, type); + break; + case 81: + case 114: + DrawBitmap(offset, type == 114); + break; + default: + throw new NotSupportedException($"EMF record {type} at {offset} is not supported."); + } + } + offset = recordEnd; + } + throw new InvalidDataException("Missing EMF EOF record."); + } + + private void Poly(int offset, uint type) + { + var count = U32(offset + 24); + var shortCoordinates = type >= 85; + var continues = type is 5 or 6 or 88 or 89; + var bezier = type is 2 or 5 or 85 or 88; + var stride = shortCoordinates ? 4 : 8; + if (count < (continues ? 1 : 2) || count > 1_000_000 || count > (recordEnd - offset - 28) / stride || + (bezier && (continues ? count % 3 != 0 : count < 4 || count % 3 != 1))) + throw new InvalidDataException("Invalid EMF point count."); + Spend(count); + var points = new (double X, double Y)[(int)count + (continues ? 1 : 0)]; + if (continues) points[0] = CurrentPathPoint(); + var lastX = 0; + var lastY = 0; + for (var index = 0; index < count; index++) + { + var position = offset + 28 + index * stride; + lastX = shortCoordinates ? (short)U16(position) : I32(position); + lastY = shortCoordinates ? (short)U16(position + 2) : I32(position + 4); + points[index + (continues ? 1 : 0)] = Map(lastX, lastY); + } + var closed = type == 3 || type == 86; + EmitFigure(bezier ? FlattenBeziers(points) : points, closed, continues); + if (continues) + { + state.CurrentX = lastX; + state.CurrentY = lastY; + } + } + + private void Rectangle(int offset) + { + var x1 = I32(offset + 8); + var y1 = I32(offset + 12); + var x2 = I32(offset + 16); + var y2 = I32(offset + 20); + if (x2 <= x1 || y2 <= y1) return; + var points = new[] { Map(x1, y1), Map(x2, y1), Map(x2, y2), Map(x1, y2) }; + if (buildingPath) + { + EmitFigure(points, true, false); + return; + } + Fill(points); + points = new[] { Map(x1, y1), Map(x2 - 1, y1), Map(x2 - 1, y2 - 1), Map(x1, y2 - 1) }; + for (var i = 0; i < 4; i++) Stroke(points[i], points[(i + 1) % 4]); + } + + private void Fill(IReadOnlyList<(double X, double Y)> points, bool applyRasterOperation = true) => + FillFigures(new[] { points }, applyRasterOperation); + + private void FillFigures(IReadOnlyList> figures, bool applyRasterOperation = true) + { + if (state.Brush.IsNull || figures.Count == 0 || (applyRasterOperation && state.RasterOperation == 11)) return; + var color = applyRasterOperation ? RasterColor(state.Brush.Color) : state.Brush.Color; + var pointCount = figures.Sum(figure => figure.Count); + if (pointCount == 0) return; + var minY = figures.SelectMany(figure => figure).Min(point => point.Y); + var maxY = figures.SelectMany(figure => figure).Max(point => point.Y); + var firstRow = Bound(minY, state.ClipTop, state.ClipBottom); + var lastRow = Bound(maxY + 1, state.ClipTop, state.ClipBottom); + var intersections = new List<(double X, int Direction)>(); + for (var row = firstRow; row < lastRow; row++) + { + Spend(pointCount); + intersections.Clear(); + var sampleY = row + 0.5; + foreach (var points in figures) + { + for (var index = 0; index < points.Count; index++) + { + var a = points[index]; + var b = points[(index + 1) % points.Count]; + if ((a.Y <= sampleY && b.Y > sampleY) || (b.Y <= sampleY && a.Y > sampleY)) + intersections.Add((a.X + (sampleY - a.Y) / (b.Y - a.Y) * (b.X - a.X), b.Y > a.Y ? 1 : -1)); + } + } + intersections.Sort((a, b) => a.X.CompareTo(b.X)); + var winding = 0; + for (var index = 0; index + 1 < intersections.Count; index++) + { + winding += intersections[index].Direction; + var inside = state.Winding ? winding != 0 : (index & 1) == 0; + if (!inside) continue; + var start = Bound(Math.Ceiling(intersections[index].X - 0.5), state.ClipLeft, state.ClipRight); + var end = Bound(Math.Ceiling(intersections[index + 1].X - 0.5), state.ClipLeft, state.ClipRight); + Spend(end - start); + for (var column = start; column < end; column++) PutPixel(column, row, color); + } + } + } + + private void Stroke((double X, double Y) a, (double X, double Y) b) + { + if (state.Pen.IsNull || state.RasterOperation == 11) return; + if (state.Pen.Width == 0) + { + StrokeCosmetic(a, b); + return; + } + if (state.Pen.Width > 0 && (state.World.M11 != 1 || state.World.M12 != 0 || + state.World.M21 != 0 || state.World.M22 != 1)) + throw new NotSupportedException("World-transformed noncosmetic EMF pens are not supported."); + var penScaleX = scaleX; + var penScaleY = scaleY; + if (state.MapMode == 8 && state.Pen.Width > 0) + { + penScaleX *= Math.Abs((double)state.ViewportWidth / state.WindowWidth); + penScaleY *= Math.Abs((double)state.ViewportHeight / state.WindowHeight); + } + if (state.Pen.Width * Math.Max(penScaleX, penScaleY) > 1) + throw new NotSupportedException("Scaled EMF pens wider than one device pixel are not supported."); + StrokeCosmetic(a, b); + } + + private void StrokeCosmetic((double X, double Y) a, (double X, double Y) b) + { + if (state.ClipLeft >= state.ClipRight || state.ClipTop >= state.ClipBottom) return; + if (Math.Abs(a.X) > 1e12 || Math.Abs(a.Y) > 1e12 || Math.Abs(b.X) > 1e12 || Math.Abs(b.Y) > 1e12) + throw new InvalidDataException("EMF cosmetic stroke coordinate precision limit exceeded."); + var dx = b.X - a.X; + var dy = b.Y - a.Y; + var first = 0d; + var last = 1d; + if (!Clip(-dx, a.X - state.ClipLeft + 1) || !Clip(dx, state.ClipRight - a.X) || + !Clip(-dy, a.Y - state.ClipTop + 1) || !Clip(dy, state.ClipBottom - a.Y)) return; + var x = Bound(Math.Floor(a.X + first * dx + 0.5), state.ClipLeft - 1, state.ClipRight); + var y = Bound(Math.Floor(a.Y + first * dy + 0.5), state.ClipTop - 1, state.ClipBottom); + var endX = Bound(Math.Floor(a.X + last * dx + 0.5), state.ClipLeft - 1, state.ClipRight); + var endY = Bound(Math.Floor(a.Y + last * dy + 0.5), state.ClipTop - 1, state.ClipBottom); + var stepX = x < endX ? 1 : -1; + var stepY = y < endY ? 1 : -1; + var lengthX = Math.Abs(endX - x); + var lengthY = Math.Abs(endY - y); + Spend((long)Math.Max(lengthX, lengthY) + 1); + var error = lengthX - lengthY; + while (true) + { + if (x == endX && y == endY) + { + if (last < 1) PutPixel(x, y, RasterColor(state.Pen.Color)); + return; + } + PutPixel(x, y, RasterColor(state.Pen.Color)); + var twiceError = error * 2; + if (twiceError > -lengthY) { error -= lengthY; x += stepX; } + if (twiceError < lengthX) { error += lengthX; y += stepY; } + } + + bool Clip(double direction, double distance) + { + if (direction == 0) return distance >= 0; + var fraction = distance / direction; + if (direction < 0) + { + if (fraction > last) return false; + first = Math.Max(first, fraction); + } + else + { + if (fraction < first) return false; + last = Math.Min(last, fraction); + } + return true; + } + } + + private (double X, double Y) Map(double x, double y) + { + var transformedX = x * state.World.M11 + y * state.World.M21 + state.World.X; + y = x * state.World.M12 + y * state.World.M22 + state.World.Y; + x = transformedX; + var deviceX = (double)x; + var deviceY = (double)y; + if (state.MapMode == 8) + { + deviceX = ((double)x - state.WindowX) * state.ViewportWidth / state.WindowWidth + state.ViewportX; + deviceY = ((double)y - state.WindowY) * state.ViewportHeight / state.WindowHeight + state.ViewportY; + } + else + { + deviceX += (double)state.ViewportX - state.WindowX; + deviceY += (double)state.ViewportY - state.WindowY; + } + return MapDevice(deviceX, deviceY); + } + + private (double X, double Y) MapDevice(double x, double y) + { + var mapped = ((x - left) * scaleX, (y - top) * scaleY); + if (double.IsNaN(mapped.Item1) || double.IsNaN(mapped.Item2) || + Math.Abs(mapped.Item1) > 1e50 || Math.Abs(mapped.Item2) > 1e50) + throw new InvalidDataException("EMF mapped coordinate limit exceeded."); + return mapped; + } + + private void ReadComment(int offset) + { + var length = U32(offset + 8); + var available = recordEnd - offset - 12; + if (length > available || available - length > 3) + throw new InvalidDataException("Invalid EMF comment data length."); + if (length < 4) return; + var identifier = U32(offset + 12); + if (identifier == 0x2B464D45) + { + ReadGdiOnlyPlusComment(offset + 16, offset + 12 + (int)length); + return; + } + if (identifier == 0) + throw new NotSupportedException("EMFSPOOL comments are not supported."); + if (identifier != 0x43494447) return; + if (length < 8) throw new InvalidDataException("Truncated public EMF comment."); + switch (U32(offset + 16)) + { + case 2: + if (length < 28 || U32(offset + 36) > (length - 28) / 2) + throw new InvalidDataException("Invalid EMF comment group description."); + if (commentGroups >= 1024) throw new InvalidDataException("EMF comment group nesting limit exceeded."); + commentGroups++; + break; + case 3: + if (length != 8 || commentGroups == 0) + throw new InvalidDataException("Invalid EMF comment group end."); + commentGroups--; + break; + case 0x80000001: + if (length < 24 || U32(offset + 32) != length - 24) + throw new InvalidDataException("Invalid original WMF comment length."); + if (U32(offset + 28) != 0) + throw new NotSupportedException("Original WMF comment flags are not supported."); + // This is an equivalent original WMF, not additional drawing commands. + break; + default: + throw new NotSupportedException("This public EMF comment extension is not supported."); + } + } + + private void ReadGdiOnlyPlusComment(int position, int end) + { + if (position == end) throw new InvalidDataException("Empty EMF+ comment."); + if (path != null) throw new NotSupportedException("An EMF path cannot cross an EMF+ comment."); + plusDc = false; + while (position < end) + { + Spend(1); + if (position > end - 12) throw new InvalidDataException("Truncated EMF+ record header."); + var type = U16(position); + var flags = U16(position + 2); + var size = U32(position + 4); + var dataSize = U32(position + 8); + if (size < 12 || size % 4 != 0 || size > end - position || dataSize > size - 12 || + ((long)dataSize + 3) / 4 * 4 != size - 12) + throw new InvalidDataException("Invalid EMF+ record size."); + if (plusEnded || (!plusStarted && type != 0x4001)) + throw new InvalidDataException("Invalid EMF+ record order."); + switch (type) + { + case 0x4001: + if (plusStarted || dataSize != 16 || (flags & ~1) != 0 || + (U32(position + 12) & 0xFFFFF000) != 0xDBC01000 || + (U32(position + 12) & 0xFFF) is not (1 or 2) || + (U32(position + 16) & ~1u) != 0 || U32(position + 20) == 0 || U32(position + 24) == 0) + throw new InvalidDataException("Invalid EMF+ header."); + plusStarted = true; + break; + case 0x4002: + if (dataSize != 0 || flags != 0) throw new InvalidDataException("Invalid EMF+ EOF."); + plusEnded = true; + plusDc = false; + break; + case 0x4004: + if (dataSize != 0 || flags != 0) throw new InvalidDataException("Invalid EMF+ GetDC."); + if (plusUsedDc || plusWorld.M11 != 1 || plusWorld.M22 != 1 || plusWorld.M12 != 0 || + plusWorld.M21 != 0 || plusWorld.X != 0 || plusWorld.Y != 0) + throw new NotSupportedException("Repeated or transformed EMF+ GetDC is not supported."); + plusDc = plusUsedDc = true; + break; + case 0x401E: + case 0x4021: + case 0x4022: + case 0x4024: + if (dataSize != 0 || (flags & 0xFF00) != 0) + throw new InvalidDataException("Invalid EMF+ rendering-quality state."); + break; + case 0x4030: + if (dataSize != 4) throw new InvalidDataException("Invalid EMF+ page transform."); + if (flags != 2 || ReadFloat(position + 12) != 1) + throw new NotSupportedException("Only identity pixel-unit EMF+ page transforms are supported."); + break; + case 0x402A: + if (dataSize != 24 || flags != 0) throw new InvalidDataException("Invalid EMF+ world transform."); + plusWorld = ReadWorldTransform(position + 12); + break; + case 0x402B: + if (dataSize != 0 || flags != 0) throw new InvalidDataException("Invalid EMF+ world-transform reset."); + plusWorld = WorldTransform.Identity; + break; + default: + throw new NotSupportedException($"EMF+ record 0x{type:X4} requires unsupported EMF+ drawing or state semantics."); + } + position += (int)size; + } + } + + private void SelectClipRegion(int offset) + { + Require(offset, 16); + var size = U32(offset + 8); + var mode = U32(offset + 12); + if (size > recordEnd - offset - 16 || mode < 1 || mode > 5) + throw new InvalidDataException("Invalid EMF clipping region size or mode."); + if (mode != 1 && mode != 5) + throw new NotSupportedException("Only copy and intersect EMF clipping regions are supported."); + if (size == 0) + { + if (mode != 5) throw new InvalidDataException("Only copy mode permits a null EMF clipping region."); + state.ClipLeft = state.ClipTop = 0; + state.ClipRight = width; state.ClipBottom = height; + return; + } + if (size < 32 || U32(offset + 16) != 32 || U32(offset + 20) != 1) + throw new InvalidDataException("Invalid EMF region header."); + var rectangles = U32(offset + 24); + if (rectangles > (size - 32) / 16 || size != 32L + rectangles * 16L || U32(offset + 28) != rectangles * 16L) + throw new InvalidDataException("Invalid EMF region rectangle count."); + if (rectangles > 1) + throw new NotSupportedException("Multiple-rectangle EMF clipping regions are not supported."); + if (rectangles == 0) + { + state.ClipLeft = state.ClipRight = state.ClipTop = state.ClipBottom = 0; + return; + } + var l = I32(offset + 48); var t = I32(offset + 52); + var r = I32(offset + 56); var b = I32(offset + 60); + if (l > r || t > b) throw new InvalidDataException("Inverted EMF region rectangle."); + // Region data is in reference-device coordinates, unlike logical clip rectangles. + var a = MapDevice(l, t); + var z = MapDevice(r, b); + var clipLeft = mode == 5 ? 0 : state.ClipLeft; + var clipTop = mode == 5 ? 0 : state.ClipTop; + var clipRight = mode == 5 ? width : state.ClipRight; + var clipBottom = mode == 5 ? height : state.ClipBottom; + state.ClipLeft = Bound(Math.Ceiling(a.X - 0.5), clipLeft, clipRight); + state.ClipRight = Bound(Math.Ceiling(z.X - 0.5), state.ClipLeft, clipRight); + state.ClipTop = Bound(Math.Ceiling(a.Y - 0.5), clipTop, clipBottom); + state.ClipBottom = Bound(Math.Ceiling(z.Y - 0.5), state.ClipTop, clipBottom); + } + + private WorldTransform ReadWorldTransform(int offset) => new( + ReadFloat(offset), ReadFloat(offset + 4), ReadFloat(offset + 8), + ReadFloat(offset + 12), ReadFloat(offset + 16), ReadFloat(offset + 20)); + + private void ModifyWorldTransform(int offset) + { + var mode = U32(offset + 32); + if (mode == 1) state.World = WorldTransform.Identity; + else if (mode == 2) state.World = WorldTransform.Multiply(ReadWorldTransform(offset + 8), state.World); + else if (mode == 3) state.World = WorldTransform.Multiply(state.World, ReadWorldTransform(offset + 8)); + else throw new NotSupportedException($"EMF world-transform modification mode {mode} is not supported."); + } + + private (double X, double Y) CurrentPathPoint() => Map(state.CurrentX, state.CurrentY); + + private PathFigure AddFigure(IReadOnlyList<(double X, double Y)> points, bool closed) + { + RequireOpenPath(); + var figures = path ?? throw new InvalidDataException("No EMF path to extend."); + if (figures.Count >= 65_536 || points.Count > 1_000_000 - pathPointCount) + throw new InvalidDataException("EMF path point or figure limit exceeded."); + Spend(points.Count); + var figure = new PathFigure(points, closed); + figures.Add(figure); + pathPointCount += points.Count; + return figure; + } + + private void EmitFigure(IReadOnlyList<(double X, double Y)> points, bool closed, bool continues) + { + if (buildingPath) + { + if (continues && activeFigure != null && activeFigure.Points[activeFigure.Points.Count - 1] == points[0]) + { + if (points.Count - 1 > 1_000_000 - pathPointCount) + throw new InvalidDataException("EMF path point limit exceeded."); + Spend(points.Count - 1); + for (var index = 1; index < points.Count; index++) activeFigure.Points.Add(points[index]); + pathPointCount += points.Count - 1; + activeFigure.Closed = closed; + } + else activeFigure = AddFigure(points, closed); + if (!continues || closed) activeFigure = null; + return; + } + if (closed) Fill(points); + StrokeFigure(points, closed); + } + + private void StrokeFigure(IReadOnlyList<(double X, double Y)> points, bool closed) + { + for (var index = 1; index < points.Count; index++) Stroke(points[index - 1], points[index]); + if (closed && points.Count > 1) Stroke(points[points.Count - 1], points[0]); + } + + private void RequireOpenPath() + { + if (!buildingPath || path == null) throw new InvalidDataException("No open EMF path bracket."); + } + + private void PaintPath(bool fill, bool stroke) + { + var figures = path; + if (figures == null || buildingPath) throw new InvalidDataException("No completed EMF path to paint."); + if (fill) FillFigures(figures.Select(figure => (IReadOnlyList<(double X, double Y)>)figure.Points).ToArray()); + if (stroke) + foreach (var figure in figures) StrokeFigure(figure.Points, figure.Closed || fill); + ClearPath(); + } + + private void ClearPath() + { + path = null; + activeFigure = null; + buildingPath = false; + pathPointCount = 0; + } + + private List<(double X, double Y)> FlattenBeziers(IReadOnlyList<(double X, double Y)> points) + { + var result = new List<(double X, double Y)> { points[0] }; + for (var index = 1; index < points.Count; index += 3) + Subdivide(points[index - 1], points[index], points[index + 1], points[index + 2], 0); + return result; + + void Subdivide((double X, double Y) a, (double X, double Y) b, + (double X, double Y) c, (double X, double Y) d, int depth) + { + Spend(1); + if (result.Count >= 1_000_000) throw new InvalidDataException("EMF curve point limit exceeded."); + var dx = d.X - a.X; + var dy = d.Y - a.Y; + var lengthSquared = dx * dx + dy * dy; + if (Flat(b) && Flat(c)) + { + result.Add(d); + return; + } + if (depth >= 20) throw new InvalidDataException("EMF curve subdivision limit exceeded."); + var ab = Midpoint(a, b); + var bc = Midpoint(b, c); + var cd = Midpoint(c, d); + var abc = Midpoint(ab, bc); + var bcd = Midpoint(bc, cd); + var middle = Midpoint(abc, bcd); + Subdivide(a, ab, abc, middle, depth + 1); + Subdivide(middle, bcd, cd, d, depth + 1); + + bool Flat((double X, double Y) point) + { + var px = point.X - a.X; + var py = point.Y - a.Y; + if (lengthSquared == 0) return px * px + py * py <= 0.015625; + var projection = px * dx + py * dy; + if (projection < 0) return px * px + py * py <= 0.015625; + if (projection > lengthSquared) + { + var endX = point.X - d.X; + var endY = point.Y - d.Y; + return endX * endX + endY * endY <= 0.015625; + } + var cross = px * dy - py * dx; + return cross * cross <= 0.015625 * lengthSquared; + } + } + } + + private static (double X, double Y) Midpoint((double X, double Y) a, (double X, double Y) b) => + ((a.X + b.X) / 2, (a.Y + b.Y) / 2); + + private void CreateFont(int offset) + { + Require(offset, 104); + var height = I32(offset + 12); + var fontWidth = I32(offset + 16); + if (height == 0 || fontWidth < 0 || I32(offset + 20) != 0 || I32(offset + 24) != 0 || + source[offset + 33] != 0 || source[offset + 34] != 0) + throw new NotSupportedException("EMF fonts require nonzero height, nonnegative width and no rotation or decorations."); + var weight = I32(offset + 28); + if (weight != 0 && weight != 400 && weight != 700) + throw new NotSupportedException("Only regular and bold EMF font weights are supported."); + var name = System.Text.Encoding.Unicode.GetString(source, offset + 40, 64).Split('\0')[0]; + if (string.IsNullOrWhiteSpace(name) || name.StartsWith("@", StringComparison.Ordinal)) + throw new NotSupportedException("An explicit horizontal EMF font face is required."); + var handle = U32(offset + 8); + CheckNewHandle(handle); + fonts.Add(handle, new MetafileFont(name, height, fontWidth, weight == 700, source[offset + 32] != 0)); + } + + private void DrawText(int offset) + { + Require(offset, 76); + if (buildingPath) throw new NotSupportedException("EMF text inside a path bracket is not supported."); + var graphicsMode = U32(offset + 24); + var xScale = ReadFloat(offset + 28); + var yScale = ReadFloat(offset + 32); + if (graphicsMode != 1 && graphicsMode != 2) + throw new NotSupportedException("Unsupported EMF text graphics mode."); + if (graphicsMode == 1 && (xScale <= 0 || yScale <= 0)) + throw new NotSupportedException("Nonpositive compatible-mode EMF text scales are not supported."); + var count = U32(offset + 44); + var options = U32(offset + 52); + if ((options & ~0x2016u) != 0) + throw new NotSupportedException("Unsupported EMF text options or shaping."); + if (count > 65_536) throw new InvalidDataException("EMF text character limit exceeded."); + var stringOffset = count == 0 ? 0 : BitmapRange(offset, U32(offset + 48), count * 2, 76); + var pairedSpacing = (options & 0x2000) != 0; + var spacingOffset = U32(offset + 72) == 0 || count == 0 ? 0 + : BitmapRange(offset, U32(offset + 72), count * (pairedSpacing ? 8u : 4u), 76); + if (count > 0 && ((state.TextAlignment is not (0 or 2 or 6 or 24 or 26 or 30)) || + state.BackgroundMode != 1 || + (pairedSpacing && (state.TextAlignment & 6) != 0))) + throw new NotSupportedException("EMF text requires transparent top or baseline layout; paired spacing requires left alignment."); + var savedBrush = state.Brush; + var savedWinding = state.Winding; + var clip = (state.ClipLeft, state.ClipTop, state.ClipRight, state.ClipBottom); + try + { + if ((options & 4) != 0) IntersectClip(offset + 48); + if ((options & 2) != 0) + { + state.Brush = new DrawingObject(false, state.BackgroundColor); + Fill(new[] { Map(I32(offset + 56), I32(offset + 60)), Map(I32(offset + 64), I32(offset + 60)), + Map(I32(offset + 64), I32(offset + 68)), Map(I32(offset + 56), I32(offset + 68)) }, false); + } + if (count == 0) return; + var font = state.Font ?? throw new NotSupportedException("An explicit EMF font must be selected before drawing text."); + var resolver = fontResolver ?? throw new NotSupportedException("EMF text requires an explicit TrueType font resolver."); + var outlines = font.Outlines ??= new TrueTypeGlyphReader(resolver(font.Name, font.Bold, font.Italic)); + var emScale = font.Height < 0 ? -font.Height / outlines.UnitsPerEm : font.Height / outlines.CellHeight; + var horizontalScale = font.Width == 0 ? emScale : (double)font.Width / outlines.AverageWidth; + // Compatible scales describe physical units; their ratio adjusts glyph width, not supplied advances. + if (graphicsMode == 1) horizontalScale *= (double)yScale / xScale; + var syntheticBoldOffset = 0d; + if (font.Bold && outlines.NeedsSyntheticBold) + { + RequireAxisAlignedWorldTransform("synthetic bold text"); + var deviceStep = Map(1, 0).X - Map(0, 0).X; + if (deviceStep <= 0) throw new NotSupportedException("Synthetic bold text requires a positive horizontal device scale."); + syntheticBoldOffset = 1 / deviceStep; + } + var glyphs = new ushort[count]; + var dx = new double[count]; + var dy = new double[count]; + double totalWidth = 0; + for (var index = 0; index < count; index++) + { + var value = U16(stringOffset + index * 2); + if ((options & 16) != 0) glyphs[index] = value; + else + { + if (!IsSimpleTextCharacter(value)) + throw new NotSupportedException("This EMF Unicode text requires shaping or glyph indices."); + glyphs[index] = outlines.GlyphForCharacter(value); + } + dx[index] = spacingOffset == 0 ? outlines.Advance(glyphs[index]) * horizontalScale + syntheticBoldOffset + : I32(spacingOffset + index * (pairedSpacing ? 8 : 4)); + dy[index] = spacingOffset != 0 && pairedSpacing ? I32(spacingOffset + index * 8 + 4) : 0; + totalWidth += dx[index]; + } + var x = (double)I32(offset + 36); + var y = (double)I32(offset + 40); + if ((state.TextAlignment & 24) == 0) y += outlines.CellAscent * emScale; + if ((state.TextAlignment & 6) == 2) x -= totalWidth; + else if ((state.TextAlignment & 6) == 6) x -= totalWidth / 2; + state.Brush = new DrawingObject(false, state.TextColor); + state.Winding = true; + for (var index = 0; index < count; index++) + { + Spend(1); + var contours = outlines.ReadGlyph(glyphs[index]); + FillFigures(contours.Select(contour => GlyphContour(contour, x, y, horizontalScale, emScale)).ToArray(), false); + if (syntheticBoldOffset != 0) + FillFigures(contours.Select(contour => GlyphContour(contour, x + syntheticBoldOffset, y, horizontalScale, emScale)).ToArray(), false); + x += dx[index]; y += dy[index]; + } + + } + finally + { + state.Brush = savedBrush; + state.Winding = savedWinding; + (state.ClipLeft, state.ClipTop, state.ClipRight, state.ClipBottom) = clip; + } + } + + private static bool IsSimpleTextCharacter(ushort value) => + value is >= 0x20 and <= 0x7E or >= 0xA0 and <= 0x24F or >= 0x1E00 and <= 0x1EFF + or >= 0x3000 and <= 0x303F or >= 0x3400 and <= 0x4DBF or >= 0x4E00 and <= 0x9FFF + or >= 0xF900 and <= 0xFAFF; + + private IReadOnlyList<(double X, double Y)> GlyphContour( + IReadOnlyList contour, double x, double y, double horizontalScale, double verticalScale) + { + Spend(contour.Count); + var first = contour[0]; + var last = contour[contour.Count - 1]; + var start = first.OnCurve ? (first.X, first.Y) : last.OnCurve ? (last.X, last.Y) + : ((last.X + first.X) / 2, (last.Y + first.Y) / 2); + var current = start; + var result = new List<(double X, double Y)> { MapGlyph(start) }; + for (var index = first.OnCurve ? 1 : 0; index < contour.Count;) + { + var point = contour[index]; + if (point.OnCurve) + { + current = (point.X, point.Y); + result.Add(MapGlyph(current)); + index++; + } + else + { + var next = contour[(index + 1) % contour.Count]; + var end = next.OnCurve ? (next.X, next.Y) : ((point.X + next.X) / 2, (point.Y + next.Y) / 2); + var curve = FlattenBeziers(new[] { MapGlyph(current), + MapGlyph((current.Item1 + (point.X - current.Item1) * 2 / 3, current.Item2 + (point.Y - current.Item2) * 2 / 3)), + MapGlyph((end.Item1 + (point.X - end.Item1) * 2 / 3, end.Item2 + (point.Y - end.Item2) * 2 / 3)), MapGlyph(end) }); + result.AddRange(curve.Skip(1)); + current = end; + index += next.OnCurve ? 2 : 1; + } + if (result.Count > 1_000_000) throw new InvalidDataException("EMF glyph contour point limit exceeded."); + } + return result; + + (double X, double Y) MapGlyph((double X, double Y) point) => + Map(x + point.X * horizontalScale, y - point.Y * verticalScale); + } + + private readonly struct ColorMask + { + private readonly uint mask; + private readonly int shift; + private readonly uint maximum; + + internal ColorMask(uint mask, int bitCount) + { + if (mask == 0 || (bitCount == 16 && mask > ushort.MaxValue)) + throw new InvalidDataException("Invalid DIB color mask."); + this.mask = mask; + shift = 0; + while ((mask & 1) == 0) + { + mask >>= 1; + shift++; + } + if ((mask & unchecked(mask + 1)) != 0) + throw new InvalidDataException("Noncontiguous DIB color mask."); + maximum = mask; + } + + internal byte Read(uint value) => (byte)(((ulong)((value & mask) >> shift) * 255 + maximum / 2) / maximum); + } + + private sealed class DibImage + { + internal int Width, Height, Stride, BitsOffset, BitCount; + internal bool TopDown; + internal ColorMask Red, Green, Blue; + } + + private void DrawBitmap(int offset, bool alphaBlend) + { + RequireAxisAlignedWorldTransform("bitmap"); + var fixedSize = alphaBlend ? 108 : 80; + Require(offset, fixedSize); + var xDest = I32(offset + 24); + var yDest = I32(offset + 28); + var destWidth = I32(offset + (alphaBlend ? 32 : 72)); + var destHeight = I32(offset + (alphaBlend ? 36 : 76)); + var sourceX = I32(offset + (alphaBlend ? 44 : 32)); + var sourceY = I32(offset + (alphaBlend ? 48 : 36)); + var sourceWidth = I32(offset + (alphaBlend ? 100 : 40)); + var sourceHeight = I32(offset + (alphaBlend ? 104 : 44)); + if (sourceWidth == 0 || sourceHeight == 0) + throw new InvalidDataException("Empty EMF bitmap source rectangle."); + if (sourceWidth < 0 || sourceHeight < 0 || (alphaBlend && (destWidth < 0 || destHeight < 0))) + throw new NotSupportedException("Mirrored source or alpha-blend extents are not supported."); + var useAlpha = false; + var constantAlpha = 255; + if (alphaBlend) + { + var blend = U32(offset + 40); + // Recorded GDI playback ignores the reserved BlendFlags byte. + if ((blend & 0xFF) != 0 || (blend >> 24) > 1) + throw new NotSupportedException("Unsupported EMF alpha-blend operation or alpha format."); + constantAlpha = (int)(blend >> 16 & 255); + useAlpha = blend >> 24 == 1; + if (ReadFloat(offset + 52) != 1 || ReadFloat(offset + 56) != 0 || + ReadFloat(offset + 60) != 0 || ReadFloat(offset + 64) != 1 || + ReadFloat(offset + 68) != 0 || ReadFloat(offset + 72) != 0) + throw new NotSupportedException("Transformed EMF source bitmaps are not supported."); + } + else if (U32(offset + 68) != 0x00CC0020) + throw new NotSupportedException("Only SRCCOPY EMF bitmap raster operations are supported."); + if (U32(offset + (alphaBlend ? 80 : 64)) != 0) + throw new NotSupportedException("Palette-indexed EMF bitmap usage is not supported."); + var image = ReadDib(offset, alphaBlend ? 84 : 48, fixedSize, useAlpha); + if (sourceX < 0 || sourceY < 0 || + (long)sourceX + sourceWidth > image.Width || (long)sourceY + sourceHeight > image.Height) + throw new InvalidDataException("EMF bitmap source rectangle is outside the DIB."); + // GDI measures StretchDIBits source crops from the bottom even for + // top-down storage. AlphaBlend instead uses top-left source DC coordinates. + if (!alphaBlend) sourceY = image.Height - sourceY - sourceHeight; + var start = Map(xDest, yDest); + var end = Map((double)xDest + destWidth, (double)yDest + destHeight); + var deltaX = end.X - start.X; + var deltaY = end.Y - start.Y; + // Mirrored GDI extents include the starting pixel, not the ending pixel. + if (deltaX < 0) { start.X++; end.X++; } + if (deltaY < 0) { start.Y++; end.Y++; } + if (deltaX == 0 || deltaY == 0) return; + if (!alphaBlend && state.StretchMode != 3 && + (Math.Abs(deltaX) != sourceWidth || Math.Abs(deltaY) != sourceHeight)) + throw new NotSupportedException("Only COLORONCOLOR EMF bitmap resampling is supported."); + var firstColumn = Bound(Math.Ceiling(Math.Min(start.X, end.X) - 0.5), state.ClipLeft, state.ClipRight); + var lastColumn = Bound(Math.Ceiling(Math.Max(start.X, end.X) - 0.5), state.ClipLeft, state.ClipRight); + var firstRow = Bound(Math.Ceiling(Math.Min(start.Y, end.Y) - 0.5), state.ClipTop, state.ClipBottom); + var lastRow = Bound(Math.Ceiling(Math.Max(start.Y, end.Y) - 0.5), state.ClipTop, state.ClipBottom); + Spend((long)(lastColumn - firstColumn) * (lastRow - firstRow)); + for (var row = firstRow; row < lastRow; row++) + { + var sy = sourceY + Bound(Math.Floor((row + 0.5 - start.Y) / deltaY * sourceHeight), 0, sourceHeight - 1); + var storageRow = image.TopDown ? sy : image.Height - 1 - sy; + for (var column = firstColumn; column < lastColumn; column++) + { + var sx = sourceX + Bound(Math.Floor((column + 0.5 - start.X) / deltaX * sourceWidth), 0, sourceWidth - 1); + var pixel = image.BitsOffset + storageRow * image.Stride + sx * (image.BitCount / 8); + uint value = (uint)(source[pixel] | source[pixel + 1] << 8); + if (image.BitCount >= 24) value |= (uint)source[pixel + 2] << 16; + if (image.BitCount == 32) value |= (uint)source[pixel + 3] << 24; + var red = image.Red.Read(value); + var green = image.Green.Read(value); + var blue = image.Blue.Read(value); + if (alphaBlend) + BlendPixel(column, row, red, green, blue, useAlpha ? source[pixel + 3] : (byte)255, constantAlpha); + else + PutPixel(column, row, (uint)(red | green << 8 | blue << 16)); + } + } + } + + private DibImage ReadDib(int record, int fieldsOffset, int fixedSize, bool useAlpha) + { + var infoSize = U32(record + fieldsOffset + 4); + var bitsSize = U32(record + fieldsOffset + 12); + var info = BitmapRange(record, U32(record + fieldsOffset), infoSize, fixedSize); + var bits = BitmapRange(record, U32(record + fieldsOffset + 8), bitsSize, fixedSize); + if ((long)info < bits + (long)bitsSize && (long)bits < info + (long)infoSize) + throw new InvalidDataException("Overlapping EMF bitmap information and pixel data."); + if (infoSize < 40) throw new InvalidDataException("Truncated DIB header."); + var headerSize = U32(info); + if (headerSize > infoSize) throw new InvalidDataException("Truncated DIB header."); + if (headerSize != 40) throw new NotSupportedException($"DIB header size {headerSize} is not supported."); + var imageWidth = I32(info + 4); + var signedHeight = I32(info + 8); + var imageHeight = Math.Abs((long)signedHeight); + if (imageWidth <= 0 || imageHeight == 0 || (long)imageWidth * imageHeight > 16_777_216) + throw new InvalidDataException("Invalid DIB dimensions or bitmap pixel limit exceeded."); + if (U16(info + 12) != 1) throw new InvalidDataException("Invalid DIB plane count."); + var bitCount = U16(info + 14); + var compression = U32(info + 16); + if (bitCount is not (16 or 24 or 32) || (compression != 0 && compression != 3) || + (compression == 3 && bitCount == 24)) + throw new NotSupportedException("Unsupported DIB bit depth or compression."); + if (useAlpha && bitCount != 32) + throw new InvalidDataException("Per-pixel alpha blending requires a 32-bit DIB."); + var stride = ((long)imageWidth * bitCount + 31) / 32 * 4; + var requiredSize = stride * imageHeight; + if (requiredSize > bitsSize) + throw new InvalidDataException("Truncated DIB pixel data."); + var declaredSize = U32(info + 20); + if (declaredSize != 0 && (declaredSize < requiredSize || declaredSize > bitsSize)) + throw new InvalidDataException("Invalid DIB image byte count."); + uint red = bitCount == 16 ? 0x7C00u : 0xFF0000u; + uint green = bitCount == 16 ? 0x03E0u : 0x00FF00u; + uint blue = bitCount == 16 ? 0x001Fu : 0x0000FFu; + if (compression == 3) + { + if (infoSize < 52) throw new InvalidDataException("Missing DIB color masks."); + red = U32(info + 40); + green = U32(info + 44); + blue = U32(info + 48); + if ((red & green) != 0 || (red & blue) != 0 || (green & blue) != 0) + throw new InvalidDataException("Overlapping DIB color masks."); + } + if (useAlpha && (red != 0xFF0000 || green != 0x00FF00 || blue != 0x0000FF)) + throw new NotSupportedException("Per-pixel alpha requires standard BGRA DIB channels."); + return new DibImage + { + Width = imageWidth, Height = (int)imageHeight, Stride = (int)stride, + BitsOffset = bits, BitCount = bitCount, TopDown = signedHeight < 0, + Red = new ColorMask(red, bitCount), Green = new ColorMask(green, bitCount), Blue = new ColorMask(blue, bitCount) + }; + } + + private int BitmapRange(int record, uint relativeOffset, uint size, int fixedSize) + { + var available = recordEnd - record; + if (relativeOffset < fixedSize || relativeOffset > available || size > available - relativeOffset) + throw new InvalidDataException("EMF bitmap range is outside its record."); + return record + (int)relativeOffset; + } + + private float ReadFloat(int offset) + { + Require(offset, 4); + var value = BitConverter.ToSingle(source, offset); + if (float.IsNaN(value) || float.IsInfinity(value)) + throw new InvalidDataException("Nonfinite EMF transform."); + return value; + } + + private void BlendPixel(int x, int y, byte red, byte green, byte blue, byte alpha, int constantAlpha) + { + if (red > alpha || green > alpha || blue > alpha) + throw new InvalidDataException("EMF alpha-blend source pixels must be premultiplied."); + var position = (y * width + x) * 4; + var factor = constantAlpha / 255d; + var sourceAlpha = alpha / 255d * factor; + var destinationAlpha = pixels[position + 3] / 255d; + var remaining = destinationAlpha * (1 - sourceAlpha); + var outputAlpha = sourceAlpha + remaining; + if (outputAlpha == 0) return; + pixels[position] = (byte)Bound((red * factor + pixels[position] * remaining) / outputAlpha + 0.5, 0, 255); + pixels[position + 1] = (byte)Bound((green * factor + pixels[position + 1] * remaining) / outputAlpha + 0.5, 0, 255); + pixels[position + 2] = (byte)Bound((blue * factor + pixels[position + 2] * remaining) / outputAlpha + 0.5, 0, 255); + pixels[position + 3] = (byte)Bound(outputAlpha * 255 + 0.5, 0, 255); + } + + private void IntersectClip(int offset) + { + RequireAxisAlignedWorldTransform("rectangular clipping"); + var a = Map(I32(offset + 8), I32(offset + 12)); + var b = Map(I32(offset + 16), I32(offset + 20)); + state.ClipLeft = Bound(Math.Ceiling(Math.Min(a.X, b.X) - 0.5), state.ClipLeft, state.ClipRight); + state.ClipRight = Bound(Math.Ceiling(Math.Max(a.X, b.X) - 0.5), state.ClipLeft, state.ClipRight); + state.ClipTop = Bound(Math.Ceiling(Math.Min(a.Y, b.Y) - 0.5), state.ClipTop, state.ClipBottom); + state.ClipBottom = Bound(Math.Ceiling(Math.Max(a.Y, b.Y) - 0.5), state.ClipTop, state.ClipBottom); + } + + private void RequireAxisAlignedWorldTransform(string operation) + { + if (state.World.M12 != 0 || state.World.M21 != 0) + throw new NotSupportedException($"Rotated or sheared EMF {operation} is not supported."); + } + + private void Restore(int level) + { + if (path != null) + throw new NotSupportedException("Restoring a device context with a pending EMF path is not supported."); + var index = level < 0 ? (long)savedStates.Count + level : (long)level - 1; + if (level == 0 || index < 0 || index >= savedStates.Count) + throw new InvalidDataException("Invalid EMF saved device context."); + state = savedStates[(int)index]; + savedStates.RemoveRange((int)index, savedStates.Count - (int)index); + } + + private void AddObject(uint handle, DrawingObject value) + { + CheckColor(value.Color); + CheckNewHandle(handle); + objects.Add(handle, value); + } + + private void CheckNewHandle(uint handle) + { + if (handle == 0 || handle >= handleCount || objects.ContainsKey(handle) || fonts.ContainsKey(handle)) + throw new InvalidDataException("Invalid or duplicate EMF object handle."); + } + + private void Select(uint handle) + { + if ((handle & 0x80000000) != 0 && (handle & 0x7FFFFFFF) is 10 or 11 or 12 or 13 or 14 or 16 or 17) + { + // Stock font selection is valid; unsupported outlines are required only when text is drawn. + state.Font = null; + return; + } + if (fonts.TryGetValue(handle, out var font)) + { + state.Font = font; + return; + } + DrawingObject value; + if ((handle & 0x80000000) != 0) + { + value = (handle & 0x7FFFFFFF) switch + { + 0 => new DrawingObject(false, 0xFFFFFF), + 4 => new DrawingObject(false, 0), + 5 => new DrawingObject(false, 0, true), + 6 => new DrawingObject(true, 0xFFFFFF), + 7 => new DrawingObject(true, 0), + 8 => new DrawingObject(true, 0, true), + _ => throw new NotSupportedException($"EMF stock object {handle} is not supported.") + }; + } + else if (!objects.TryGetValue(handle, out value)) + throw new InvalidDataException("Selecting an unknown EMF object."); + if (value.IsPen) state.Pen = value; + else state.Brush = value; + } + + private void PutPixel(int x, int y, uint color) + { + if (x < state.ClipLeft || x >= state.ClipRight || y < state.ClipTop || y >= state.ClipBottom) return; + var position = (y * width + x) * 4; + pixels[position] = (byte)color; + pixels[position + 1] = (byte)(color >> 8); + pixels[position + 2] = (byte)(color >> 16); + pixels[position + 3] = 255; + } + + private uint RasterColor(uint color) => state.RasterOperation switch + { + 1 => 0, + 4 => ~color & 0xFFFFFF, + 13 => color, + 16 => 0xFFFFFF, + _ => throw new InvalidDataException("Invalid EMF raster painting state.") + }; + + private void Require(int offset, int count) + { + if (offset < 0 || count < 0 || offset > recordEnd - count) + throw new InvalidDataException("Truncated EMF record."); + } + + private ushort U16(int offset) + { + Require(offset, 2); + return (ushort)(source[offset] | source[offset + 1] << 8); + } + + private uint U32(int offset) + { + Require(offset, 4); + return (uint)(source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24); + } + + private int I32(int offset) => unchecked((int)U32(offset)); + private static int Bound(double value, int min, int max) => (int)Math.Max(min, Math.Min(max, value)); + private static int Nonzero(int value) => value != 0 ? value : throw new InvalidDataException("Zero EMF mapping extent."); + + private static void CheckColor(uint color) + { + // PALETTERGB is a direct RGB request on this true-color surface, unlike PALETTEINDEX. + if ((color & 0xFF000000) is not (0 or 0x02000000)) + throw new NotSupportedException("Indexed palettes and this EMF color encoding are not supported."); + } + + private void Spend(long work) + { + remainingWork -= work; + if (remainingWork < 0) throw new InvalidDataException("EMF rendering work limit exceeded."); + } + + private byte[] EncodePng(float cropLeft, float cropTop, float cropRight, float cropBottom) + { + var x = 0; var y = 0; var encodedWidth = width; var encodedHeight = height; + if (cropLeft > 0 || cropTop > 0 || cropRight > 0 || cropBottom > 0) + { + x = Bound(Math.Round(width * cropLeft), 0, width - 1); + y = Bound(Math.Round(height * cropTop), 0, height - 1); + encodedWidth = Bound(Math.Round(width * (1 - cropLeft - cropRight)), 1, width - x); + encodedHeight = Bound(Math.Round(height * (1 - cropTop - cropBottom)), 1, height - y); + } + using var output = new MemoryStream(); + output.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, 0, 8); + var header = new byte[13]; + WriteBigEndian(header, 0, (uint)encodedWidth); + WriteBigEndian(header, 4, (uint)encodedHeight); + header[8] = 8; + header[9] = 6; + Chunk(output, "IHDR", header); + using var compressed = new MemoryStream(); + compressed.WriteByte(0x78); + compressed.WriteByte(0x9C); + uint sum1 = 1, sum2 = 0; + using (var deflate = new DeflateStream(compressed, CompressionLevel.Optimal, leaveOpen: true)) + { + for (var row = 0; row < encodedHeight; row++) + { + deflate.WriteByte(0); + sum2 = (sum2 + sum1) % 65521; + var start = ((row + y) * width + x) * 4; + deflate.Write(pixels, start, encodedWidth * 4); + for (var index = start; index < start + encodedWidth * 4; index++) + { + sum1 = (sum1 + pixels[index]) % 65521; + sum2 = (sum2 + sum1) % 65521; + } + } + } + var checksum = new byte[4]; + WriteBigEndian(checksum, 0, sum2 << 16 | sum1); + compressed.Write(checksum, 0, 4); + Chunk(output, "IDAT", compressed.ToArray()); + Chunk(output, "IEND", Array.Empty()); + return output.ToArray(); + } + + private static void Chunk(Stream output, string type, byte[] data) + { + var buffer = new byte[checked(data.Length + 12)]; + WriteBigEndian(buffer, 0, (uint)data.Length); + for (var index = 0; index < 4; index++) buffer[index + 4] = (byte)type[index]; + Buffer.BlockCopy(data, 0, buffer, 8, data.Length); + var crc = uint.MaxValue; + for (var index = 4; index < data.Length + 8; index++) + { + crc ^= buffer[index]; + for (var bit = 0; bit < 8; bit++) + crc = crc >> 1 ^ ((crc & 1) != 0 ? 0xEDB88320u : 0u); + } + WriteBigEndian(buffer, data.Length + 8, ~crc); + output.Write(buffer, 0, buffer.Length); + } + + private static void WriteBigEndian(byte[] data, int offset, uint value) + { + data[offset] = (byte)(value >> 24); + data[offset + 1] = (byte)(value >> 16); + data[offset + 2] = (byte)(value >> 8); + data[offset + 3] = (byte)value; + } +} diff --git a/src/MiniPdf/MiniPdf.csproj b/src/MiniPdf/MiniPdf.csproj index cc8d294d..7e79afa5 100644 --- a/src/MiniPdf/MiniPdf.csproj +++ b/src/MiniPdf/MiniPdf.csproj @@ -44,8 +44,6 @@ - - diff --git a/src/MiniPdf/PdfWriter.cs b/src/MiniPdf/PdfWriter.cs index c59f4ffb..3e8daf48 100644 --- a/src/MiniPdf/PdfWriter.cs +++ b/src/MiniPdf/PdfWriter.cs @@ -1861,7 +1861,7 @@ private static bool IsRgbaPng(byte[] data) return false; } - private static bool TryDecodePngToRgb(byte[] data, out int width, out int height, out byte[] rgb, out byte[]? alpha) + internal static bool TryDecodePngToRgb(byte[] data, out int width, out int height, out byte[] rgb, out byte[]? alpha) { width = 1; height = 1; rgb = new byte[] { 255, 255, 255 }; alpha = null; if (data.Length < 33) return false; @@ -2663,9 +2663,53 @@ private static bool TryMeasureFontWidth(FontMeasureInfo font, string text, float return true; } - private static byte[] LoadPreferredTtfFont(string path, string fontName) + internal static byte[] ResolveMetafileFont(string fontName, bool bold, bool italic) + { + var suffix = bold && italic ? " Bold Italic" : bold ? " Bold" : italic ? " Italic" : ""; + byte[]? FindExactBytes(string name) + { + var target = NormalizeFontName(name); + foreach (var registered in MiniPdf.GetRegisteredFonts()) + if (NormalizeFontName(registered.Name) == target) + return LoadPreferredTtfFontBytes(registered.Data, name, true); + var path = FindExactFontByPreferredName(name); + return path == null ? null : LoadPreferredTtfFontBytes(File.ReadAllBytes(path), name, true); + } + bool HasRequestedStyle(byte[] data) + { + if (!bold && !italic) return true; + var (offset, length) = FindTable(data, "OS/2"); + if (offset == 0 || length < 64) + throw new InvalidDataException("Metafile font style requires a valid OS/2 table."); + var weight = ReadU16(data, (int)offset + 4); + var flags = ReadU16(data, (int)offset + 62); + return (!bold || weight >= 600 || (flags & 0x20) != 0) + && (!italic || (flags & 0x201) != 0); + } + if (suffix.Length != 0) + { + var styled = FindExactBytes(fontName + suffix); + if (styled != null && HasRequestedStyle(styled)) return styled; + } + var regular = FindExactBytes(fontName) + ?? throw new NotSupportedException($"Metafile font '{fontName}' is not available; no family substitution was made."); + if (HasRequestedStyle(regular)) return regular; + var (family, _) = ReadFontNames(regular); + if (!string.IsNullOrEmpty(family)) + { + var styled = FindExactBytes(family + suffix); + if (styled != null && HasRequestedStyle(styled)) return styled; + } + if (bold && !italic && new TrueTypeGlyphReader(regular).NeedsSyntheticBold) + return regular; + throw new NotSupportedException($"Metafile font '{fontName}' has no supported requested style (bold={bold}, italic={italic})."); + } + + private static byte[] LoadPreferredTtfFont(string path, string fontName) => + LoadPreferredTtfFontBytes(File.ReadAllBytes(path), fontName, false); + + private static byte[] LoadPreferredTtfFontBytes(byte[] raw, string fontName, bool exactFace) { - var raw = File.ReadAllBytes(path); if (raw.Length > 12 && raw[0] == 't' && raw[1] == 't' && raw[2] == 'c' && raw[3] == 'f') { var numFonts = (int)ReadU32(raw, 8); @@ -2687,7 +2731,7 @@ private static byte[] LoadPreferredTtfFont(string path, string fontName) if (familyKey == target || fullKey == target) return ExtractTtfFromTtc(raw, offset); - if (partialMatchOffset < 0 + if (!exactFace && partialMatchOffset < 0 && ((fullKey.Length > 0 && fullKey.Contains(target, StringComparison.Ordinal)) || (familyKey.Length > 0 && familyKey.Contains(target, StringComparison.Ordinal)) || IsFontAliasMatch(target, fullKey) @@ -2695,6 +2739,8 @@ private static byte[] LoadPreferredTtfFont(string path, string fontName) partialMatchOffset = offset; } + if (exactFace) + throw new NotSupportedException($"No exact '{fontName}' face exists in the TrueType collection."); return ExtractTtfFromTtc(raw, partialMatchOffset >= 0 ? partialMatchOffset : fallbackOffset); } diff --git a/src/MiniPdf/TrueTypeGlyphReader.cs b/src/MiniPdf/TrueTypeGlyphReader.cs new file mode 100644 index 00000000..4bc2bdb9 --- /dev/null +++ b/src/MiniPdf/TrueTypeGlyphReader.cs @@ -0,0 +1,381 @@ +namespace MiniSoftware; + +// Unhinted outlines decoded from the OpenType glyf/loca specification. +internal sealed class TrueTypeGlyphReader +{ + internal readonly struct Point + { + internal readonly double X, Y; + internal readonly bool OnCurve; + internal Point(double x, double y, bool onCurve) { X = x; Y = y; OnCurve = onCurve; } + } + + private readonly byte[] data; + private readonly Dictionary tables = new(); + private readonly int[] locations; + private readonly ushort[] advances; + private readonly short[] bearings; + internal int UnitsPerEm { get; } + internal int CellAscent + { + get { var os2 = Table("OS/2"); os2.Skip(74); return os2.U16(); } + } + internal bool NeedsSyntheticBold + { + get + { + var os2 = Table("OS/2"); + os2.Skip(4); + var weight = os2.U16(); + os2.Skip(56); + return weight > 0 && weight < 600 && (os2.U16() & 0x20) == 0; + } + } + internal int CellHeight + { + get + { + var os2 = Table("OS/2"); + os2.Skip(74); + var height = os2.U16() + os2.U16(); + if (height == 0) throw new InvalidDataException("Invalid TrueType Windows cell height."); + return height; + } + } + internal int AverageWidth + { + get + { + var os2 = Table("OS/2"); + os2.Skip(2); + var average = os2.I16(); + if (average <= 0) throw new InvalidDataException("Invalid TrueType average character width."); + return average; + } + } + private int remainingWork; + + internal TrueTypeGlyphReader(byte[] data) + { + this.data = data ?? throw new ArgumentNullException(nameof(data)); + var directory = new Reader(data, 0, data.Length); + if (directory.U32() != 0x00010000) + throw new NotSupportedException("Metafile fonts require standalone TrueType glyf outlines."); + var count = directory.U16(); + directory.Skip(6); + for (var index = 0; index < count; index++) + { + var tag = new string(new[] { (char)directory.Byte(), (char)directory.Byte(), + (char)directory.Byte(), (char)directory.Byte() }); + directory.Skip(4); + var offset = directory.U32(); + var length = directory.U32(); + if (offset > data.Length || length > data.Length - offset || tables.ContainsKey(tag)) + throw new InvalidDataException("Invalid or duplicate TrueType table range."); + tables.Add(tag, ((int)offset, (int)length)); + } + var head = Table("head"); + head.Skip(18); + UnitsPerEm = head.U16(); + if (UnitsPerEm < 16 || UnitsPerEm > 16384) + throw new InvalidDataException("Invalid TrueType units per em."); + head.Skip(30); + var locationFormat = head.I16(); + if (locationFormat != 0 && locationFormat != 1) + throw new InvalidDataException("Invalid TrueType loca format."); + var maxp = Table("maxp"); + maxp.Skip(4); + var glyphCount = maxp.U16(); + if (glyphCount == 0) throw new InvalidDataException("Empty TrueType glyph set."); + var glyf = Table("glyf"); + var loca = Table("loca"); + locations = new int[glyphCount + 1]; + for (var index = 0; index < locations.Length; index++) + { + var relative = locationFormat == 0 ? (uint)loca.U16() * 2 : loca.U32(); + if (relative > glyf.Length || (index > 0 && relative < locations[index - 1])) + throw new InvalidDataException("Invalid TrueType glyph location."); + locations[index] = (int)relative; + } + var hhea = Table("hhea"); + hhea.Skip(34); + var metricCount = hhea.U16(); + if (metricCount == 0 || metricCount > glyphCount) + throw new InvalidDataException("Invalid TrueType horizontal metric count."); + var hmtx = Table("hmtx"); + advances = new ushort[glyphCount]; + bearings = new short[glyphCount]; + for (var index = 0; index < glyphCount; index++) + { + advances[index] = index < metricCount ? hmtx.U16() : advances[index - 1]; + bearings[index] = hmtx.I16(); + } + } + + internal int Advance(ushort glyph) + { + CheckGlyph(glyph); + return advances[glyph]; + } + + internal ushort GlyphForCharacter(ushort character) + { + var cmap = Table("cmap"); + if (cmap.U16() != 0) throw new InvalidDataException("Invalid TrueType cmap version."); + var count = cmap.U16(); + if (count > 256) throw new InvalidDataException("TrueType cmap subtable limit exceeded."); + Reader? selected = null; + var selectedFormat = 0; + for (var index = 0; index < count; index++) + { + var platform = cmap.U16(); + var encoding = cmap.U16(); + var offset = cmap.U32(); + if (platform != 0 && !(platform == 3 && (encoding == 1 || encoding == 10))) continue; + var subtable = Table("cmap").Slice(offset); + var format = subtable.U16(); + if (format != 4 && format != 12) continue; + if (format == 12) subtable.Skip(2); + var length = format == 4 ? subtable.U16() : subtable.U32(); + var bounded = Table("cmap").Slice(offset, length); + if (selected == null || format > selectedFormat) { selected = bounded; selectedFormat = format; } + } + if (selected == null) throw new NotSupportedException("No supported Unicode cmap in the metafile font."); + var table = selected; + ushort glyph = 0; + if (selectedFormat == 12) + { + table.Skip(12); + var groups = table.U32(); + if (groups > (table.Length - 16) / 12) + throw new InvalidDataException("Invalid TrueType cmap group count."); + var low = 0; + var high = (int)groups - 1; + while (low <= high) + { + var middle = low + (high - low) / 2; + var group = table.At(16 + middle * 12); + var start = group.U32(); + var end = group.U32(); + var firstGlyph = group.U32(); + if (start > end || end > 0x10FFFF) + throw new InvalidDataException("Invalid TrueType cmap character range."); + if (character >= start && character <= end) + { + var value = (ulong)firstGlyph + character - start; + if (value > ushort.MaxValue) throw new InvalidDataException("Invalid TrueType cmap glyph."); + glyph = (ushort)value; + break; + } + if (character < start) high = middle - 1; + else low = middle + 1; + } + } + else + { + table.Skip(6); + var twiceCount = table.U16(); + var segments = twiceCount / 2; + if (segments == 0 || twiceCount % 2 != 0 || 16 + segments * 8 > table.Length) + throw new InvalidDataException("Invalid TrueType cmap segment count."); + var low = 0; + var high = segments - 1; + while (low <= high) + { + var index = low + (high - low) / 2; + var end = table.At(14 + index * 2).U16(); + var start = table.At(16 + segments * 2 + index * 2).U16(); + if (start > end) throw new InvalidDataException("Invalid TrueType cmap segment."); + if (character < start) { high = index - 1; continue; } + if (character > end) { low = index + 1; continue; } + var delta = table.At(16 + segments * 4 + index * 2).I16(); + var rangePosition = 16 + segments * 6 + index * 2; + var range = table.At(rangePosition).U16(); + glyph = range == 0 ? unchecked((ushort)(character + delta)) + : table.At(rangePosition + range + (character - start) * 2).U16(); + if (range != 0 && glyph != 0) glyph = unchecked((ushort)(glyph + delta)); + break; + } + } + CheckGlyph(glyph); + if (glyph == 0) throw new NotSupportedException($"Metafile font has no glyph for U+{character:X4}."); + return glyph; + } + + internal List> ReadGlyph(ushort glyph) + { + remainingWork = 1_000_000; + return ReadGlyph(glyph, new HashSet()); + } + + private List> ReadGlyph(ushort glyph, HashSet ancestors) + { + CheckGlyph(glyph); + if (ancestors.Count >= 16 || !ancestors.Add(glyph)) + throw new InvalidDataException("Cyclic or excessively nested TrueType composite glyph."); + Spend(1); + var result = new List>(); + var start = locations[glyph]; + var length = locations[glyph + 1] - start; + if (length != 0) + { + var reader = Table("glyf").Slice((uint)start, (uint)length); + var contourCount = reader.I16(); + reader.Skip(8); + if (contourCount > 0) ReadSimple(reader, contourCount, result); + else if (contourCount < 0) ReadComposite(reader, ancestors, result, glyph); + } + ancestors.Remove(glyph); + return result; + } + + private void ReadSimple(Reader reader, int contourCount, List> result) + { + var ends = new ushort[contourCount]; + for (var index = 0; index < contourCount; index++) + { + ends[index] = reader.U16(); + if (index > 0 && ends[index] <= ends[index - 1]) + throw new InvalidDataException("Invalid TrueType contour endpoint."); + } + var count = ends[contourCount - 1] + 1; + Spend(count); + reader.Skip(reader.U16()); + var flags = new byte[count]; + for (var index = 0; index < count;) + { + var flag = reader.Byte(); + if ((flag & 0x80) != 0) throw new InvalidDataException("Reserved TrueType point flag."); + var repeat = (flag & 8) == 0 ? 1 : reader.Byte() + 1; + if (repeat > count - index) throw new InvalidDataException("Excessive TrueType flag repetition."); + for (var end = index + repeat; index < end; index++) flags[index] = flag; + } + var xs = Coordinates(2, 16); + var ys = Coordinates(4, 32); + var first = 0; + foreach (var end in ends) + { + var points = new List(); + for (; first <= end; first++) points.Add(new Point(xs[first], ys[first], (flags[first] & 1) != 0)); + result.Add(points); + } + + int[] Coordinates(int shortFlag, int sameFlag) + { + var coordinates = new int[count]; + var value = 0; + for (var index = 0; index < count; index++) + { + var flag = flags[index]; + var delta = (flag & shortFlag) != 0 ? reader.Byte() * ((flag & sameFlag) != 0 ? 1 : -1) + : (flag & sameFlag) != 0 ? 0 : reader.I16(); + value = checked(value + delta); + coordinates[index] = value; + } + return coordinates; + } + } + + private void ReadComposite(Reader reader, HashSet ancestors, List> result, ushort parent) + { + ushort flags; + var hasInstructions = false; + do + { + Spend(1); + flags = reader.U16(); + hasInstructions |= (flags & 256) != 0; + var glyph = reader.U16(); + if ((flags & 2) == 0) + throw new NotSupportedException("Point-attached TrueType composite glyphs are not supported."); + var x = (flags & 1) != 0 ? reader.I16() : (sbyte)reader.Byte(); + var y = (flags & 1) != 0 ? reader.I16() : (sbyte)reader.Byte(); + var xx = 1d; var yy = 1d; var xy = 0d; var yx = 0d; + var transforms = flags & (8 | 64 | 128); + if (transforms == 8) xx = yy = reader.I16() / 16384d; + else if (transforms == 64) { xx = reader.I16() / 16384d; yy = reader.I16() / 16384d; } + else if (transforms == 128) + { + xx = reader.I16() / 16384d; xy = reader.I16() / 16384d; + yx = reader.I16() / 16384d; yy = reader.I16() / 16384d; + } + else if (transforms != 0) throw new InvalidDataException("Conflicting TrueType composite transforms."); + if ((flags & ~0x1FEF) != 0 || (flags & 0x1800) == 0x1800) + throw new InvalidDataException("Invalid TrueType composite flags."); + // ROUND_XY_TO_GRID affects device hinting, not these unhinted design coordinates. + if ((flags & 512) != 0 && (xx != 1 || yy != 1 || xy != 0 || yx != 0 || + Advance(glyph) != Advance(parent) || HorizontalOrigin(glyph) != HorizontalOrigin(parent))) + throw new NotSupportedException("Inherited TrueType composite metrics must match untransformed parent metrics."); + double offsetX = x, offsetY = y; + if ((flags & 0x800) != 0) { offsetX = x * xx + y * yx; offsetY = x * xy + y * yy; } + foreach (var contour in ReadGlyph(glyph, ancestors)) + { + Spend(contour.Count); + result.Add(contour.Select(point => new Point( + point.X * xx + point.Y * yx + offsetX, + point.X * xy + point.Y * yy + offsetY, point.OnCurve)).ToList()); + } + + } while ((flags & 32) != 0); + if (hasInstructions) reader.Skip(reader.U16()); + } + + private int HorizontalOrigin(ushort glyph) + { + var length = locations[glyph + 1] - locations[glyph]; + if (length == 0) return -bearings[glyph]; + var reader = Table("glyf").Slice((uint)locations[glyph], (uint)length); + reader.Skip(2); + return reader.I16() - bearings[glyph]; + } + + private Reader Table(string tag) + { + if (!tables.TryGetValue(tag, out var table)) + throw new NotSupportedException($"Metafile font requires a TrueType {tag} table."); + return new Reader(data, table.Offset, table.Length); + } + + private void CheckGlyph(ushort glyph) + { + if (glyph >= advances.Length) throw new InvalidDataException("Invalid TrueType glyph index."); + } + + private void Spend(int count) + { + remainingWork -= count; + if (remainingWork < 0) throw new InvalidDataException("TrueType glyph expansion limit exceeded."); + } + + private sealed class Reader + { + private readonly byte[] data; + private readonly int start, end; + private int position; + internal int Length => end - start; + internal Reader(byte[] data, int start, int length) + { + this.data = data; this.start = start; position = start; end = start + length; + } + internal byte Byte() + { + if (position >= end) throw new InvalidDataException("Truncated TrueType table or glyph."); + return data[position++]; + } + internal ushort U16() => (ushort)(Byte() << 8 | Byte()); + internal short I16() => unchecked((short)U16()); + internal uint U32() => (uint)U16() << 16 | U16(); + internal void Skip(int count) + { + if (count < 0 || count > end - position) throw new InvalidDataException("Truncated TrueType table or glyph."); + position += count; + } + internal Reader At(int offset) => Slice((uint)offset); + internal Reader Slice(uint offset, uint? length = null) + { + if (offset > Length || (length.HasValue && length.Value > Length - offset)) + throw new InvalidDataException("TrueType range is outside its table."); + return new Reader(data, start + (int)offset, length.HasValue ? (int)length.Value : Length - (int)offset); + } + } +} diff --git a/src/MiniPdf/WmfVectorAdapter.cs b/src/MiniPdf/WmfVectorAdapter.cs new file mode 100644 index 00000000..ce8e2162 --- /dev/null +++ b/src/MiniPdf/WmfVectorAdapter.cs @@ -0,0 +1,173 @@ +namespace MiniSoftware; + +internal static class WmfVectorAdapter +{ + internal static bool IsWmf(byte[] data) => data.Length >= 18 && + (Read32(data, 0) == 0x9AC6CDD7 || (Read16(data, 2) == 9 && Read16(data, 4) == 0x300)); + + internal static byte[] Convert(byte[] data, int fallbackWidth, int fallbackHeight) + { + var header = 0; + int left = 0, top = 0, right = fallbackWidth, bottom = fallbackHeight; + if (Read32(data, 0) == 0x9AC6CDD7) + { + Require(data, 0, 22); + ushort checksum = 0; + for (var offset = 0; offset < 20; offset += 2) checksum ^= Read16(data, offset); + if (checksum != Read16(data, 20) || Read16(data, 14) == 0 || Read32(data, 16) != 0) + throw new InvalidDataException("Invalid placeable WMF header."); + left = Signed(data, 6); top = Signed(data, 8); right = Signed(data, 10); bottom = Signed(data, 12); + header = 22; + } + Require(data, header, 18); + var objects = Read16(data, header + 10); + if (Read16(data, header) is not (1 or 2) || Read16(data, header + 2) != 9 || + Read16(data, header + 4) != 0x300 || (long)Read32(data, header + 6) * 2 != data.Length - header || + Read16(data, header + 16) != 0 || right <= left || bottom <= top || objects > 65534) + throw new InvalidDataException("Invalid WMF header or dimensions."); + var allocated = new bool[objects]; + var records = new List { Record(17, 8), Record(10, left, top), Record(9, right - left, bottom - top), + Record(12, left, top), Record(11, right - left, bottom - top) }; + var ended = false; + for (var offset = header + 18; offset < data.Length;) + { + if (records.Count > 1_000_000) throw new InvalidDataException("WMF record limit exceeded."); + Require(data, offset, 6); + var words = Read32(data, offset); + if (words < 3 || words > Read32(data, header + 12) || (long)words * 2 > data.Length - offset) + throw new InvalidDataException("Invalid WMF record size."); + var end = offset + (int)words * 2; + var function = Read16(data, offset + 4); + var p = offset + 6; + int I(int index) { if (p + index * 2 > end - 2) throw new InvalidDataException("Truncated WMF parameters."); return Signed(data, p + index * 2); } + uint U(int index) { if (p + index * 2 > end - 2) throw new InvalidDataException("Truncated WMF parameters."); return Read16(data, p + index * 2); } + uint Color(int index) { if (p + index * 2 > end - 4) throw new InvalidDataException("Truncated WMF color."); return Read32(data, p + index * 2); } + int NewObject() + { + var index = Array.FindIndex(allocated, value => !value); + if (index < 0) throw new InvalidDataException("WMF object table is full."); + allocated[index] = true; + return index + 1; + } + switch (function) + { + case 0: + if (words != 3 || end != data.Length) throw new InvalidDataException("Invalid WMF EOF."); + ended = true; + break; + case 0x001E: records.Add(Record(33)); break; + case 0x0127: records.Add(Record(34, I(0))); break; + case 0x0102: records.Add(Record(18, (int)U(0))); break; + case 0x0103: records.Add(Record(17, I(0))); break; + case 0x0104: records.Add(Record(20, (int)U(0))); break; + case 0x0106: records.Add(Record(19, (int)U(0))); break; + case 0x012E: records.Add(Record(22, (int)U(0))); break; + case 0x0201: records.Add(Record(25, unchecked((int)Color(0)))); break; + case 0x0209: records.Add(Record(24, unchecked((int)Color(0)))); break; + case 0x020B: records.Add(Record(10, I(1), I(0))); break; + case 0x020C: records.Add(Record(9, I(1), I(0))); break; + case 0x020D: records.Add(Record(12, I(1), I(0))); break; + case 0x020E: records.Add(Record(11, I(1), I(0))); break; + case 0x0214: records.Add(Record(27, I(1), I(0))); break; + case 0x0213: records.Add(Record(54, I(1), I(0))); break; + case 0x0416: records.Add(Record(30, I(3), I(2), I(1), I(0))); break; + // Native WMF conversion subtracts one from the lower-right EMF rectangle coordinates. + case 0x041B: records.Add(Record(43, I(3), I(2), I(1) - 1, I(0) - 1)); break; + case 0x012D: + case 0x01F0: + var selected = (int)U(0); + if (function == 0x012D && (selected & 0x8000) != 0) + { + records.Add(Record(37, unchecked((int)(0x80000000u | (uint)(selected & 0x7FFF))))); + break; + } + if (selected >= allocated.Length || !allocated[selected]) throw new InvalidDataException("Unknown WMF object."); + records.Add(Record(function == 0x012D ? 37 : 40, selected + 1)); + if (function == 0x01F0) allocated[selected] = false; + break; + case 0x02FA: records.Add(Record(38, NewObject(), (int)U(0), I(1), I(2), unchecked((int)Color(3)))); break; + case 0x02FC: records.Add(Record(39, NewObject(), (int)U(0), unchecked((int)Color(1)), (int)U(3))); break; + case 0x02FB: + if (end - p < 18) throw new InvalidDataException("Truncated WMF font."); + var font = new byte[332]; + Write32(font, 0, 82); Write32(font, 4, (uint)font.Length); Write32(font, 8, (uint)NewObject()); + for (var index = 0; index < 5; index++) Write32(font, 12 + index * 4, unchecked((uint)I(index))); + Buffer.BlockCopy(data, p + 10, font, 32, 8); + for (var index = 0; index < 31 && p + 18 + index < end && data[p + 18 + index] != 0; index++) + { + if (data[p + 18 + index] > 0x7F) throw new NotSupportedException("WMF font names require supported character-set decoding."); + font[40 + index * 2] = data[p + 18 + index]; + } + records.Add(font); + break; + case 0x0521: + var textLength = (int)U(0); + var reference = p + 2 + ((textLength + 1) & ~1); + if (reference > end - 4) throw new InvalidDataException("Truncated WMF text."); + var text = new byte[(76 + textLength * 2 + 3) & ~3]; + Write32(text, 0, 84); Write32(text, 4, (uint)text.Length); Write32(text, 24, 2); + Write32(text, 28, 0x3F800000); Write32(text, 32, 0x3F800000); + Write32(text, 36, unchecked((uint)Signed(data, reference + 2))); Write32(text, 40, unchecked((uint)Signed(data, reference))); + Write32(text, 44, (uint)textLength); Write32(text, 48, 76); + for (var index = 0; index < textLength; index++) + { + if (data[p + 2 + index] > 0x7F) throw new NotSupportedException("WMF text requires supported character-set decoding."); + text[76 + index * 2] = data[p + 2 + index]; + } + records.Add(text); + break; + case 0x0324: + case 0x0325: + var count = (int)U(0); + if (count < 2 || count > (end - p - 2) / 4) throw new InvalidDataException("Invalid WMF polygon."); + var points = new int[5 + count * 2]; + points[4] = count; + for (var index = 0; index < count; index++) + { + points[5 + index * 2] = I(1 + index * 2); + points[6 + index * 2] = I(2 + index * 2); + } + records.Add(Record(function == 0x0324 ? 3 : 4, points)); + break; + default: throw new NotSupportedException($"WMF record 0x{function:X4} is not supported by the independent adapter."); + } + offset = end; + } + if (!ended) throw new InvalidDataException("Missing WMF EOF."); + records.Add(Record(14, 0, 0, 20)); + var size = 88 + records.Sum(record => record.Length); + var emf = new byte[size]; + Write32(emf, 0, 1); Write32(emf, 4, 88); + Write32(emf, 8, (uint)left); Write32(emf, 12, (uint)top); Write32(emf, 16, (uint)right); Write32(emf, 20, (uint)bottom); + Write32(emf, 40, 0x464D4520); Write32(emf, 44, 0x10000); Write32(emf, 48, (uint)size); + Write32(emf, 52, (uint)records.Count + 1); Write32(emf, 56, (uint)objects + 1); + var destination = 88; + foreach (var record in records) { Buffer.BlockCopy(record, 0, emf, destination, record.Length); destination += record.Length; } + return emf; + } + + private static byte[] Record(int type, params int[] values) + { + var result = new byte[8 + values.Length * 4]; + Write32(result, 0, (uint)type); Write32(result, 4, (uint)result.Length); + for (var index = 0; index < values.Length; index++) Write32(result, 8 + index * 4, unchecked((uint)values[index])); + return result; + } + private static void Require(byte[] data, int offset, int length) + { + if (offset < 0 || length < 0 || offset > data.Length - length) throw new InvalidDataException("Truncated WMF data."); + } + private static ushort Read16(byte[] data, int offset) + { + Require(data, offset, 2); return (ushort)(data[offset] | data[offset + 1] << 8); + } + private static int Signed(byte[] data, int offset) => (short)Read16(data, offset); + private static uint Read32(byte[] data, int offset) + { + Require(data, offset, 4); return (uint)(data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16 | data[offset + 3] << 24); + } + private static void Write32(byte[] data, int offset, uint value) + { + data[offset] = (byte)value; data[offset + 1] = (byte)(value >> 8); data[offset + 2] = (byte)(value >> 16); data[offset + 3] = (byte)(value >> 24); + } +} diff --git a/tests/MiniPdf.Benchmark/generate_office_pdfs_docx.py b/tests/MiniPdf.Benchmark/generate_office_pdfs_docx.py index 36c151f5..8f6f9bdc 100644 --- a/tests/MiniPdf.Benchmark/generate_office_pdfs_docx.py +++ b/tests/MiniPdf.Benchmark/generate_office_pdfs_docx.py @@ -21,7 +21,7 @@ def _create_word(): """Create a fresh Word COM instance.""" import win32com.client - word = win32com.client.Dispatch("Word.Application") + word = win32com.client.DispatchEx("Word.Application") word.Visible = False word.DisplayAlerts = False return word @@ -90,7 +90,7 @@ def main(): continue print(f" Converting {docx.name} ...", end=" ", flush=True) try: - doc = word.Documents.Open(os.path.abspath(str(docx))) + doc = word.Documents.Open(os.path.abspath(str(docx)), ReadOnly=True, AddToRecentFiles=False) # ExportAsFixedFormat: OutputFileName, ExportFormat (wdExportFormatPDF=17) doc.ExportAsFixedFormat(os.path.abspath(pdf_path), 17) doc.Close(False) diff --git a/tests/MiniPdf.Tests/DocxIssueFileTests.cs b/tests/MiniPdf.Tests/DocxIssueFileTests.cs index 99fee351..de668466 100644 --- a/tests/MiniPdf.Tests/DocxIssueFileTests.cs +++ b/tests/MiniPdf.Tests/DocxIssueFileTests.cs @@ -160,6 +160,42 @@ line.X1 is > 71.9f and < 72.1f Assert.InRange(footnoteText.Y, 74.9f, 75.1f); } + [WindowsEmfTheory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(4)] + [InlineData(5)] + public void Issue90_EmbeddedAlphaBitmap_MatchesNativePlayback(int imageIndex) + { + using var archive = System.IO.Compression.ZipFile.OpenRead(FindIssueDocx("TestIssue90.docx")); + var entry = archive.GetEntry($"word/media/image{imageIndex}.emf"); + Assert.NotNull(entry); + using var stream = entry.Open(); + using var buffer = new MemoryStream(); + stream.CopyTo(buffer); + var source = buffer.ToArray(); + byte[]? bitmap = null; + for (var offset = 0; offset < source.Length;) + { + var size = checked((int)BitConverter.ToUInt32(source, offset + 4)); + Assert.InRange(size, 8, source.Length - offset); + if (BitConverter.ToUInt32(source, offset) == 114) + { + bitmap = source.AsSpan(offset, size).ToArray(); + break; + } + offset += size; + } + Assert.NotNull(bitmap); + Assert.Equal(0x01FF8000u, BitConverter.ToUInt32(bitmap, 40)); + var emf = EmfNativePlaybackTests.FrameMetafile("sparse-bounds", bitmap); + var expected = EmfNativePlaybackTests.PlayNative(emf, 32, 32); + var actual = EmfVectorRendererTests.Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + EmfNativePlaybackTests.AssertPixelsEqual(actual, expected, 32, 32); + } + [Fact] public void Issue91_DecomposedVietnameseText_IsNormalizedBeforeRendering() { diff --git a/tests/MiniPdf.Tests/EmfNativePlaybackTests.cs b/tests/MiniPdf.Tests/EmfNativePlaybackTests.cs new file mode 100644 index 00000000..ce27f282 --- /dev/null +++ b/tests/MiniPdf.Tests/EmfNativePlaybackTests.cs @@ -0,0 +1,332 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using static MiniSoftware.Tests.EmfVectorRendererTests; + +namespace MiniSoftware.Tests; + +public sealed class WindowsEmfTheoryAttribute : TheoryAttribute +{ + public WindowsEmfTheoryAttribute() + { + if (!OperatingSystem.IsWindows()) Skip = "Native EMF playback comparisons require Windows GDI."; + } +} + +public class EmfNativePlaybackTests +{ + [WindowsGlyphTheory] + [InlineData(28f, 28f, false)] + [InlineData(28f, 28f, true)] + [InlineData(27.447916f, 27.407408f, false)] + [InlineData(27.447916f, 27.407408f, true)] + [InlineData(2f, 1f, false)] + [InlineData(2f, 1f, true)] + [InlineData(1f, 2f, false)] + [InlineData(1f, 2f, true)] + public void CompatibleTextScaleMetadataMatchesNativeReference(float xScale, float yScale, bool explicitSpacing) + { + var ratio = yScale / xScale; + byte[] Metafile(float x, float y, bool transformedReference = false) + { + var advance = transformedReference ? (int)Math.Round(12 / ratio) : 12; + var text = TextRecord(4, 24, new ushort[] { 65, 65 }, 0, explicitSpacing ? new[] { advance, advance } : null); + Set(text, 24, transformedReference ? 2u : 1u); + Set(text, 28, BitConverter.SingleToUInt32Bits(x)); + Set(text, 32, BitConverter.SingleToUInt32Bits(y)); + var records = new List { FontRecord("Arial"), Record(37, 1), Record(18, 1), Record(22, 24) }; + if (transformedReference) + records.Add(Record(35, BitConverter.SingleToUInt32Bits(ratio), 0, 0, 0x3F800000, + BitConverter.SingleToUInt32Bits(4 - 4 * ratio), 0)); + records.Add(text); + return FrameMetafile("sparse-bounds", records.ToArray()); + } + var expected = PlayNative(Metafile(1, 1, true), 32, 32); + var emf = Metafile(xScale, yScale); + var native = PlayNative(emf, 32, 32); + Assert.Equal(expected.Where((_, index) => index % 4 != 3), + native.Where((_, index) => index % 4 != 3)); + + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + Assert.Equal(EmfVectorRenderer.Render(Metafile(1, 1, true), 32, 32, (_, _, _) => font), + EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font)); + } + + [WindowsEmfTheory] + [InlineData("sparse-bounds")] + [InlineData("offset-frame")] + [InlineData("different-device-resolutions")] + [InlineData("micrometers")] + [InlineData("single-pixel-bounds")] + public void PlacesInkRelativeToPhysicalFrameRatherThanDrawingBounds(string scenario) + { + var emf = FrameMetafile(scenario); + const int size = 64; + + var actual = Decode(EmfVectorRenderer.Render(emf, size, size), size, size); + var expected = PlayNative(emf, size, size); + + AssertPixelsEqual(actual, expected, size, size); + } + + [WindowsEmfTheory] + [InlineData("reset")] + [InlineData("copy")] + [InlineData("intersect")] + [InlineData("empty")] + [InlineData("device-coordinates")] + [InlineData("metadata")] + [InlineData("stock-font")] + public void ClippingAndMetadataMatchNativePlayback(string scenario) + { + var records = new List { Record(37, 0x80000008), Record(37, 0x80000004) }; + if (scenario == "reset") { records.Add(Record(30, 8, 8, 12, 12)); records.Add(Record(75, 0, 5)); } + if (scenario == "copy") records.Add(Region(5)); + if (scenario == "intersect") { records.Add(Record(30, 4, 4, 10, 10)); records.Add(Region(1)); } + if (scenario == "empty") records.Add(Record(75, 32, 5, 32, 1, 0, 0, 0, 0, 0, 0)); + if (scenario == "stock-font") records.Add(Record(37, 0x8000000D)); + if (scenario == "device-coordinates") + { + records.Add(Record(17, 8)); records.Add(Record(9, 32, 32)); records.Add(Record(11, 64, 64)); + records.Add(Record(35, 0x3F800000, 0, 0, 0x3F800000, 0x40800000, 0x40800000)); + records.Add(Region(5)); + } + if (scenario == "metadata") + { + records.Add(Record(70, 4, 0x12345678)); + records.Add(Record(70, 28, 0x43494447, 2, 0, 0, 32, 32, 0)); + records.Add(Record(48, 0x8000000F)); + } + records.Add(Record(3, 0, 0, 31, 31, 4, 0, 0, 32, 0, 32, 32, 0, 32)); + if (scenario == "metadata") records.Add(Record(70, 8, 0x43494447, 3)); + var emf = FrameMetafile("sparse-bounds", records.ToArray()); + + var actual = Decode(EmfVectorRenderer.Render(emf, 64, 64), 64, 64); + var expected = PlayNative(emf, 64, 64); + + AssertPixelsEqual(actual, expected, 64, 64); + } + + internal static byte[] Region(uint mode) => + Record(75, 48, mode, 32, 1, 1, 16, 8, 8, 12, 12, 8, 8, 12, 12); + + [WindowsEmfTheory] + [InlineData(0x000000u)] + [InlineData(0xFFFFFFu)] + [InlineData(0x123456u)] + public void PaletteRgbColorsMatchNativeTrueColorPlayback(uint color) + { + byte[] Metafile(uint value) + { + var text = TextRecord(0, 0, Array.Empty(), 2); + Set(text, 56, 20); Set(text, 60, 4); Set(text, 64, 24); Set(text, 68, 8); + return FrameMetafile("sparse-bounds", Record(37, 0x80000008), + Record(39, 1, 0, value, 0), Record(37, 1), Record(43, 4, 4, 12, 12), + Record(38, 2, 0, 0, 0, value), Record(37, 2), Record(27, 4, 16), Record(54, 12, 16), + Record(15, 20, 20, value), Record(24, value), Record(25, value), text); + } + var expected = PlayNative(Metafile(color), 32, 32); + var emf = Metafile(color | 0x02000000); + var native = PlayNative(emf, 32, 32); + Assert.Equal(expected.Where((_, index) => index % 4 != 3), + native.Where((_, index) => index % 4 != 3)); + + var actual = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + AssertPixelsEqual(actual, expected, 32, 32); + } + + [WindowsEmfTheory] + [InlineData(0u)] + [InlineData(1u)] + [InlineData(4u)] + [InlineData(11u)] + [InlineData(13u)] + [InlineData(16u)] + public void DestinationIndependentRasterOperationsMatchNativePlayback(uint operation) + { + var text = TextRecord(0, 0, Array.Empty(), 2); + Set(text, 56, 20); Set(text, 60, 4); Set(text, 64, 24); Set(text, 68, 8); + var emf = FrameMetafile("sparse-bounds", Record(37, 0x80000008), Record(39, 1, 0, 0x112233, 0), + Record(37, 1), Record(43, 0, 0, 32, 32), Record(20, operation), Record(39, 2, 0, 0x123456, 0), + Record(37, 2), Record(43, 4, 4, 12, 12), Record(38, 3, 0, 0, 0, 0x654321), + Record(37, 3), Record(27, 4, 16), Record(54, 12, 16), Record(15, 20, 20, 0xABCDEF), + Record(25, 0x345678), text); + var expected = PlayNative(emf, 32, 32); + + var actual = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + AssertPixelsEqual(actual, expected, 32, 32); + } + + [WindowsEmfTheory] + [InlineData(128, false)] + [InlineData(128, true)] + [InlineData(255, false)] + [InlineData(255, true)] + public void ReservedAlphaBlendFlagsMatchNativePlayback(int flags, bool perPixelAlpha) + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 64, 128 }, alphaBlend: true, imageWidth: 1); + var blend = 0x00FF0000u | (perPixelAlpha ? 0x01000000u : 0); + Set(bitmap, 40, blend); + var expected = PlayNative(FrameMetafile("sparse-bounds", bitmap), 32, 32); + Assert.Contains(expected, value => value != 255); + + Set(bitmap, 40, blend | (uint)flags << 8); + var emf = FrameMetafile("sparse-bounds", bitmap); + var native = PlayNative(emf, 32, 32); + Assert.Equal(expected.Where((_, index) => index % 4 != 3), + native.Where((_, index) => index % 4 != 3)); + + var actual = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + AssertPixelsEqual(actual, expected, 32, 32); + } + + [WindowsEmfTheory] + [InlineData(0, "upscale")] + [InlineData(1, "identity")] + [InlineData(1, "downscale")] + [InlineData(1, "nonuniform")] + public void CreatedThinPensMatchNativeScaling(uint penWidth, string scenario) + { + var records = new List { Record(38, 1, 0, penWidth, 0, 0), Record(37, 1) }; + if (scenario is "upscale" or "identity") + { + records.Add(Record(27, 4, 8)); records.Add(Record(54, 20, 8)); + } + else + { + records.Add(Record(17, 8)); records.Add(Record(9, 256, 256)); + records.Add(Record(11, 32, scenario == "nonuniform" ? 16u : 32u)); + records.Add(Record(27, 32, scenario == "nonuniform" ? 128u : 64u)); + records.Add(Record(54, 128, scenario == "nonuniform" ? 128u : 64u)); + } + var emf = FrameMetafile("sparse-bounds", records.ToArray()); + var size = scenario == "identity" ? 32 : 64; + var expected = PlayNative(emf, size, size); + var actual = Decode(EmfVectorRenderer.Render(emf, size, size), size, size); + + AssertPixelsEqual(actual, expected, size, size); + } + + [WindowsEmfTheory] + [InlineData(64)] + public void RejectsScaledPensRequiringWideRasterization(int size) + { + var emf = FrameMetafile("sparse-bounds", Record(38, 1, 0, 1, 0, 0), Record(37, 1), + Record(27, 4, 8), Record(54, 20, 8)); + var expected = PlayNative(emf, size, size); + Assert.Equal(0, expected[(15 * size + 9) * 4]); + Assert.Equal(0, expected[(16 * size + 9) * 4]); + + var error = Assert.Throws(() => EmfVectorRenderer.Render(emf, size, size)); + Assert.Contains("wider than one device pixel", error.Message); + } + + internal static byte[] FrameMetafile(string scenario, params byte[][] records) + { + var emf = Build(records.Length == 0 ? new[] + { + Record(37, 0x80000008), Record(37, 0x80000004), + Record(3, 8, 8, 15, 15, 4, 8, 8, 16, 8, 16, 16, 8, 16) + } : records); + if (scenario == "single-pixel-bounds") emf = Build(Record(15, 8, 8, 0x0000FF)); + Set(emf, 8, 8); Set(emf, 12, 8); Set(emf, 16, 15); Set(emf, 20, 15); + if (records.Length != 0) { Set(emf, 8, 0); Set(emf, 12, 0); Set(emf, 16, 63); Set(emf, 20, 63); } + Set(emf, 32, 800); Set(emf, 36, 800); + Set(emf, 72, 32); Set(emf, 76, 32); Set(emf, 80, 8); Set(emf, 84, 8); + if (scenario == "single-pixel-bounds") { Set(emf, 16, 8); Set(emf, 20, 8); } + if (scenario == "offset-frame") + { + Set(emf, 24, 200); Set(emf, 28, 200); Set(emf, 32, 1000); Set(emf, 36, 1000); + } + if (scenario == "different-device-resolutions") { Set(emf, 80, 16); Set(emf, 32, 1600); } + if (scenario == "micrometers") + { + var extended = new byte[emf.Length + 20]; + Buffer.BlockCopy(emf, 0, extended, 0, 88); + Buffer.BlockCopy(emf, 88, extended, 108, emf.Length - 88); + emf = extended; + Set(emf, 4, 108); Set(emf, 48, (uint)emf.Length); + Set(emf, 100, 16000); Set(emf, 104, 16000); + } + return emf; + } + + internal static void Set(byte[] bytes, int offset, uint value) => + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(offset), value); + + internal static void AssertPixelsEqual(byte[] actual, byte[] expected, int width, int height) + { + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var offset = (y * width + x) * 4; + var alpha = actual[offset + 3]; + for (var channel = 0; channel < 3; channel++) + { + var value = (actual[offset + channel] * alpha + 255 * (255 - alpha) + 127) / 255; + Assert.True(value == expected[offset + 2 - channel], + $"Native EMF mismatch at ({x}, {y}), channel {channel}: " + + $"managed {value}, native {expected[offset + 2 - channel]}."); + } + } + } + } + + internal static byte[] PlayNative(byte[] emf, int width, int height) + { + var metafile = SetEnhMetaFileBits((uint)emf.Length, emf); + Assert.NotEqual(IntPtr.Zero, metafile); + var dc = CreateCompatibleDC(IntPtr.Zero); + var bitmap = IntPtr.Zero; + var previous = IntPtr.Zero; + try + { + Assert.NotEqual(IntPtr.Zero, dc); + var info = new byte[40]; + BinaryPrimitives.WriteInt32LittleEndian(info, 40); + BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(4), width); + BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(8), -height); + BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(12), 1); + BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(14), 32); + bitmap = CreateDIBSection(dc, info, 0, out var bits, IntPtr.Zero, 0); + Assert.NotEqual(IntPtr.Zero, bitmap); + previous = SelectObject(dc, bitmap); + Assert.NotEqual(IntPtr.Zero, previous); + var pixels = Enumerable.Repeat((byte)255, width * height * 4).ToArray(); + Marshal.Copy(pixels, 0, bits, pixels.Length); + var bounds = new NativeRect { Right = width, Bottom = height }; + Assert.True(PlayEnhMetaFile(dc, metafile, ref bounds)); + Assert.True(GdiFlush()); + Marshal.Copy(bits, pixels, 0, pixels.Length); + return pixels; + } + finally + { + if (previous != IntPtr.Zero) SelectObject(dc, previous); + if (bitmap != IntPtr.Zero) DeleteObject(bitmap); + if (dc != IntPtr.Zero) DeleteDC(dc); + DeleteEnhMetaFile(metafile); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct NativeRect { internal int Left, Top, Right, Bottom; } + [DllImport("gdi32.dll")] + private static extern IntPtr SetEnhMetaFileBits(uint length, byte[] bytes); + [DllImport("gdi32.dll")] + private static extern bool DeleteEnhMetaFile(IntPtr metafile); + [DllImport("gdi32.dll")] + private static extern IntPtr CreateCompatibleDC(IntPtr dc); + [DllImport("gdi32.dll")] + private static extern bool DeleteDC(IntPtr dc); + [DllImport("gdi32.dll")] + private static extern IntPtr CreateDIBSection(IntPtr dc, byte[] info, uint usage, out IntPtr bits, IntPtr section, uint offset); + [DllImport("gdi32.dll")] + private static extern IntPtr SelectObject(IntPtr dc, IntPtr value); + [DllImport("gdi32.dll")] + private static extern bool DeleteObject(IntPtr value); + [DllImport("gdi32.dll")] + private static extern bool PlayEnhMetaFile(IntPtr dc, IntPtr metafile, ref NativeRect bounds); + [DllImport("gdi32.dll")] + private static extern bool GdiFlush(); +} diff --git a/tests/MiniPdf.Tests/EmfVectorRendererTests.cs b/tests/MiniPdf.Tests/EmfVectorRendererTests.cs new file mode 100644 index 00000000..0ca06317 --- /dev/null +++ b/tests/MiniPdf.Tests/EmfVectorRendererTests.cs @@ -0,0 +1,1579 @@ +using System.Buffers.Binary; +using System.IO.Compression; + +namespace MiniSoftware.Tests; + +public class EmfVectorRendererTests +{ + [Theory] + [InlineData(0x01000000u)] + [InlineData(0x03000000u)] + [InlineData(0xFF000000u)] + public void RejectsIndexedOrUnsupportedColorEncodings(uint color) + { + Assert.Throws(() => + EmfVectorRenderer.Render(Build(Record(24, color)), 32, 32)); + } + + [Theory] + [InlineData(0u, 255, 255, 255, 255)] + [InlineData(1u, 0, 0, 0, 255)] + [InlineData(4u, 169, 203, 237, 255)] + [InlineData(11u, 0, 0, 0, 0)] + [InlineData(13u, 86, 52, 18, 255)] + [InlineData(16u, 255, 255, 255, 255)] + public void RasterOperationsPreserveTransparencyAndDoNotAffectTextOrBitmaps( + uint operation, byte red, byte green, byte blue, byte alpha) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 255, 0 }, alphaBlend: true, imageWidth: 1); + Set(bitmap, 24, 16); Set(bitmap, 28, 16); Set(bitmap, 32, 4); Set(bitmap, 36, 4); + Set(bitmap, 40, 0x00FF0000); + var emf = Build(Record(20, operation), Record(15, 30, 30, 0x123456), bitmap, + FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), Record(24, 0x020000FF), + TextRecord(4, 24, new ushort[] { 1 }, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 30, 30, red, green, blue, alpha); + AssertPixel(pixels, 32, 17, 17, 255, 0, 0, 255); + AssertPixel(pixels, 32, 5, 11, 255, 0, 0, 255); + } + + [Fact] + public void RestoresRasterOperationAlongWithDeviceContext() + { + var emf = Build(Record(20, 0), Record(33), Record(20, 1), Record(15, 4, 4, 0x123456), + Record(34, uint.MaxValue), Record(15, 5, 4, 0x123456), Record(20, 13), Record(15, 6, 4, 0x123456)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 4, 4, 0, 0, 0, 255); + AssertPixel(pixels, 32, 5, 4, 255, 255, 255, 255); + AssertPixel(pixels, 32, 6, 4, 86, 52, 18, 255); + } + + [Theory] + [InlineData(6u)] + [InlineData(7u)] + [InlineData(9u)] + [InlineData(17u)] + public void UnsupportedRasterOperationsDoNotReturnPartialImages(uint operation) + { + Assert.Throws(() => + EmfVectorRenderer.Render(Build(Record(15, 4, 4, 0x123456), Record(20, operation)), 32, 32)); + } + + [Fact] + public void StockFontSelectionClearsExplicitFontWithoutSuppressingOtherDrawing() + { + var pixel = Record(15, 4, 4, 0x123456); + var emf = Build(Record(37, 0x8000000D), pixel); + Assert.Equal(EmfVectorRenderer.Render(Build(pixel), 32, 32), EmfVectorRenderer.Render(emf, 32, 32)); + + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = Build(FontRecord(), Record(37, 1), Record(37, 0x8000000D), Record(18, 1), + Record(22, 24), TextRecord(4, 24, new ushort[] { 1 }, 16)); + Assert.Throws(() => EmfVectorRenderer.Render(text, 32, 32, (_, _, _) => font)); + } + + [Fact] + public void RestoresExplicitFontAfterStockFontSelection() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = TextRecord(4, 24, new ushort[] { 1 }, 16); + var baseline = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), text); + var saved = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), Record(33), + Record(37, 0x8000000D), Record(34, uint.MaxValue), text); + + Assert.Equal(EmfVectorRenderer.Render(baseline, 32, 32, (_, _, _) => font), + EmfVectorRenderer.Render(saved, 32, 32, (_, _, _) => font)); + } + + [Fact] + public void RendersPolygonAndLineWithIndependentPngEncoding() + { + var emf = Build( + Record(39, 1, 0, 0x0000FF, 0), + Record(37, 1), + Record(37, 0x80000008), + Polygon16((4, 4), (28, 4), (4, 28)), + Record(38, 2, 0, 0, 0, 0xFF0000), + Record(37, 2), + Record(27, 4, 30), + Record(54, 28, 30)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 6, 6, 255, 0, 0, 255); + AssertPixel(pixels, 32, 26, 26, 0, 0, 0, 0); + AssertPixel(pixels, 32, 15, 30, 0, 0, 255, 255); + AssertPixel(pixels, 32, 15, 29, 0, 0, 0, 0); + AssertPixel(pixels, 32, 28, 30, 0, 0, 0, 0); + } + + [Fact] + public void RectangleOutlineExcludesRightAndBottomEdges() + { + var emf = Build(Record(37, 0x80000005), Record(43, 4, 4, 12, 12)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 4, 4, 0, 0, 0, 255); + AssertPixel(pixels, 32, 11, 11, 0, 0, 0, 255); + AssertPixel(pixels, 32, 12, 8, 0, 0, 0, 0); + AssertPixel(pixels, 32, 8, 12, 0, 0, 0, 0); + AssertPixel(pixels, 32, 8, 8, 0, 0, 0, 0); + } + + [Fact] + public void CroppingUsesRenderedPixelsAndPreservesAlpha() + { + var emf = Build(Record(37, 0x80000008), Record(39, 1, 0, 0x0000FF, 0), Record(37, 1), Record(43, 4, 4, 20, 20)); + var png = EmfVectorRenderer.RenderCropped(emf, 32, 32, null, 0.25f, 0.125f, 0.25f, 0.125f); + var pixels = Decode(png, 16, 24); + + AssertPixel(pixels, 16, 1, 1, 255, 0, 0, 255); + AssertPixel(pixels, 16, 12, 16, 0, 0, 0, 0); + } + + [Theory] + [InlineData(0u, 4u)] + [InlineData(2u, 28u)] + [InlineData(6u, 16u)] + public void TopAlignedTextUsesTheFontCellAscent(uint alignment, uint referenceX) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + byte[] RenderText(uint align, uint y) => EmfVectorRenderer.Render( + Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, align), + TextRecord(referenceX, y, new ushort[] { 1, 1 }, 16)), 32, 32, (_, _, _) => font); + + Assert.Equal(RenderText(alignment + 24, 24), RenderText(alignment, 4)); + } + + [Theory] + [InlineData('ề')] + [InlineData('修')] + public void SimpleUnicodeTextUsesCmapInsteadOfRequiringGlyphIndices(char character) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var cmap = TrueTypeGlyphReaderTests.TableOffset(font, "cmap"); + TrueTypeGlyphReaderTests.Write16(font, cmap + 26, character); + TrueTypeGlyphReaderTests.Write16(font, cmap + 32, character); + TrueTypeGlyphReaderTests.Write16(font, cmap + 36, 1 - character); + byte[] RenderText(ushort value, uint options) => EmfVectorRenderer.Render( + Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new[] { value }, options)), 32, 32, (_, _, _) => font); + + Assert.Equal(RenderText(1, 16), RenderText(character, 0)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SyntheticBoldOverstrikesWithoutReplacingTheFamily(bool suppliedAdvances) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + TrueTypeGlyphReaderTests.Write16(font, TrueTypeGlyphReaderTests.TableOffset(font, "OS/2") + 4, 400); + var definition = FontRecord(); Set(definition, 28, 700); + var emf = Build(definition, Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new ushort[] { 1, 1 }, 16, suppliedAdvances ? new[] { 12, 12 } : null)); + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 14, 11, 0, 0, 0, 255); + AssertPixel(pixels, 32, suppliedAdvances ? 17 : 18, 11, 0, 0, 0, 255); + } + + [Theory] + [InlineData(1, false)] + [InlineData(2, true)] + public void HonorsPolygonFillRule(uint fillMode, bool centerIsFilled) + { + var emf = Build( + Record(37, 0x80000008), + Record(37, 0x80000004), + Record(19, fillMode), + Polygon16((4, 4), (28, 4), (28, 28), (4, 28), (4, 4), + (10, 10), (22, 10), (22, 22), (10, 22), (10, 10), (4, 4))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 16, 0, 0, 0, centerIsFilled ? (byte)255 : (byte)0); + AssertPixel(pixels, 32, 6, 16, 0, 0, 0, 255); + } + + [Theory] + [InlineData(-1)] + [InlineData(1)] + public void RestoresMappingBrushAndClipTogether(int restoreLevel) + { + var emf = Build( + Record(39, 1, 0, 0x0000FF, 0), + Record(37, 1), + Record(37, 0x80000008), + Record(33), + Record(17, 8), + Record(9, 64, 64), + Record(11, 32, 32), + Record(30, 8, 8, 24, 24), + Record(43, 0, 0, 64, 64), + Record(37, 0x80000004), + Record(34, unchecked((uint)restoreLevel)), + Record(43, 24, 24, 30, 30)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 3, 3, 0, 0, 0, 0); + AssertPixel(pixels, 32, 4, 4, 255, 0, 0, 255); + AssertPixel(pixels, 32, 12, 12, 0, 0, 0, 0); + AssertPixel(pixels, 32, 25, 25, 255, 0, 0, 255); + } + + [Fact] + public void AppliesNegativeViewportExtentWithoutOverflowingExtremeCoordinates() + { + var emf = Build( + Record(17, 8), + Record(9, 32, 32), + Record(11, unchecked((uint)-32), 32), + Record(12, 32, 0), + Record(37, 0x80000008), + Record(37, 0x80000004), + Record(43, 0, 0, 8, 8), + Record(43, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 25, 4, 0, 0, 0, 255); + AssertPixel(pixels, 32, 4, 4, 0, 0, 0, 0); + } + + [Fact] + public void PhysicalFramePreservesWhitespaceAroundSparseDrawingBounds() + { + var emf = EmfNativePlaybackTests.FrameMetafile("sparse-bounds"); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 64, 64), 64, 64); + + AssertPixel(pixels, 64, 0, 0, 0, 0, 0, 0); + AssertPixel(pixels, 64, 16, 16, 0, 0, 0, 255); + AssertPixel(pixels, 64, 31, 31, 0, 0, 0, 255); + AssertPixel(pixels, 64, 32, 32, 0, 0, 0, 0); + } + + [Fact] + public void NullClipResetCanBeRestoredWithTheDeviceContext() + { + var emf = Build(Record(30, 8, 8, 12, 12), Record(33), Record(75, 0, 5), + Record(15, 2, 2, 0x0000FF), Record(34, uint.MaxValue), + Record(15, 4, 4, 0xFF0000), Record(15, 9, 9, 0xFF0000)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 2, 2, 255, 0, 0, 255); + AssertPixel(pixels, 32, 4, 4, 0, 0, 0, 0); + AssertPixel(pixels, 32, 9, 9, 0, 0, 255, 255); + } + + [Fact] + public void PrivateGroupAndOriginalWmfCommentsDoNotAddDrawing() + { + var emf = Build(Record(70, 3, 0x00434241), + Record(70, 28, 0x43494447, 2, 0, 0, 32, 32, 0), + Record(70, 24, 0x43494447, 0x80000001, 0x300, 0, 0, 0), + Record(15, 8, 8, 0x0000FF), Record(70, 8, 0x43494447, 3)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 8, 255, 0, 0, 255); + Assert.Single(pixels.Where((value, index) => index % 4 == 3 && value != 0)); + } + + [Theory] + [InlineData("comment-length")] + [InlineData("comment-padding")] + [InlineData("group-description")] + [InlineData("unclosed-group")] + [InlineData("unexpected-group-end")] + [InlineData("wmf-length")] + [InlineData("region-size")] + [InlineData("region-count")] + [InlineData("region-null")] + public void RejectsMalformedCommentsAndRegions(string defect) + { + var record = defect switch + { + "comment-length" => Record(70, uint.MaxValue), + "comment-padding" => Record(70, 0, 0), + "group-description" => Record(70, 28, 0x43494447, 2, 0, 0, 32, 32, uint.MaxValue), + "unclosed-group" => Record(70, 28, 0x43494447, 2, 0, 0, 32, 32, 0), + "unexpected-group-end" => Record(70, 8, 0x43494447, 3), + "wmf-length" => Record(70, 24, 0x43494447, 0x80000001, 0x300, 0, 0, uint.MaxValue), + "region-size" => Record(75, uint.MaxValue, 5), + "region-count" => Record(75, 32, 5, 32, 1, 1, 16, 8, 8, 12, 12), + _ => Record(75, 0, 1) + }; + + Assert.Throws(() => EmfVectorRenderer.Render(Build(record), 32, 32)); + } + + [Theory] + [InlineData(0)] + public void RenderingExtensionsAreNotSilentlySkipped(uint identifier) + { + var emf = Build(Record(15, 1, 1, 0x0000FF), Record(70, 4, identifier)); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void EmptyEmfPlusCommentIsRejectedAsInvalid() + { + Assert.Throws(() => EmfVectorRenderer.Render(Build(Record(70, 4, 0x2B464D45)), 32, 32)); + } + + [Fact] + public void GdiOnlyEmfPlusProcessesOnlyTheGetDcScope() + { + var emf = Build(PlusRecord(0x4001, 1, 0xDBC01002, 0, 96, 96), Record(15, 1, 1, 0x0000FF), + PlusRecord(0x4004), Record(15, 4, 4, 0x0000FF), + PlusRecord(0x402B), Record(15, 8, 8, 0xFF0000), PlusRecord(0x4002)); + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + AssertPixel(pixels, 32, 1, 1, 0, 0, 0, 0); + AssertPixel(pixels, 32, 4, 4, 255, 0, 0, 255); + AssertPixel(pixels, 32, 8, 8, 0, 0, 0, 0); + } + + [Theory] + [InlineData("drawing")] + [InlineData("repeated-dc")] + public void UnsupportedEmfPlusSemanticsDoNotReturnPartialPictures(string feature) + { + var unsupported = feature == "drawing" ? PlusRecord(0x4009, 0, 0xFFFFFFFF) : PlusRecord(0x4004); + var emf = Build(PlusRecord(0x4001, 1, 0xDBC01002, 0, 96, 96), PlusRecord(0x4004), + Record(15, 4, 4, 0x0000FF), unsupported, PlusRecord(0x4002)); + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Theory] + [InlineData("missing-header")] + [InlineData("missing-eof")] + [InlineData("bad-size")] + public void RejectsMalformedEmfPlusStreams(string defect) + { + var header = PlusRecord(0x4001, 1, 0xDBC01002, 0, 96, 96); + if (defect == "bad-size") Set(header, 20, uint.MaxValue); + var records = new List(); + if (defect != "missing-header") records.Add(header); + records.Add(PlusRecord(0x4004)); + if (defect != "missing-eof") records.Add(PlusRecord(0x4002)); + Assert.Throws(() => EmfVectorRenderer.Render(Build(records.ToArray()), 32, 32)); + } + + private static byte[] PlusRecord(ushort type, ushort flags = 0, params uint[] data) => + Record(70, new uint[] { (uint)(16 + data.Length * 4), 0x2B464D45, + type | (uint)flags << 16, (uint)(12 + data.Length * 4), (uint)data.Length * 4 }.Concat(data).ToArray()); + + [Theory] + [InlineData(83)] + [InlineData(78)] + [InlineData(76)] + public void UnsupportedRecordsDoNotProducePartialImages(uint recordType) + { + var emf = Build(Record(15, 1, 1, 0x0000FF), Record(recordType)); + + var exception = Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + + Assert.Contains(recordType.ToString(), exception.Message); + } + + [Theory] + [InlineData("size")] + [InlineData("truncated")] + [InlineData("missing-eof")] + [InlineData("count")] + [InlineData("handles")] + [InlineData("zero-extent")] + [InlineData("restore")] + public void RejectsMalformedInputs(string defect) + { + var emf = defect switch + { + "truncated" => Build(Record(15, 1)), + "handles" => Build(Record(37, 3)), + "zero-extent" => Build(Record(9, 0, 32)), + "restore" => Build(Record(34, unchecked((uint)-1))), + _ => Build(Record(15, 1, 1, 0x0000FF)) + }; + if (defect == "size") BinaryPrimitives.WriteUInt32LittleEndian(emf.AsSpan(92), uint.MaxValue); + if (defect == "count") BinaryPrimitives.WriteUInt32LittleEndian(emf.AsSpan(52), 999); + if (defect == "missing-eof") + { + Array.Resize(ref emf, emf.Length - 20); + BinaryPrimitives.WriteUInt32LittleEndian(emf.AsSpan(48), (uint)emf.Length); + } + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void RejectsZeroOutputDimensions() + { + Assert.Throws(() => EmfVectorRenderer.Render(Build(), 0, 32)); + } + + [Fact] + public void RejectsExcessiveDeviceContextNesting() + { + var emf = Build(Enumerable.Range(0, 1025).Select(_ => Record(33)).ToArray()); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void ClipsExtremeSetPixelCoordinatesBeforeIntegerConversion() + { + var emf = Build( + Record(17, 8), + Record(9, 1, 1), + Record(11, int.MaxValue, int.MaxValue), + Record(15, int.MaxValue, int.MaxValue, 0x0000FF), + Record(15, 0, 0, 0xFF0000)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 0, 0, 0, 0, 255, 255); + Assert.Equal(1, Enumerable.Range(0, 32 * 32).Count(index => pixels[index * 4 + 3] != 0)); + } + + [Theory] + [InlineData(2, 8)] + [InlineData(3, 12)] + public void ComposesWorldTransformsInSpecifiedMultiplicationOrder(uint mode, int expectedLeft) + { + var emf = Build(Record(37, 0x80000008), Record(37, 0x80000004), + WorldRecord(35, new float[] { 1, 0, 0, 1, 4, 0 }), + WorldRecord(36, new float[] { 2, 0, 0, 2, 0, 0 }, mode), + Polygon16((2, 2), (4, 2), (4, 4), (2, 4))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, expectedLeft + 1, 5, 0, 0, 0, 255); + AssertPixel(pixels, 32, expectedLeft - 1, 5, 0, 0, 0, 0); + } + + [Fact] + public void RotatesWorldCoordinatesBeforePageMapping() + { + var emf = Build(Record(37, 0x80000008), Record(37, 0x80000004), + WorldRecord(35, new float[] { 0, 1, -1, 0, 20, 0 }), + Polygon16((2, 2), (6, 2), (6, 6), (2, 6))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 15, 3, 0, 0, 0, 255); + AssertPixel(pixels, 32, 3, 3, 0, 0, 0, 0); + } + + [Fact] + public void RestoresWorldTransformWithDeviceContext() + { + var emf = Build(Record(37, 0x80000008), Record(37, 0x80000004), + WorldRecord(35, new float[] { 1, 0, 0, 1, 8, 4 }), Record(33), + WorldRecord(35, new float[] { 1, 0, 0, 1, 20, 20 }), Record(34, unchecked((uint)-1)), + Polygon16((2, 2), (6, 2), (6, 6), (2, 6))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 11, 7, 0, 0, 0, 255); + AssertPixel(pixels, 32, 23, 23, 0, 0, 0, 0); + } + + [Fact] + public void IdentityModificationIgnoresUnusedTransformBytes() + { + var emf = Build(Record(37, 0x80000008), Record(37, 0x80000004), + WorldRecord(35, new float[] { 1, 0, 0, 1, 20, 20 }), + WorldRecord(36, Enumerable.Repeat(float.NaN, 6).ToArray(), 1), + Polygon16((2, 2), (6, 2), (6, 6), (2, 6))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 3, 3, 0, 0, 0, 255); + AssertPixel(pixels, 32, 23, 23, 0, 0, 0, 0); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsRotatedBitmapAndRectangularClipRatherThanUsingIncorrectBounds(bool bitmap) + { + var operation = bitmap ? BitmapRecord(24, -2, ColorPixels(24, true, false)) : Record(30, 0, 0, 12, 12); + var emf = Build(WorldRecord(35, new float[] { 0, 1, -1, 0, 20, 0 }), operation); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsSingularOrNonfiniteWorldTransforms(bool nonfinite) + { + var emf = Build(WorldRecord(35, nonfinite + ? new float[] { float.PositiveInfinity, 0, 0, 1, 0, 0 } + : new float[] { 1, 1, 1, 1, 0, 0 })); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void CapturingAPathDoesNotImmediatelyPaintIt() + { + var emf = Build(Record(59), Record(27, 4, 4), Record(54, 28, 4), + Record(54, 28, 28), Record(60)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + Assert.All(pixels, value => Assert.Equal(0, value)); + } + + [Theory] + [InlineData(62)] + [InlineData(63)] + [InlineData(64)] + public void PathPaintingDistinguishesFillStrokeAndImplicitClosure(uint operation) + { + var emf = Build(Record(39, 1, 0, 0x0000FF, 0), Record(37, 1), + Record(38, 2, 0, 0, 0, 0xFF0000), Record(37, 2), + Record(59), Record(27, 4, 4), Record(54, 28, 4), Record(54, 28, 28), + Record(54, 4, 28), Record(60), Record(operation, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 16, operation == 64 ? (byte)0 : (byte)255, 0, 0, operation == 64 ? (byte)0 : (byte)255); + AssertPixel(pixels, 32, 16, 4, operation == 62 ? (byte)255 : (byte)0, 0, operation == 62 ? (byte)0 : (byte)255, 255); + if (operation == 64) AssertPixel(pixels, 32, 4, 16, 0, 0, 0, 0); + else AssertPixel(pixels, 32, 4, 16, operation == 62 ? (byte)255 : (byte)0, 0, operation == 62 ? (byte)0 : (byte)255, 255); + } + + [Fact] + public void PathPointsRemainInDeviceSpaceAfterTransformChanges() + { + var emf = Build(Record(37, 0x80000004), Record(59), + Record(27, 4, 4), Record(54, 12, 4), Record(54, 12, 12), Record(54, 4, 12), Record(61), + Record(60), WorldRecord(35, new float[] { 1, 0, 0, 1, 16, 16 }), Record(62, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 6, 6, 0, 0, 0, 255); + AssertPixel(pixels, 32, 22, 22, 0, 0, 0, 0); + } + + [Fact] + public void TransformChangeBeforeFirstPathSegmentUsesTheTransformedLogicalCurrentPosition() + { + var emf = Build(Record(37, 0x80000004), Record(59), Record(27, 4, 4), + WorldRecord(35, new float[] { 1, 0, 0, 1, 8, 0 }), + Record(54, 12, 4), Record(54, 12, 12), Record(54, 4, 12), Record(61), Record(60), + WorldRecord(35, new float[] { 1, 0, 0, 1, 0, 0 }), Record(62, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 5, 5, 0, 0, 0, 0); + AssertPixel(pixels, 32, 13, 5, 0, 0, 0, 255); + } + + [Fact] + public void TransformChangeAfterPathSegmentBeginsANewFigureInsteadOfBridgingDevicePositions() + { + var emf = Build(Record(59), Record(27, 4, 4), Record(54, 12, 4), + WorldRecord(35, new float[] { 1, 0, 0, 1, 8, 0 }), + Record(54, 12, 12), Record(60), WorldRecord(35, new float[] { 1, 0, 0, 1, 0, 0 }), + Record(64, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 4, 0, 0, 0, 255); + AssertPixel(pixels, 32, 20, 8, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 8, 0, 0, 0, 0); + } + + [Fact] + public void CosmeticPenRemainsOneDevicePixelWideWhenOutputIsScaled() + { + var emf = Build(Record(27, 4, 4), Record(54, 28, 4)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 128, 128), 128, 128); + + AssertPixel(pixels, 128, 32, 16, 0, 0, 0, 255); + AssertPixel(pixels, 128, 32, 15, 0, 0, 0, 0); + AssertPixel(pixels, 128, 32, 17, 0, 0, 0, 0); + Assert.Equal(96, Enumerable.Range(0, 128 * 128).Count(index => pixels[index * 4 + 3] != 0)); + } + + [Fact] + public void ClipsCosmeticLineBeforeRasterizingExtremeIntegerCoordinates() + { + var emf = Build(Record(27, unchecked((uint)int.MinValue), 16), Record(54, int.MaxValue, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 0, 16, 0, 0, 0, 255); + AssertPixel(pixels, 32, 31, 16, 0, 0, 0, 255); + Assert.Equal(32, Enumerable.Range(0, 32 * 32).Count(index => pixels[index * 4 + 3] != 0)); + } + + [Fact] + public void RejectsStrokeCoordinatesBeyondTheClippingPrecisionLimit() + { + var emf = Build(WorldRecord(35, new float[] { 1e20f, 0, 0, 1, 0, 0 }), Record(54, 28, 4)); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void PreservesCollinearBezierExcursionsWhenStartAndEndCoincide() + { + var emf = Build(PointsRecord(2, (8, 16), (28, 16), (-12, 16), (8, 16))); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 3, 16, 0, 0, 0, 255); + AssertPixel(pixels, 32, 13, 16, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 16, 0, 0, 0, 0); + } + + [Theory] + [InlineData(1, false)] + [InlineData(2, true)] + public void FillsMultiplePathFiguresTogetherSoHolesRespectTheFillRule(uint fillMode, bool filled) + { + var emf = Build(Record(37, 0x80000004), Record(19, fillMode), Record(59), + Polygon16((4, 4), (28, 4), (28, 28), (4, 28)), + Polygon16((10, 10), (22, 10), (22, 22), (10, 22)), + Record(60), Record(62, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 16, 0, 0, 0, filled ? (byte)255 : (byte)0); + AssertPixel(pixels, 32, 6, 16, 0, 0, 0, 255); + } + + [Theory] + [InlineData(2)] + [InlineData(5)] + [InlineData(85)] + [InlineData(88)] + public void Flattens32And16BitCubicPathsWithoutFillingTheirControlPolygon(uint type) + { + var continues = type is 5 or 88; + var points = continues + ? new[] { (4, 4), (28, 4), (28, 24) } + : new[] { (4, 24), (4, 4), (28, 4), (28, 24) }; + var emf = Build(Record(37, 0x80000004), Record(59), Record(27, 4, 24), + PointsRecord(type, points), Record(60), Record(62, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 16, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 8, 0, 0, 0, 0); + AssertPixel(pixels, 32, 16, 10, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 25, 0, 0, 0, 0); + } + + [Theory] + [InlineData(6)] + [InlineData(89)] + public void PolylineToUpdatesCurrentPositionForSubsequentDrawing(uint type) + { + var emf = Build(Record(27, 4, 4), PointsRecord(type, (28, 4), (28, 28)), Record(54, 4, 28)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 4, 0, 0, 0, 255); + AssertPixel(pixels, 32, 28, 16, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 28, 0, 0, 0, 255); + AssertPixel(pixels, 32, 4, 16, 0, 0, 0, 0); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BeginAndAbortDiscardEarlierPaths(bool abort) + { + var records = new List { Record(37, 0x80000004), Record(59), Polygon16((4, 4), (12, 4), (4, 12)) }; + if (abort) records.Add(Record(68)); + records.AddRange(new[] { Record(59), Polygon16((20, 20), (28, 20), (20, 28)), Record(60), Record(62, 0, 0, 32, 32) }); + + var pixels = Decode(EmfVectorRenderer.Render(Build(records.ToArray()), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 5, 5, 0, 0, 0, 0); + AssertPixel(pixels, 32, 21, 21, 0, 0, 0, 255); + } + + [Fact] + public void ClosingFigureDoesNotMoveCurrentPositionAndSubsequentLineStartsANewFigure() + { + var emf = Build(Record(59), Record(27, 4, 4), Record(54, 12, 4), Record(54, 12, 12), + Record(61), Record(54, 20, 12), Record(60), Record(64, 0, 0, 32, 32)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 16, 12, 0, 0, 0, 255); + AssertPixel(pixels, 32, 16, 8, 0, 0, 0, 0); + } + + [Theory] + [InlineData("end")] + [InlineData("close")] + [InlineData("paint-open")] + [InlineData("paint-twice")] + [InlineData("curve-count")] + public void RejectsInvalidPathSequencesAndCubicPointCounts(string defect) + { + var records = defect switch + { + "end" => new[] { Record(60) }, + "close" => new[] { Record(59), Record(61) }, + "paint-open" => new[] { Record(59), Record(62, 0, 0, 32, 32) }, + "paint-twice" => new[] { Record(59), Record(60), Record(62, 0, 0, 32, 32), Record(62, 0, 0, 32, 32) }, + _ => new[] { PointsRecord(5, (4, 4), (12, 12)) } + }; + + Assert.Throws(() => EmfVectorRenderer.Render(Build(records), 32, 32)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsUnimplementedDeviceContextSavingWithPendingPath(bool restore) + { + var records = restore + ? new[] { Record(33), Record(59), Record(34, unchecked((uint)-1)) } + : new[] { Record(59), Record(33) }; + + Assert.Throws(() => EmfVectorRenderer.Render(Build(records), 32, 32)); + } + + private static byte[] WorldRecord(uint type, float[] values, uint mode = 0) + { + var bytes = new byte[type == 36 ? 36 : 32]; + Set(bytes, 0, type); + Set(bytes, 4, (uint)bytes.Length); + for (var index = 0; index < 6; index++) + BinaryPrimitives.WriteSingleLittleEndian(bytes.AsSpan(8 + index * 4), values[index]); + if (type == 36) Set(bytes, 32, mode); + return bytes; + } + + private static byte[] PointsRecord(uint type, params (int X, int Y)[] points) + { + var stride = type >= 85 ? 4 : 8; + var bytes = new byte[28 + points.Length * stride]; + Set(bytes, 0, type); + Set(bytes, 4, (uint)bytes.Length); + Set(bytes, 24, (uint)points.Length); + for (var index = 0; index < points.Length; index++) + { + if (stride == 4) + { + BinaryPrimitives.WriteInt16LittleEndian(bytes.AsSpan(28 + index * stride), checked((short)points[index].X)); + BinaryPrimitives.WriteInt16LittleEndian(bytes.AsSpan(30 + index * stride), checked((short)points[index].Y)); + } + else + { + Set(bytes, 28 + index * stride, unchecked((uint)points[index].X)); + Set(bytes, 32 + index * stride, unchecked((uint)points[index].Y)); + } + } + return bytes; + } + + [Theory] + [InlineData(16, false, false)] + [InlineData(16, true, false)] + [InlineData(16, false, true)] + [InlineData(16, true, true)] + [InlineData(24, false, false)] + [InlineData(24, true, false)] + [InlineData(32, false, false)] + [InlineData(32, true, false)] + [InlineData(32, false, true)] + [InlineData(32, true, true)] + public void RendersDibColorsRowOrientationAndPadding(int bitCount, bool topDown, bool bitfields) + { + uint[]? masks = !bitfields ? null : bitCount == 16 + ? new uint[] { 0xF800, 0x07E0, 0x001F } + : new uint[] { 0xFF0000, 0x00FF00, 0x0000FF }; + var bitmap = BitmapRecord(bitCount, topDown ? -2 : 2, ColorPixels(bitCount, topDown, bitfields), masks: masks); + var emf = Build(Record(21, 3), bitmap); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 6, 6, 255, 0, 0, 255); + AssertPixel(pixels, 32, 17, 6, 0, 255, 0, 255); + AssertPixel(pixels, 32, 6, 17, 0, 0, 255, 255); + AssertPixel(pixels, 32, 17, 17, 255, 255, 255, 255); + AssertPixel(pixels, 32, 2, 2, 0, 0, 0, 0); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void CropsDibSourceFromBottomRegardlessOfStorageDirection(bool topDown) + { + var bitmap = BitmapRecord(24, topDown ? -2 : 2, ColorPixels(24, topDown, false)); + Set(bitmap, 36, 0); + Set(bitmap, 44, 1); + var emf = Build(Record(21, 3), bitmap); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 6, 6, 0, 0, 255, 255); + AssertPixel(pixels, 32, 17, 6, 255, 255, 255, 255); + } + + [Fact] + public void AppliesDibMirroringMappingAndClip() + { + var bitmap = BitmapRecord(24, -2, ColorPixels(24, true, false)); + Set(bitmap, 24, 40); + Set(bitmap, 28, 8); + Set(bitmap, 72, unchecked((uint)-32)); + Set(bitmap, 76, 32); + var emf = Build(Record(17, 8), Record(9, 64, 64), Record(11, 32, 32), + Record(30, 16, 8, 40, 32), Record(21, 3), bitmap); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 6, 0, 255, 0, 255); + AssertPixel(pixels, 32, 17, 6, 255, 0, 0, 255); + AssertPixel(pixels, 32, 7, 6, 0, 0, 0, 0); + AssertPixel(pixels, 32, 8, 16, 0, 0, 0, 0); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MirroredDibExtentsIncludeStartPixelAndExcludeEndPixel(bool horizontal) + { + var bitmap = BitmapRecord(24, -2, ColorPixels(24, true, false)); + Set(bitmap, horizontal ? 24 : 28, 20); + Set(bitmap, horizontal ? 72 : 76, unchecked((uint)-16)); + + var pixels = Decode(EmfVectorRenderer.Render(Build(Record(21, 3), bitmap), 32, 32), 32, 32); + + void Check(int coordinate, params byte[] expected) => + AssertPixel(pixels, 32, horizontal ? coordinate : 6, horizontal ? 6 : coordinate, expected); + Check(4, 0, 0, 0, 0); + Check(5, 0, horizontal ? (byte)255 : (byte)0, horizontal ? (byte)0 : (byte)255, 255); + Check(12, 0, horizontal ? (byte)255 : (byte)0, horizontal ? (byte)0 : (byte)255, 255); + Check(13, 255, 0, 0, 255); + Check(20, 255, 0, 0, 255); + Check(21, 0, 0, 0, 0); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AlphaBlendUsesTopLeftSourceDcCoordinatesRegardlessOfDibStorage(bool topDown) + { + var bitmap = BitmapRecord(32, topDown ? -2 : 2, ColorPixels(32, topDown, false), alphaBlend: true); + Set(bitmap, 40, 0x00FF0000); + Set(bitmap, 104, 1); + + var pixels = Decode(EmfVectorRenderer.Render(Build(bitmap), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 6, 6, 255, 0, 0, 255); + AssertPixel(pixels, 32, 17, 6, 0, 255, 0, 255); + } + + [Fact] + public void NormalizesNonstandardContiguousDibMasks() + { + var bitmap = BitmapRecord(16, -1, new byte[] { 16, 0, 0, 0 }, + masks: new uint[] { 0x001F, 0x03E0, 0x7C00 }, imageWidth: 1); + var pixels = Decode(EmfVectorRenderer.Render(Build(Record(21, 3), bitmap), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 8, 132, 0, 0, 255); + } + + [Theory] + [InlineData(0, false)] + [InlineData(128, false)] + [InlineData(255, false)] + [InlineData(0, true)] + [InlineData(128, true)] + [InlineData(255, true)] + public void CombinesPremultipliedPixelAndConstantAlpha(int constantAlpha, bool opaqueBackground) + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 128, 128 }, alphaBlend: true, + masks: new uint[] { 0xFF0000, 0x00FF00, 0x0000FF }, imageWidth: 1); + Set(bitmap, 40, 0x01000000 | (uint)constantAlpha << 16); + var records = new List(); + if (opaqueBackground) + { + records.Add(Record(39, 1, 0, 0xFF0000, 0)); + records.Add(Record(37, 1)); + records.Add(Record(37, 0x80000008)); + records.Add(Record(43, 0, 0, 32, 32)); + } + records.Add(bitmap); + var pixels = Decode(EmfVectorRenderer.Render(Build(records.ToArray()), 32, 32), 32, 32); + + var alpha = (byte)Math.Round(128 * constantAlpha / 255d); + if (opaqueBackground) + AssertPixel(pixels, 32, 8, 8, alpha, 0, (byte)(255 - alpha), 255); + else + AssertPixel(pixels, 32, 8, 8, alpha == 0 ? (byte)0 : (byte)255, 0, 0, alpha); + } + + [Fact] + public void CompositesMultipleLayersWithoutTreatingStraightPngChannelsAsPremultiplied() + { + var red = BitmapRecord(32, -1, new byte[] { 0, 0, 128, 128 }, alphaBlend: true, imageWidth: 1); + var blue = BitmapRecord(32, -1, new byte[] { 64, 0, 0, 64 }, alphaBlend: true, imageWidth: 1); + + var pixels = Decode(EmfVectorRenderer.Render(Build(red, blue), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 8, 153, 0, 102, 160); + } + + [Fact] + public void IgnoresReservedDibAlphaWhenPerPixelAlphaFlagIsAbsent() + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 255, 0 }, alphaBlend: true, imageWidth: 1); + Set(bitmap, 40, 0x00800000); + + var pixels = Decode(EmfVectorRenderer.Render(Build(bitmap), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 8, 8, 255, 0, 0, 128); + } + + [Theory] + [InlineData(128, false)] + [InlineData(128, true)] + [InlineData(255, false)] + [InlineData(255, true)] + public void ReservedBlendFlagsPreserveConstantAndPerPixelAlpha(int flags, bool perPixelAlpha) + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 64, 128 }, alphaBlend: true, imageWidth: 1); + var blend = 0x00800000u | (perPixelAlpha ? 0x01000000u : 0); + Set(bitmap, 40, blend); + var expected = EmfVectorRenderer.Render(Build(bitmap), 32, 32); + + Set(bitmap, 40, blend | (uint)flags << 8); + var actual = EmfVectorRenderer.Render(Build(bitmap), 32, 32); + + Assert.Equal(expected, actual); + AssertPixel(Decode(actual, 32, 32), 32, 8, 8, + perPixelAlpha ? (byte)128 : (byte)64, 0, 0, perPixelAlpha ? (byte)64 : (byte)128); + } + + [Theory] + [InlineData("depth")] + [InlineData("compression")] + [InlineData("rop")] + [InlineData("stretch-mode")] + [InlineData("blend-operation")] + [InlineData("alpha-format")] + [InlineData("transform")] + public void RejectsUnsupportedBitmapFeaturesInsteadOfReturningPartialImages(string feature) + { + var alphaBlend = feature is "blend-operation" or "alpha-format" or "transform"; + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 0, 255 }, alphaBlend: alphaBlend, imageWidth: 1); + var info = alphaBlend ? 108 : 80; + if (feature == "depth") BinaryPrimitives.WriteUInt16LittleEndian(bitmap.AsSpan(info + 14), 8); + if (feature == "compression") Set(bitmap, info + 16, 1); + if (feature == "rop") Set(bitmap, 68, 0x00660046); + if (feature == "blend-operation") Set(bitmap, 40, 0x01FF0001); + if (feature == "alpha-format") Set(bitmap, 40, 0x02FF0000); + if (feature == "transform") Set(bitmap, 52, 0x40000000); + var emf = feature == "stretch-mode" ? Build(bitmap) : Build(Record(21, 3), bitmap); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Theory] + [InlineData("offset")] + [InlineData("length")] + [InlineData("overlap")] + [InlineData("header")] + [InlineData("dimensions")] + [InlineData("planes")] + [InlineData("pixels")] + [InlineData("source-rectangle")] + [InlineData("masks")] + public void RejectsMalformedBitmapRangesAndMetadata(string defect) + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 0, 0 }, + masks: new uint[] { 0xFF0000, 0x00FF00, 0x0000FF }, imageWidth: 1); + if (defect == "offset") Set(bitmap, 48, uint.MaxValue); + if (defect == "length") Set(bitmap, 52, uint.MaxValue); + if (defect == "overlap") Set(bitmap, 56, 80); + if (defect == "header") Set(bitmap, 80, 124); + if (defect == "dimensions") Set(bitmap, 88, 0x80000000); + if (defect == "planes") BinaryPrimitives.WriteUInt16LittleEndian(bitmap.AsSpan(92), 2); + if (defect == "pixels") Set(bitmap, 60, 1); + if (defect == "source-rectangle") Set(bitmap, 32, int.MaxValue); + if (defect == "masks") Set(bitmap, 120, 0x00FF00); + + Assert.Throws(() => + EmfVectorRenderer.Render(Build(Record(21, 3), bitmap), 32, 32)); + } + + [Fact] + public void RejectsNonpremultipliedAlphaSource() + { + var bitmap = BitmapRecord(32, -1, new byte[] { 0, 0, 255, 128 }, alphaBlend: true, imageWidth: 1); + + Assert.Throws(() => EmfVectorRenderer.Render(Build(bitmap), 32, 32)); + } + + [Theory] + [InlineData(24u, 4u)] + [InlineData(26u, 28u)] + [InlineData(30u, 16u)] + public void CompatibleScalePreservesExplicitAdvancesAndHorizontalAlignment(uint alignment, uint referenceX) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var expectedDefinition = FontRecord(); + Set(expectedDefinition, 16, 6); + var expectedText = TextRecord(referenceX, 24, new ushort[] { 1, 1 }, 16, new[] { 12, 12 }); + var compatibleText = (byte[])expectedText.Clone(); + Set(compatibleText, 24, 1); Set(compatibleText, 28, 0x40000000); + byte[] RenderText(byte[] definition, byte[] text) => EmfVectorRenderer.Render( + Build(definition, Record(37, 1), Record(18, 1), Record(22, alignment), text), 32, 32, (_, _, _) => font); + + var expected = RenderText(expectedDefinition, expectedText); + var actual = RenderText(FontRecord(), compatibleText); + + Assert.Equal(expected, actual); + var pixels = Decode(actual, 32, 32); + AssertPixel(pixels, 32, 5, 11, 0, 0, 0, 255); + AssertPixel(pixels, 32, 9, 11, 0, 0, 0, 0); + AssertPixel(pixels, 32, 17, 11, 0, 0, 0, 255); + } + + [Theory] + [InlineData(0u)] + [InlineData(12u)] + public void CompatibleScaleAdjustsDefaultAndRequestedFontWidthsAndNaturalAdvances(uint requestedWidth) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var definition = FontRecord(); Set(definition, 16, requestedWidth); + var expectedDefinition = FontRecord(); Set(expectedDefinition, 16, 6); + var expectedText = TextRecord(4, 24, new ushort[] { 1, 1 }, 16); + var compatibleText = (byte[])expectedText.Clone(); + Set(compatibleText, 24, 1); Set(compatibleText, 28, 0x40000000); + byte[] RenderText(byte[] face, byte[] text) => EmfVectorRenderer.Render( + Build(face, Record(37, 1), Record(18, 1), Record(22, 24), text), 32, 32, (_, _, _) => font); + + Assert.Equal(RenderText(expectedDefinition, expectedText), RenderText(definition, compatibleText)); + } + + [Fact] + public void CompatibleScalePreservesPairedAdvancesAndLocalClipping() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = TextRecord(4, 24, new ushort[] { 1, 1 }, 0x2014, new[] { 12, 2, 0, 0 }); + Set(text, 24, 1); Set(text, 28, 0x40000000); + Set(text, 56, 4); Set(text, 60, 10); Set(text, 64, 21); Set(text, 68, 32); + var emf = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), text, Record(15, 30, 30, 0xFF0000)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 17, 11, 0, 0, 0, 0); + AssertPixel(pixels, 32, 17, 13, 0, 0, 0, 255); + AssertPixel(pixels, 32, 21, 13, 0, 0, 0, 0); + AssertPixel(pixels, 32, 30, 30, 0, 0, 255, 255); + } + + [Fact] + public void AdvancedTextIgnoresCompatibleScaleFields() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = TextRecord(4, 24, new ushort[] { 1, 1 }, 16); + var modified = (byte[])text.Clone(); + Set(modified, 28, 0x40000000); Set(modified, 32, 0); + byte[] RenderText(byte[] record) => EmfVectorRenderer.Render( + Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), record), 32, 32, (_, _, _) => font); + + Assert.Equal(RenderText(text), RenderText(modified)); + } + + [Theory] + [InlineData(0f, 1f)] + [InlineData(-1f, 1f)] + [InlineData(1f, -1f)] + [InlineData(float.NaN, 1f)] + [InlineData(1f, float.PositiveInfinity)] + public void InvalidOrUnsupportedCompatibleScalesDoNotReturnPartialImages(float xScale, float yScale) + { + var text = TextRecord(0, 0, Array.Empty(), 2); + Set(text, 24, 1); Set(text, 28, BitConverter.SingleToUInt32Bits(xScale)); Set(text, 32, BitConverter.SingleToUInt32Bits(yScale)); + var emf = Build(Record(15, 4, 4, 0x0000FF), text); + + if (!float.IsFinite(xScale) || !float.IsFinite(yScale)) + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + else + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32)); + } + + [Fact] + public void CompatibleOpaqueTextDoesNotScaleItsRectangleAndRestoresThePreviousClip() + { + var text = TextRecord(0, 0, Array.Empty(), 6); + Set(text, 24, 1); Set(text, 28, 0x40000000); + Set(text, 56, 4); Set(text, 60, 5); Set(text, 64, 10); Set(text, 68, 12); + var emf = Build(Record(30, 2, 2, 16, 16), Record(25, 0x00FF00), text, + Record(15, 12, 5, 0xFF0000), Record(15, 20, 20, 0x0000FF)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32), 32, 32); + + AssertPixel(pixels, 32, 4, 5, 0, 255, 0, 255); + AssertPixel(pixels, 32, 10, 5, 0, 0, 0, 0); + AssertPixel(pixels, 32, 12, 5, 0, 0, 255, 255); + AssertPixel(pixels, 32, 20, 20, 0, 0, 0, 0); + } + + [Theory] + [InlineData(false, 24, 4)] + [InlineData(true, 26, 28)] + [InlineData(true, 30, 16)] + public void RendersIndependentGlyphContoursWithHolesAndTextAlignment(bool glyphIndices, uint alignment, uint referenceX) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var emf = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, alignment), + Record(24, 0x0000FF), TextRecord(referenceX, 24, glyphIndices ? new ushort[] { 1, 1 } : new ushort[] { 65, 65 }, + glyphIndices ? 16u : 0u)); + var names = new List(); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (name, _, _) => { names.Add(name); return font; }), 32, 32); + + Assert.Equal(new[] { "Synthetic" }, names); + AssertPixel(pixels, 32, 5, 11, 255, 0, 0, 255); + AssertPixel(pixels, 32, 9, 17, 0, 0, 0, 0); + AssertPixel(pixels, 32, 17, 11, 255, 0, 0, 255); + AssertPixel(pixels, 32, 15, 11, 0, 0, 0, 0); + } + + [Fact] + public void PositiveFontHeightsUseCellMetricsForOutlinesAndAdvances() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var positive = FontRecord(); + Set(positive, 12, 24); + var text = TextRecord(4, 24, new ushort[] { 1, 1 }, 16); + byte[] RenderText(byte[] definition) => EmfVectorRenderer.Render( + Build(definition, Record(37, 1), Record(18, 1), Record(22, 24), text), + 32, 32, (_, _, _) => font); + + var expected = Decode(RenderText(FontRecord()), 32, 32); + var actual = Decode(RenderText(positive), 32, 32); + + Assert.Equal(expected, actual); + AssertPixel(actual, 32, 5, 11, 0, 0, 0, 255); + AssertPixel(actual, 32, 17, 11, 0, 0, 0, 255); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsUnusableCellMetricsWithoutReturningPartialImages(bool truncated) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var cell = TrueTypeGlyphReaderTests.TableOffset(font, "OS/2"); + TrueTypeGlyphReaderTests.Write16(font, cell + 74, 0); + TrueTypeGlyphReaderTests.Write16(font, cell + 76, 0); + if (truncated) + { + for (var entry = 12; entry < 12 + BinaryPrimitives.ReadUInt16BigEndian(font.AsSpan(4)) * 16; entry += 16) + if (System.Text.Encoding.ASCII.GetString(font, entry, 4) == "OS/2") + TrueTypeGlyphReaderTests.Write32(font, entry + 12, 76); + } + var definition = FontRecord(); + Set(definition, 12, 24); + var emf = Build(Record(15, 1, 1, 0x0000FF), definition, Record(37, 1), + Record(18, 1), Record(22, 24), TextRecord(4, 24, new ushort[] { 1 }, 16)); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font)); + } + + [Fact] + public void NegativeCharacterHeightsDoNotRequireCellMetrics() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var os2 = TrueTypeGlyphReaderTests.TableOffset(font, "OS/2"); + TrueTypeGlyphReaderTests.Write16(font, os2 + 74, 0); + TrueTypeGlyphReaderTests.Write16(font, os2 + 76, 0); + var emf = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new ushort[] { 1 }, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 5, 11, 0, 0, 0, 255); + AssertPixel(pixels, 32, 15, 11, 0, 0, 0, 0); + } + + [Fact] + public void RequestedFontWidthsScaleOutlinesButNotExplicitSpacing() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var definition = FontRecord(); + Set(definition, 12, 24); + Set(definition, 16, 6); + byte[] RenderText(int[]? advances) => Decode(EmfVectorRenderer.Render( + Build(definition, Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new ushort[] { 1, 1 }, 16, advances)), + 32, 32, (_, _, _) => font), 32, 32); + + var measured = RenderText(null); + var positioned = RenderText(new[] { 12, 0 }); + + AssertPixel(measured, 32, 8, 11, 0, 0, 0, 255); + AssertPixel(measured, 32, 9, 11, 0, 0, 0, 0); + AssertPixel(measured, 32, 11, 11, 0, 0, 0, 255); + AssertPixel(positioned, 32, 11, 11, 0, 0, 0, 0); + AssertPixel(positioned, 32, 17, 11, 0, 0, 0, 255); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void RejectsUnusableAverageWidthWhenCustomFontWidthIsRequested(int average) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + TrueTypeGlyphReaderTests.Write16(font, TrueTypeGlyphReaderTests.TableOffset(font, "OS/2") + 2, average); + var definition = FontRecord(); + Set(definition, 16, 6); + var emf = Build(Record(15, 1, 1, 0x0000FF), definition, Record(37, 1), + Record(18, 1), Record(22, 24), TextRecord(4, 24, new ushort[] { 1 }, 16)); + + Assert.Throws(() => EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font)); + } + + [Fact] + public void RendersQuadraticContoursWithImplicitOffCurveEndpoints() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Simple( + new[] { (0, 0, false), (250, 700, false), (500, 0, false) })); + var emf = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new ushort[] { 1 }, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 9, 17, 0, 0, 0, 255); + AssertPixel(pixels, 32, 4, 10, 0, 0, 0, 0); + AssertPixel(pixels, 32, 9, 25, 0, 0, 0, 0); + } + + [Fact] + public void AppliesPairedTextSpacingAndRestoresTextClipForLaterDrawing() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = TextRecord(4, 24, new ushort[] { 1, 1 }, 0x2014, new[] { 12, 2, 0, 0 }); + Set(text, 56, 4); Set(text, 60, 10); Set(text, 64, 21); Set(text, 68, 32); + var emf = Build(FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), text, Record(15, 30, 30, 0xFF0000)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 17, 11, 0, 0, 0, 0); + AssertPixel(pixels, 32, 17, 13, 0, 0, 0, 255); + AssertPixel(pixels, 32, 23, 13, 0, 0, 0, 0); + AssertPixel(pixels, 32, 30, 30, 0, 0, 255, 255); + } + + [Fact] + public void EmptyOpaqueTextFillsTheSpecifiedRectangleWithoutLoadingFonts() + { + var text = TextRecord(0, 0, Array.Empty(), 2); + Set(text, 56, 4); Set(text, 60, 5); Set(text, 64, 10); Set(text, 68, 12); + + var pixels = Decode(EmfVectorRenderer.Render(Build(Record(25, 0x00FF00), text), 32, 32), 32, 32); + + AssertPixel(pixels, 32, 4, 5, 0, 255, 0, 255); + AssertPixel(pixels, 32, 10, 5, 0, 0, 0, 0); + } + + [Fact] + public void RestoresFontAndTextStateAlongWithTheDeviceContext() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var small = FontRecord(); + Set(small, 8, 2); Set(small, 12, unchecked((uint)-10)); + var emf = Build(FontRecord(), small, Record(37, 1), Record(18, 1), Record(22, 24), Record(24, 0x0000FF), + Record(33), Record(37, 2), Record(24, 0xFF0000), Record(22, 26), Record(18, 2), + Record(34, uint.MaxValue), TextRecord(4, 24, new ushort[] { 1 }, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, (_, _, _) => font), 32, 32); + + AssertPixel(pixels, 32, 5, 11, 255, 0, 0, 255); + AssertPixel(pixels, 32, 9, 17, 0, 0, 0, 0); + } + + [Theory] + [InlineData("string-range")] + [InlineData("spacing-range")] + [InlineData("count")] + [InlineData("duplicate-handle")] + [InlineData("glyph")] + public void RejectsMalformedTextAndSharedObjectHandles(string defect) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var text = TextRecord(4, 24, new ushort[] { 1 }, 16, new[] { 12 }); + if (defect == "string-range") Set(text, 48, uint.MaxValue); + if (defect == "spacing-range") Set(text, 72, uint.MaxValue); + if (defect == "count") Set(text, 44, uint.MaxValue); + if (defect == "glyph") BinaryPrimitives.WriteUInt16LittleEndian(text.AsSpan(76), 65535); + var records = new List { FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24) }; + if (defect == "duplicate-handle") records.Add(Record(39, 1, 0, 0, 0)); + records.Add(text); + + Assert.Throws(() => EmfVectorRenderer.Render(Build(records.ToArray()), 32, 32, (_, _, _) => font)); + } + + [Theory] + [InlineData("resolver")] + [InlineData("bottom-layout")] + [InlineData("rtl-layout")] + [InlineData("current-position")] + [InlineData("shaping")] + [InlineData("font-height")] + [InlineData("text-options")] + public void UnsupportedTextDoesNotReturnPartialImages(string defect) + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var definition = FontRecord(); + var text = TextRecord(4, 24, new ushort[] { 65 }, 0); + if (defect == "font-height") Set(definition, 12, 0); + if (defect == "shaping") BinaryPrimitives.WriteUInt16LittleEndian(text.AsSpan(76), 0x627); + if (defect == "text-options") Set(text, 52, 0x80); + var alignment = defect switch { "bottom-layout" => 8u, "rtl-layout" => 280u, "current-position" => 25u, _ => 24u }; + var emf = Build(Record(15, 1, 1, 0x0000FF), definition, Record(37, 1), + Record(18, 1), Record(22, alignment), text); + + Assert.Throws(() => + EmfVectorRenderer.Render(emf, 32, 32, defect == "resolver" ? null : (_, _, _) => font)); + } + + [Fact] + public void ResettingTextAlignmentAfterDrawingDoesNotInvalidateTheImage() + { + var font = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var records = new[] { FontRecord(), Record(37, 1), Record(18, 1), Record(22, 24), + TextRecord(4, 24, new ushort[] { 1 }, 16) }; + var expected = EmfVectorRenderer.Render(Build(records), 32, 32, (_, _, _) => font); + var actual = EmfVectorRenderer.Render(Build(records.Concat(new[] { Record(22, 0) }).ToArray()), + 32, 32, (_, _, _) => font); + + Assert.Equal(expected, actual); + } + + [Theory] + [InlineData(4u)] + [InlineData(16u)] + [InlineData(32u)] + public void RejectsInvalidTextAlignmentValues(uint alignment) + { + Assert.Throws(() => + EmfVectorRenderer.Render(Build(Record(22, alignment)), 32, 32)); + } + + [Fact] + public void ResolvesStyledFacesWithoutRewritingTheirNames() + { + var bytes = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + var definition = FontRecord(); + System.Text.Encoding.Unicode.GetBytes("Synthetic Bold\0").CopyTo(definition, 40); + Set(definition, 28, 700); + definition[32] = 1; + var requests = new List<(string, bool, bool)>(); + var emf = Build(definition, Record(37, 1), Record(18, 1), Record(22, 24), TextRecord(4, 24, new ushort[] { 1 }, 16)); + + var pixels = Decode(EmfVectorRenderer.Render(emf, 32, 32, + (name, bold, italic) => { requests.Add((name, bold, italic)); return bytes; }), 32, 32); + + Assert.Equal(new[] { ("Synthetic Bold", true, true) }, requests); + AssertPixel(pixels, 32, 5, 11, 0, 0, 0, 255); + } + + internal static byte[] FontRecord(string face = "Synthetic") + { + var bytes = new byte[332]; + Set(bytes, 0, 82); Set(bytes, 4, (uint)bytes.Length); Set(bytes, 8, 1); + Set(bytes, 12, unchecked((uint)-20)); Set(bytes, 28, 400); + System.Text.Encoding.Unicode.GetBytes(face + "\0").CopyTo(bytes, 40); + return bytes; + } + + internal static byte[] TextRecord(uint x, uint y, ushort[] values, uint options, int[]? advances = null) + { + var spacingOffset = (76 + values.Length * 2 + 3) & ~3; + var bytes = new byte[spacingOffset + (advances?.Length ?? 0) * 4]; + Set(bytes, 0, 84); Set(bytes, 4, (uint)bytes.Length); Set(bytes, 24, 2); + Set(bytes, 28, 0x3F800000); Set(bytes, 32, 0x3F800000); + Set(bytes, 36, x); Set(bytes, 40, y); Set(bytes, 44, (uint)values.Length); + Set(bytes, 48, 76); Set(bytes, 52, options); + Set(bytes, 72, advances == null ? 0u : (uint)spacingOffset); + for (var index = 0; index < values.Length; index++) + BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(76 + index * 2), values[index]); + if (advances != null) + for (var index = 0; index < advances.Length; index++) Set(bytes, spacingOffset + index * 4, unchecked((uint)advances[index])); + return bytes; + } + + private static void Set(byte[] bytes, int offset, uint value) => + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(offset), value); + + internal static byte[] BitmapRecord(int bitCount, int signedHeight, byte[] bits, + bool alphaBlend = false, uint[]? masks = null, int imageWidth = 2) + { + var fixedSize = alphaBlend ? 108 : 80; + var infoSize = 40 + (masks?.Length ?? 0) * 4; + var bytes = new byte[(fixedSize + infoSize + bits.Length + 3) & ~3]; + Set(bytes, 0, alphaBlend ? 114u : 81u); + Set(bytes, 4, (uint)bytes.Length); + Set(bytes, 24, 4); + Set(bytes, 28, 4); + if (alphaBlend) + { + Set(bytes, 32, 16); + Set(bytes, 36, 16); + Set(bytes, 40, 0x01FF0000); + Set(bytes, 52, 0x3F800000); + Set(bytes, 64, 0x3F800000); + Set(bytes, 100, (uint)imageWidth); + Set(bytes, 104, (uint)Math.Abs(signedHeight)); + } + else + { + Set(bytes, 40, (uint)imageWidth); + Set(bytes, 44, (uint)Math.Abs(signedHeight)); + Set(bytes, 68, 0x00CC0020); + Set(bytes, 72, 16); + Set(bytes, 76, 16); + } + var fieldsOffset = alphaBlend ? 84 : 48; + Set(bytes, fieldsOffset, (uint)fixedSize); + Set(bytes, fieldsOffset + 4, (uint)infoSize); + Set(bytes, fieldsOffset + 8, (uint)(fixedSize + infoSize)); + Set(bytes, fieldsOffset + 12, (uint)bits.Length); + Set(bytes, fixedSize, 40); + Set(bytes, fixedSize + 4, (uint)imageWidth); + Set(bytes, fixedSize + 8, unchecked((uint)signedHeight)); + BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(fixedSize + 12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(fixedSize + 14), (ushort)bitCount); + Set(bytes, fixedSize + 16, masks == null ? 0u : 3u); + Set(bytes, fixedSize + 20, (uint)bits.Length); + if (masks != null) + for (var index = 0; index < masks.Length; index++) Set(bytes, fixedSize + 40 + index * 4, masks[index]); + bits.CopyTo(bytes, fixedSize + infoSize); + return bytes; + } + + private static byte[] ColorPixels(int bitCount, bool topDown, bool bitfields) + { + var colors = bitCount == 16 + ? new uint[] { bitfields ? 0xF800u : 0x7C00u, bitfields ? 0x07E0u : 0x03E0u, 0x001F, bitfields ? 0xFFFFu : 0x7FFFu } + : new uint[] { 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFFFF }; + var stride = (2 * bitCount + 31) / 32 * 4; + var bits = new byte[stride * 2]; + for (var y = 0; y < 2; y++) + { + for (var x = 0; x < 2; x++) + { + var position = (topDown ? y : 1 - y) * stride + x * (bitCount / 8); + var value = colors[y * 2 + x]; + for (var channel = 0; channel < bitCount / 8; channel++) bits[position + channel] = (byte)(value >> (channel * 8)); + } + } + return bits; + } + + internal static byte[] Build(params byte[][] records) + { + var header = new byte[88]; + void Set(int offset, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(offset), value); + Set(0, 1); + Set(4, 88); + Set(16, 32); + Set(20, 32); + Set(32, 847); + Set(36, 847); + Set(40, 0x464D4520); + Set(44, 0x10000); + Set(48, (uint)(88 + records.Sum(record => record.Length) + 20)); + Set(52, (uint)(records.Length + 2)); + Set(56, 16); + using var stream = new MemoryStream(); + stream.Write(header); + foreach (var record in records) stream.Write(record); + stream.Write(Record(14, 0, 0, 20)); + return stream.ToArray(); + } + + internal static byte[] Record(uint type, params uint[] values) + { + var bytes = new byte[8 + values.Length * 4]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, type); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), (uint)bytes.Length); + for (var index = 0; index < values.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(8 + index * 4), values[index]); + return bytes; + } + + private static byte[] Polygon16(params (short X, short Y)[] points) + { + var bytes = new byte[28 + points.Length * 4]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, 86); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4), (uint)bytes.Length); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(24), (uint)points.Length); + for (var index = 0; index < points.Length; index++) + { + BinaryPrimitives.WriteInt16LittleEndian(bytes.AsSpan(28 + index * 4), points[index].X); + BinaryPrimitives.WriteInt16LittleEndian(bytes.AsSpan(30 + index * 4), points[index].Y); + } + return bytes; + } + + internal static byte[] Decode(byte[] png, int width, int height) + { + Assert.Equal(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, png[..8]); + Assert.Equal(width, BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(16))); + Assert.Equal(height, BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20))); + using var compressed = new MemoryStream(); + for (var offset = 8; offset < png.Length;) + { + var size = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(offset)); + var chunk = png.AsSpan(offset + 4, size + 4); + uint crc = uint.MaxValue; + foreach (var value in chunk) + { + crc ^= value; + for (var bit = 0; bit < 8; bit++) + crc = (crc & 1) == 0 ? crc >> 1 : (crc >> 1) ^ 0xEDB88320; + } + Assert.Equal(~crc, BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(offset + size + 8))); + if (chunk[..4].SequenceEqual("IDAT"u8)) compressed.Write(png, offset + 8, size); + offset += size + 12; + } + compressed.Position = 0; + using var zlib = new ZLibStream(compressed, CompressionMode.Decompress); + var filtered = new byte[height * (width * 4 + 1)]; + zlib.ReadExactly(filtered); + Assert.Equal(-1, zlib.ReadByte()); + var pixels = new byte[width * height * 4]; + for (var row = 0; row < height; row++) + { + Assert.Equal(0, filtered[row * (width * 4 + 1)]); + Buffer.BlockCopy(filtered, row * (width * 4 + 1) + 1, pixels, row * width * 4, width * 4); + } + return pixels; + } + + private static void AssertPixel(byte[] pixels, int width, int x, int y, params byte[] expected) + { + Assert.Equal(expected, pixels.AsSpan((y * width + x) * 4, 4).ToArray()); + } +} diff --git a/tests/MiniPdf.Tests/RegisteredFontTests.cs b/tests/MiniPdf.Tests/RegisteredFontTests.cs index 8f2b272c..4d425649 100644 --- a/tests/MiniPdf.Tests/RegisteredFontTests.cs +++ b/tests/MiniPdf.Tests/RegisteredFontTests.cs @@ -67,4 +67,30 @@ public void ClearRegisteredFonts_DoesNotChangeEarlierSnapshot() Assert.Equal("NotoSansTC", Assert.Single(snapshot).Name); } + + [Fact] + public void MetafileResolverUsesTheRegisteredFamilyWithoutSubstitution() + { + var data = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + MiniPdf.RegisterFont("MiniPdfRegisteredMetafileFace", data); + + Assert.Same(data, PdfWriter.ResolveMetafileFont("MiniPdfRegisteredMetafileFace", false, false)); + } + + [Fact] + public void MetafileResolverUsesSameFamilyOutlinesForSyntheticBold() + { + var data = TrueTypeGlyphReaderTests.CreateFont(TrueTypeGlyphReaderTests.Box()); + TrueTypeGlyphReaderTests.Write16(data, TrueTypeGlyphReaderTests.TableOffset(data, "OS/2") + 4, 400); + MiniPdf.RegisterFont("MiniPdfRegisteredMetafileFace", data); + + Assert.Same(data, PdfWriter.ResolveMetafileFont("MiniPdfRegisteredMetafileFace", true, false)); + } + + [Fact] + public void MetafileResolverRejectsAnUnavailableFamily() + { + Assert.Throws(() => + PdfWriter.ResolveMetafileFont("MiniPdfNoSuchMetafileFamilyF6DD51", false, false)); + } } diff --git a/tests/MiniPdf.Tests/TrueTypeGlyphReaderTests.cs b/tests/MiniPdf.Tests/TrueTypeGlyphReaderTests.cs new file mode 100644 index 00000000..90e3743e --- /dev/null +++ b/tests/MiniPdf.Tests/TrueTypeGlyphReaderTests.cs @@ -0,0 +1,310 @@ +using System.Buffers.Binary; + +namespace MiniSoftware.Tests; + +public class TrueTypeGlyphReaderTests +{ + [Fact] + public void ReadsContoursAndHorizontalMetricsWithoutDrawingDependencies() + { + var font = new TrueTypeGlyphReader(CreateFont(Box())); + var contours = font.ReadGlyph(1); + + Assert.Equal(1000, font.UnitsPerEm); + Assert.Equal(600, font.Advance(1)); + Assert.Equal(1, font.GlyphForCharacter('A')); + Assert.Equal(2, contours.Count); + Assert.Equal(new[] { (0d, 0d), (0d, 700d), (500d, 700d), (500d, 0d) }, + contours[0].Select(point => (point.X, point.Y))); + Assert.All(contours.SelectMany(contour => contour), point => Assert.True(point.OnCurve)); + Assert.Empty(font.ReadGlyph(0)); + } + + [Fact] + public void DecodesRepeatedFlagsAndUnsignedShortCoordinateDeltas() + { + var glyph = new byte[24]; + Write16(glyph, 0, 1); + Write16(glyph, 10, 3); + glyph[14] = 0x3F; + glyph[15] = 3; + new byte[] { 10, 20, 30, 40, 20, 20, 20, 20 }.CopyTo(glyph, 16); + var font = new TrueTypeGlyphReader(CreateFont(glyph)); + + Assert.Equal(new[] { (10d, 20d), (30d, 40d), (60d, 60d), (100d, 80d) }, + Assert.Single(font.ReadGlyph(1)).Select(point => (point.X, point.Y))); + } + + [Theory] + [InlineData(0x000B, 100, 200)] + [InlineData(0x080B, 50, 100)] + [InlineData(0x100B, 100, 200)] + public void ScalesCompositePointsAndHonorsOffsetCoordinateSystem(ushort flags, int expectedX, int expectedY) + { + var font = new TrueTypeGlyphReader(CreateFont(Box(), Composite(flags, 1, 100, 200, 8192))); + + var contours = font.ReadGlyph(2); + + Assert.Equal((expectedX, expectedY), ((int)contours[0][0].X, (int)contours[0][0].Y)); + Assert.Equal((expectedX + 250, expectedY + 350), ((int)contours[0][2].X, (int)contours[0][2].Y)); + } + + [Fact] + public void AppliesCompositeMatrixInOpenTypeRowVectorOrder() + { + var font = new TrueTypeGlyphReader(CreateFont(Box(), Composite(0x83, 1, -100, 200, 0, 16384, -16384, 0))); + + var point = font.ReadGlyph(2)[0][2]; + + Assert.Equal(-800, point.X); + Assert.Equal(700, point.Y); + } + + [Fact] + public void ReadsSignedByteCompositeOffsets() + { + var glyph = new byte[16]; + Write16(glyph, 0, -1); Write16(glyph, 10, 2); Write16(glyph, 12, 1); + glyph[14] = unchecked((byte)-10); glyph[15] = unchecked((byte)-20); + var font = new TrueTypeGlyphReader(CreateFont(Box(), glyph)); + + var point = font.ReadGlyph(2)[0][0]; + + Assert.Equal(-10, point.X); + Assert.Equal(-20, point.Y); + } + + [Fact] + public void LooksUpIndirectFormatFourGlyphsAndAppliesDelta() + { + var cmap = new byte[36]; + Write16(cmap, 0, 4); Write16(cmap, 2, cmap.Length); Write16(cmap, 6, 4); + Write16(cmap, 14, 66); Write16(cmap, 16, 0xFFFF); + Write16(cmap, 20, 65); Write16(cmap, 22, 0xFFFF); + Write16(cmap, 24, 1); Write16(cmap, 26, 1); Write16(cmap, 28, 4); + Write16(cmap, 32, 1); Write16(cmap, 34, 2); + var font = new TrueTypeGlyphReader(ReplaceCmap(CreateFont(Box(), Box(), Box()), cmap, 1)); + + Assert.Equal(2, font.GlyphForCharacter('A')); + Assert.Equal(3, font.GlyphForCharacter('B')); + Assert.Throws(() => font.GlyphForCharacter('@')); + } + + [Fact] + public void LooksUpFormatTwelveGroupsWithoutFillingCharacterGaps() + { + var cmap = new byte[40]; + Write16(cmap, 0, 12); Write32(cmap, 4, (uint)cmap.Length); Write32(cmap, 12, 2); + Write32(cmap, 16, 65); Write32(cmap, 20, 65); Write32(cmap, 24, 1); + Write32(cmap, 28, 67); Write32(cmap, 32, 67); Write32(cmap, 36, 2); + var font = new TrueTypeGlyphReader(ReplaceCmap(CreateFont(Box(), Box()), cmap, 10)); + + Assert.Equal(1, font.GlyphForCharacter('A')); + Assert.Equal(2, font.GlyphForCharacter('C')); + Assert.Throws(() => font.GlyphForCharacter('B')); + } + + [Fact] + public void ReadsShortLocaOffsetsAndReusesFinalLongHorizontalMetric() + { + var bytes = CreateFont(Box(), Box()); + var head = TableOffset(bytes, "head"); + var loca = TableOffset(bytes, "loca"); + Write16(bytes, head + 50, 0); + var glyphSize = Box().Length; + Write16(bytes, loca, 0); Write16(bytes, loca + 2, 0); + Write16(bytes, loca + 4, glyphSize / 2); Write16(bytes, loca + 6, glyphSize); + Write16(bytes, TableOffset(bytes, "hhea") + 34, 1); + var font = new TrueTypeGlyphReader(bytes); + + Assert.Equal(600, font.Advance(2)); + Assert.Equal(2, font.ReadGlyph(2).Count); + } + + [Theory] + [InlineData("cycle")] + [InlineData("glyph-index")] + [InlineData("truncated")] + [InlineData("repeat")] + [InlineData("transform-flags")] + [InlineData("location")] + [InlineData("table-range")] + public void RejectsMalformedGlyphsAndFontRanges(string defect) + { + var glyph = Box(); + if (defect == "cycle") glyph = Composite(3, 1, 0, 0); + if (defect == "glyph-index") glyph = Composite(3, 300, 0, 0); + if (defect == "truncated") Array.Resize(ref glyph, 16); + if (defect == "repeat") { glyph[16] = 9; glyph[17] = 255; } + if (defect == "transform-flags") glyph = Composite(0x4B, 1, 0, 0); + var bytes = CreateFont(glyph); + if (defect == "location") Write32(bytes, TableOffset(bytes, "loca") + 4, uint.MaxValue); + if (defect == "table-range") Write32(bytes, 20, uint.MaxValue); + + Assert.Throws(() => new TrueTypeGlyphReader(bytes).ReadGlyph(1)); + } + + [Theory] + [InlineData(1)] + public void RejectsPointAttachedComposites(ushort flags) + { + var font = new TrueTypeGlyphReader(CreateFont(Box(), Composite(flags, 1, 0, 0))); + + Assert.Throws(() => font.ReadGlyph(2)); + } + + [Fact] + public void GridRoundingDoesNotRoundUnhintedCompositeDesignOffsets() + { + var font = new TrueTypeGlyphReader(CreateFont(Box(), Composite(0x80F, 1, 1, 1, 0x2000))); + var contours = font.ReadGlyph(2); + + Assert.Equal(0.5, contours[0][0].X); + Assert.Equal(0.5, contours[0][0].Y); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RejectsInheritedCompositeMetricsThatDifferFromTheParent(bool bearing) + { + var bytes = CreateFont(Box(), Composite(0x203, 1, 0, 0)); + Write16(bytes, TableOffset(bytes, "hmtx") + 8 + (bearing ? 2 : 0), 100); + var font = new TrueTypeGlyphReader(bytes); + + Assert.Throws(() => font.ReadGlyph(2)); + } + + internal static byte[] Box() => Simple( + new[] { (0, 0, true), (0, 700, true), (500, 700, true), (500, 0, true) }, + new[] { (100, 100, true), (400, 100, true), (400, 600, true), (100, 600, true) }); + + internal static byte[] Simple(params (int X, int Y, bool OnCurve)[][] contours) + { + var points = contours.SelectMany(contour => contour).ToArray(); + var size = 12 + contours.Length * 2 + points.Length * 5; + var bytes = new byte[(size + 1) & ~1]; + Write16(bytes, 0, contours.Length); + var last = -1; + for (var index = 0; index < contours.Length; index++) + { + last += contours[index].Length; + Write16(bytes, 10 + index * 2, last); + } + var flagsOffset = 12 + contours.Length * 2; + var previousX = 0; + var previousY = 0; + for (var index = 0; index < points.Length; index++) + { + var point = points[index]; + bytes[flagsOffset + index] = point.OnCurve ? (byte)1 : (byte)0; + Write16(bytes, flagsOffset + points.Length + index * 2, point.X - previousX); + Write16(bytes, flagsOffset + points.Length * 3 + index * 2, point.Y - previousY); + previousX = point.X; previousY = point.Y; + } + return bytes; + } + + internal static byte[] Composite(ushort flags, ushort glyph, short x, short y, params short[] transform) + { + var bytes = new byte[18 + transform.Length * 2]; + Write16(bytes, 0, -1); + Write16(bytes, 10, flags); + Write16(bytes, 12, glyph); + Write16(bytes, 14, x); + Write16(bytes, 16, y); + for (var index = 0; index < transform.Length; index++) Write16(bytes, 18 + index * 2, transform[index]); + return bytes; + } + + internal static byte[] CreateFont(params byte[][] glyphs) + { + var count = glyphs.Length + 1; + var head = new byte[54]; + Write16(head, 18, 1000); + Write16(head, 50, 1); + var hhea = new byte[36]; + Write16(hhea, 34, count); + var os2 = new byte[78]; + Write16(os2, 2, 600); + Write16(os2, 74, 1000); + Write16(os2, 76, 200); + var hmtx = new byte[count * 4]; + for (var index = 0; index < count; index++) Write16(hmtx, index * 4, 600); + var maxp = new byte[6]; + Write32(maxp, 0, 0x10000); + Write16(maxp, 4, count); + var loca = new byte[(count + 1) * 4]; + var offset = 0; + for (var index = 0; index < glyphs.Length; index++) + { + offset += glyphs[index].Length; + Write32(loca, (index + 2) * 4, (uint)offset); + } + var cmap = new byte[44]; + Write16(cmap, 2, 1); + Write16(cmap, 4, 3); + Write16(cmap, 6, 1); + Write32(cmap, 8, 12); + Write16(cmap, 12, 4); + Write16(cmap, 14, 32); + Write16(cmap, 18, 4); + Write16(cmap, 26, 0x40 + glyphs.Length); + Write16(cmap, 28, 0xFFFF); + Write16(cmap, 32, 0x41); + Write16(cmap, 34, 0xFFFF); + Write16(cmap, 36, -64); + Write16(cmap, 38, 1); + var tables = new Dictionary + { + ["head"] = head, ["hhea"] = hhea, ["hmtx"] = hmtx, ["maxp"] = maxp, + ["loca"] = loca, ["glyf"] = glyphs.SelectMany(glyph => glyph).ToArray(), + ["OS/2"] = os2, ["cmap"] = cmap + }; + var dataOffset = 12 + tables.Count * 16; + var font = new byte[dataOffset + tables.Values.Sum(table => (table.Length + 3) & ~3)]; + Write32(font, 0, 0x10000); + Write16(font, 4, tables.Count); + var entry = 12; + foreach (var table in tables) + { + System.Text.Encoding.ASCII.GetBytes(table.Key).CopyTo(font, entry); + Write32(font, entry + 8, (uint)dataOffset); + Write32(font, entry + 12, (uint)table.Value.Length); + table.Value.CopyTo(font, dataOffset); + dataOffset += (table.Value.Length + 3) & ~3; + entry += 16; + } + return font; + } + + internal static int TableOffset(byte[] font, string tag) + { + var count = BinaryPrimitives.ReadUInt16BigEndian(font.AsSpan(4)); + for (var index = 0; index < count; index++) + if (System.Text.Encoding.ASCII.GetString(font, 12 + index * 16, 4) == tag) + return (int)BinaryPrimitives.ReadUInt32BigEndian(font.AsSpan(20 + index * 16)); + throw new InvalidOperationException("Synthetic font table was not found."); + } + + private static byte[] ReplaceCmap(byte[] font, byte[] subtable, int encoding) + { + var offset = TableOffset(font, "cmap"); + Array.Resize(ref font, offset + 12 + subtable.Length); + font.AsSpan(offset).Clear(); + Write16(font, offset + 2, 1); Write16(font, offset + 4, 3); + Write16(font, offset + 6, encoding); Write32(font, offset + 8, 12); + subtable.CopyTo(font, offset + 12); + var count = BinaryPrimitives.ReadUInt16BigEndian(font.AsSpan(4)); + for (var index = 0; index < count; index++) + if (System.Text.Encoding.ASCII.GetString(font, 12 + index * 16, 4) == "cmap") + Write32(font, 24 + index * 16, (uint)(12 + subtable.Length)); + return font; + } + + internal static void Write16(byte[] bytes, int offset, int value) => + BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(offset), unchecked((ushort)value)); + + internal static void Write32(byte[] bytes, int offset, uint value) => + BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(offset), value); +} diff --git a/tests/MiniPdf.Tests/TrueTypeNativeGlyphTests.cs b/tests/MiniPdf.Tests/TrueTypeNativeGlyphTests.cs new file mode 100644 index 00000000..1229fecd --- /dev/null +++ b/tests/MiniPdf.Tests/TrueTypeNativeGlyphTests.cs @@ -0,0 +1,209 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; + +namespace MiniSoftware.Tests; + +public sealed class WindowsGlyphTheoryAttribute : TheoryAttribute +{ + public WindowsGlyphTheoryAttribute() + { + if (!OperatingSystem.IsWindows()) Skip = "Native unhinted outline comparisons require Windows GDI."; + else if (!File.Exists(TrueTypeNativeGlyphTests.FontPath)) Skip = "Native outline comparisons require installed Arial."; + } +} + +public class TrueTypeNativeGlyphTests +{ + internal static string FontPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf"); + + [WindowsGlyphTheory] + [InlineData('A')] + [InlineData('B')] + [InlineData('O')] + [InlineData('S')] + [InlineData('g')] + public void DecodedContoursMatchNativeUnhintedOutlines(char character) + { + var font = new TrueTypeGlyphReader(File.ReadAllBytes(FontPath)); + var glyph = font.GlyphForCharacter(character); + var actual = Segments(font.ReadGlyph(glyph)); + var native = NativeOutline(character, font.UnitsPerEm, out var advance); + var expected = Segments(native); + + Assert.NotEmpty(expected); + Assert.Equal(advance, font.Advance(glyph)); + Assert.True(actual.SetEquals(expected), + $"Unhinted {character} outline differs: {actual.Count} decoded segments, {expected.Count} native segments; " + + $"first unexpected {actual.Except(expected).FirstOrDefault()}, first missing {expected.Except(actual).FirstOrDefault()}."); + } + + [WindowsEmfTheory] + [InlineData('ồ')] + [InlineData('ề')] + [InlineData('ẫ')] + [InlineData('ủ')] + public void SegoeVietnameseCompositesMatchNativeUnhintedOutlines(char character) + { + var bytes = File.ReadAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "segoeui.ttf")); + var font = new TrueTypeGlyphReader(bytes); + var glyph = font.GlyphForCharacter(character); + var native = NativeOutline(character, font.UnitsPerEm, out var advance, face: "Segoe UI"); + + Assert.Equal(advance, font.Advance(glyph)); + Assert.True(Segments(font.ReadGlyph(glyph)).SetEquals(Segments(native)), "Vietnamese composite outlines must preserve their shared horizontal origin."); + } + + [WindowsGlyphTheory] + [InlineData('A')] + [InlineData('g')] + public void PositiveCellHeightsMatchNativeUnhintedFontSizing(char character) + { + var bytes = File.ReadAllBytes(FontPath); + var font = new TrueTypeGlyphReader(bytes); + var offset = TrueTypeGlyphReaderTests.TableOffset(bytes, "OS/2"); + var cellHeight = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(offset + 74)) + + BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(offset + 76)); + var actual = Segments(font.ReadGlyph(font.GlyphForCharacter(character))); + var native = NativeOutline(character, font.UnitsPerEm, out var advance, cellHeight); + + Assert.True(actual.SetEquals(Segments(native)), "Positive cell height must select the matching em size."); + Assert.Equal(font.Advance(font.GlyphForCharacter(character)), advance); + } + + [WindowsGlyphTheory] + [InlineData(1, false)] + [InlineData(2, false)] + [InlineData(2, true)] + public void RequestedAverageWidthsMatchNativeHorizontalScaling(int factor, bool positiveHeight) + { + var bytes = File.ReadAllBytes(FontPath); + var font = new TrueTypeGlyphReader(bytes); + var offset = TrueTypeGlyphReaderTests.TableOffset(bytes, "OS/2"); + var average = BinaryPrimitives.ReadInt16BigEndian(bytes.AsSpan(offset + 2)); + var glyph = font.GlyphForCharacter('A'); + var expected = font.ReadGlyph(glyph).Select(contour => contour.Select(point => + new TrueTypeGlyphReader.Point(point.X * factor, point.Y, point.OnCurve)).ToList()).ToList(); + var cellHeight = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(offset + 74)) + + BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(offset + 76)); + var native = NativeOutline('A', font.UnitsPerEm, out var advance, + cellHeight: positiveHeight ? cellHeight : null, width: average * factor); + + Assert.True(Segments(expected).SetEquals(Segments(native)), "Requested width must scale only the horizontal outline."); + Assert.Equal(font.Advance(glyph) * factor, advance); + } + + private static HashSet<(long, long, long, long, long, long)> Segments(List> contours) + { + var result = new HashSet<(long, long, long, long, long, long)>(); + foreach (var contour in contours) + { + var first = contour[0]; + var last = contour[contour.Count - 1]; + var start = first.OnCurve ? (first.X, first.Y) : last.OnCurve ? (last.X, last.Y) : Mid(last, first); + var current = start; + for (var index = first.OnCurve ? 1 : 0; index < contour.Count;) + { + var point = contour[index]; + if (point.OnCurve) { Line((point.X, point.Y)); index++; } + else + { + var next = contour[(index + 1) % contour.Count]; + var end = next.OnCurve ? (next.X, next.Y) : Mid(point, next); + Add(current, (point.X, point.Y), end); + current = end; + index += next.OnCurve ? 2 : 1; + } + } + Line(start); + + void Line((double X, double Y) end) + { + if (current != end) Add(current, ((current.Item1 + end.X) / 2, (current.Item2 + end.Y) / 2), end); + current = end; + } + void Add((double X, double Y) a, (double X, double Y) b, (double X, double Y) c) => + result.Add((Q(a.X), Q(a.Y), Q(b.X), Q(b.Y), Q(c.X), Q(c.Y))); + } + return result; + + static long Q(double value) => (long)Math.Round(value * 128); + static (double, double) Mid(TrueTypeGlyphReader.Point a, TrueTypeGlyphReader.Point b) => ((a.X + b.X) / 2, (a.Y + b.Y) / 2); + } + + private static List> NativeOutline(char character, int unitsPerEm, out int advance, + int? cellHeight = null, int width = 0, string face = "Arial") + { + var dc = CreateCompatibleDC(IntPtr.Zero); + Assert.NotEqual(IntPtr.Zero, dc); + var font = IntPtr.Zero; + var previous = IntPtr.Zero; + try + { + font = CreateFontW(cellHeight ?? -unitsPerEm, width, 0, 0, 400, 0, 0, 0, 1, 0, 0, 3, 0, face); + Assert.NotEqual(IntPtr.Zero, font); + previous = SelectObject(dc, font); + Assert.NotEqual(IntPtr.Zero, previous); + var transform = new Matrix { M11 = 65536, M22 = 65536 }; + const uint unhintedNative = 0x102; + var length = GetGlyphOutlineW(dc, character, unhintedNative, out var metrics, 0, null, ref transform); + Assert.NotEqual(uint.MaxValue, length); + var bytes = new byte[length]; + Assert.Equal(length, GetGlyphOutlineW(dc, character, unhintedNative, out metrics, length, bytes, ref transform)); + advance = metrics.AdvanceX; + var contours = new List>(); + for (var offset = 0; offset < bytes.Length;) + { + var end = checked(offset + (int)U32(offset)); + Assert.InRange(end, offset + 16, bytes.Length); + Assert.Equal(24u, U32(offset + 4)); + var contour = new List { Point(offset + 8, true) }; + for (var curve = offset + 16; curve < end;) + { + var type = U16(curve); + var count = U16(curve + 2); + Assert.True(type == 1 || type == 2, $"Unexpected native quadratic outline primitive {type}."); + Assert.True(count >= (type == 1 ? 1 : 2)); + Assert.True(curve + 4 + count * 8 <= end); + for (var index = 0; index < count; index++) + contour.Add(Point(curve + 4 + index * 8, type == 1 || index == count - 1)); + curve += 4 + count * 8; + } + contours.Add(contour); + offset = end; + } + return contours; + + ushort U16(int offset) => BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(offset)); + uint U32(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(offset)); + TrueTypeGlyphReader.Point Point(int offset, bool onCurve) => new( + BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(offset)) / 65536d, + BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(offset + 4)) / 65536d, onCurve); + } + finally + { + if (previous != IntPtr.Zero) SelectObject(dc, previous); + if (font != IntPtr.Zero) DeleteObject(font); + DeleteDC(dc); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct Matrix { internal int M11, M12, M21, M22; } + [StructLayout(LayoutKind.Sequential)] + private struct Metrics { internal uint Width, Height; internal int OriginX, OriginY; internal short AdvanceX, AdvanceY; } + + [DllImport("gdi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern IntPtr CreateFontW(int height, int width, int escapement, int orientation, int weight, + uint italic, uint underline, uint strikeout, uint charset, uint precision, uint clip, uint quality, uint pitch, string face); + [DllImport("gdi32.dll", ExactSpelling = true)] + private static extern uint GetGlyphOutlineW(IntPtr dc, uint character, uint format, + out Metrics metrics, uint length, [Out] byte[]? buffer, ref Matrix transform); + [DllImport("gdi32.dll")] + private static extern IntPtr CreateCompatibleDC(IntPtr dc); + [DllImport("gdi32.dll")] + private static extern bool DeleteDC(IntPtr dc); + [DllImport("gdi32.dll")] + private static extern IntPtr SelectObject(IntPtr dc, IntPtr value); + [DllImport("gdi32.dll")] + private static extern bool DeleteObject(IntPtr value); +} diff --git a/tests/MiniPdf.Tests/WmfVectorAdapterTests.cs b/tests/MiniPdf.Tests/WmfVectorAdapterTests.cs new file mode 100644 index 00000000..b3e65369 --- /dev/null +++ b/tests/MiniPdf.Tests/WmfVectorAdapterTests.cs @@ -0,0 +1,105 @@ +using System.Buffers.Binary; +using System.Runtime.InteropServices; + +namespace MiniSoftware.Tests; + +public class WmfVectorAdapterTests +{ + [Fact] + public void ProductionPortableConversionRendersPlaceableWmf() + { + var png = DocxReader.TryConvertMetafileToPngPortable(CreateWmf(), 1, 1, rasterHeight: 32); + Assert.NotNull(png); + var pixels = EmfVectorRendererTests.Decode(png, 32, 32); + Assert.Equal(new byte[] { 255, 0, 0, 255 }, pixels.AsSpan((8 * 32 + 8) * 4, 4).ToArray()); + Assert.Equal(new byte[] { 0, 0, 255, 255 }, pixels.AsSpan((27 * 32 + 27) * 4, 4).ToArray()); + } + + [WindowsEmfTheory] + [InlineData(32)] + [InlineData(64)] + public void PlaceableVectorWmfMatchesNativeConversion(int size) + { + var wmf = CreateWmf(); + var emf = WmfVectorAdapter.Convert(wmf, size, size); + var actual = EmfVectorRendererTests.Decode(EmfVectorRenderer.Render(emf, size, size), size, size); + var dc = CreateCompatibleDC(IntPtr.Zero); + var native = IntPtr.Zero; + try + { + Assert.NotEqual(IntPtr.Zero, dc); + var picture = new MetafilePicture { MapMode = 8, Width = 847, Height = 847 }; + var bits = wmf.AsSpan(22).ToArray(); + native = SetWinMetaFileBits((uint)bits.Length, bits, dc, ref picture); + Assert.NotEqual(IntPtr.Zero, native); + var length = GetEnhMetaFileBits(native, 0, null); + Assert.NotEqual(0u, length); + var converted = new byte[length]; + Assert.Equal(length, GetEnhMetaFileBits(native, length, converted)); + var expected = EmfNativePlaybackTests.PlayNative(converted, size, size); + EmfNativePlaybackTests.AssertPixelsEqual(actual, expected, size, size); + } + finally + { + if (native != IntPtr.Zero) DeleteEnhMetaFile(native); + if (dc != IntPtr.Zero) DeleteDC(dc); + } + } + + [Theory] + [InlineData("checksum")] + [InlineData("length")] + [InlineData("record")] + public void MalformedWmfDoesNotReturnAnImage(string defect) + { + var data = CreateWmf(); + if (defect == "checksum") data[20] ^= 1; + if (defect == "length") BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(28), uint.MaxValue); + if (defect == "record") BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(40), uint.MaxValue); + Assert.Throws(() => WmfVectorAdapter.Convert(data, 32, 32)); + } + + private static byte[] CreateWmf() + { + byte[] Record(ushort function, params ushort[] parameters) + { + var record = new byte[6 + parameters.Length * 2]; + BinaryPrimitives.WriteUInt32LittleEndian(record, (uint)record.Length / 2); + BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(4), function); + for (var index = 0; index < parameters.Length; index++) + BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(6 + index * 2), parameters[index]); + return record; + } + var records = new[] { + Record(0x020B, 0, 0), Record(0x020C, 32, 32), + Record(0x02FC, 0, 255, 0, 0), Record(0x012D, 0), + Record(0x02FA, 5, 0, 0, 0, 0), Record(0x012D, 1), Record(0x041B, 24, 24, 4, 4), + Record(0x012D, 0x8005), Record(0x012D, 0x8008), Record(0x01F0, 0), Record(0x01F0, 1), + Record(0x02FC, 0, 0, 255, 0), Record(0x012D, 0), Record(0x041B, 30, 30, 26, 26), Record(0) }; + var result = new byte[40 + records.Sum(record => record.Length)]; + BinaryPrimitives.WriteUInt32LittleEndian(result, 0x9AC6CDD7); + BinaryPrimitives.WriteInt16LittleEndian(result.AsSpan(10), 32); + BinaryPrimitives.WriteInt16LittleEndian(result.AsSpan(12), 32); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(14), 96); + ushort checksum = 0; + for (var index = 0; index < 20; index += 2) checksum ^= BinaryPrimitives.ReadUInt16LittleEndian(result.AsSpan(index)); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(20), checksum); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(22), 1); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(24), 9); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(26), 0x300); + BinaryPrimitives.WriteUInt32LittleEndian(result.AsSpan(28), (uint)(result.Length - 22) / 2); + BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(32), 2); + BinaryPrimitives.WriteUInt32LittleEndian(result.AsSpan(34), (uint)records.Max(record => record.Length) / 2); + var offset = 40; + foreach (var record in records) { record.CopyTo(result, offset); offset += record.Length; } + return result; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MetafilePicture { internal int MapMode, Width, Height; internal IntPtr Metafile; } + [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr dc); + [DllImport("gdi32.dll")] private static extern bool DeleteDC(IntPtr dc); + [DllImport("gdi32.dll")] private static extern bool DeleteEnhMetaFile(IntPtr metafile); + [DllImport("gdi32.dll")] private static extern IntPtr SetWinMetaFileBits(uint size, byte[] data, IntPtr dc, ref MetafilePicture picture); + [DllImport("gdi32.dll")] private static extern uint GetEnhMetaFileBits(IntPtr metafile, uint size, [Out] byte[]? data); +} diff --git a/tests/MiniPdf.Tests/XlsxIssueFileTests.cs b/tests/MiniPdf.Tests/XlsxIssueFileTests.cs index 781163cf..9e76bcc5 100644 --- a/tests/MiniPdf.Tests/XlsxIssueFileTests.cs +++ b/tests/MiniPdf.Tests/XlsxIssueFileTests.cs @@ -64,21 +64,22 @@ public void Issue202609031340_PreservesLayoutAndOlePreviews() private static void AssertHasDrawingContent(byte[] png) { - using var stream = new MemoryStream(png, writable: false); - using var bitmap = new global::MiniSoftware.Drawing.Imaging.Bitmap(stream); + Assert.True(PdfWriter.TryDecodePngToRgb(png, out var width, out var height, out var rgb, out var alpha)); var visiblePixels = 0; var hasRed = false; var hasBlue = false; - for (var row = 0; row < bitmap.Height; row += 2) + for (var row = 0; row < height; row += 2) { - for (var column = 0; column < bitmap.Width; column += 2) + for (var column = 0; column < width; column += 2) { - var color = bitmap.GetPixel(column, row); - if (color.A > 0 && (color.R < 250 || color.G < 250 || color.B < 250)) + var position = row * width + column; + var a = alpha == null ? (byte)255 : alpha[position]; + var r = rgb[position * 3]; var g = rgb[position * 3 + 1]; var b = rgb[position * 3 + 2]; + if (a > 0 && (r < 250 || g < 250 || b < 250)) visiblePixels++; - if (color.A > 0 && color.R > color.G * 1.5 && color.R > color.B * 1.5) + if (a > 0 && r > g * 1.5 && r > b * 1.5) hasRed = true; - if (color.A > 0 && color.B > color.R * 1.5 && color.B > color.G * 1.5) + if (a > 0 && b > r * 1.5 && b > g * 1.5) hasBlue = true; } } From bbfb0924a37c3a8f5d955a187a871726320c7c8b Mon Sep 17 00:00:00 2001 From: Wei Lin Date: Thu, 19 Nov 2026 17:16:54 +0800 Subject: [PATCH 2/2] Preserve CJK metafile font fallback on Linux Reuse the existing CJK font selection policy and report substitution rather than losing OLE previews when an exact family is unavailable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/MiniPdf/PdfWriter.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/MiniPdf/PdfWriter.cs b/src/MiniPdf/PdfWriter.cs index 3e8daf48..ffe5c3ce 100644 --- a/src/MiniPdf/PdfWriter.cs +++ b/src/MiniPdf/PdfWriter.cs @@ -2691,8 +2691,19 @@ bool HasRequestedStyle(byte[] data) var styled = FindExactBytes(fontName + suffix); if (styled != null && HasRequestedStyle(styled)) return styled; } - var regular = FindExactBytes(fontName) - ?? throw new NotSupportedException($"Metafile font '{fontName}' is not available; no family substitution was made."); + var regular = FindExactBytes(fontName); + if (regular == null && CjkFontFileMap.ContainsKey(fontName)) + { + var fallbackPath = FindSystemFontByPreferredName(fontName); + if (fallbackPath != null) + { + regular = LoadTtfFontFromBytes(File.ReadAllBytes(fallbackPath)); + var (fallbackFamily, _) = ReadFontNames(regular); + System.Diagnostics.Trace.TraceWarning("Metafile font '{0}' is unavailable; using existing CJK fallback '{1}'.", fontName, fallbackFamily); + } + } + if (regular == null) + throw new NotSupportedException($"Metafile font '{fontName}' is not available; no family substitution was made."); if (HasRequestedStyle(regular)) return regular; var (family, _) = ReadFontNames(regular); if (!string.IsNullOrEmpty(family))