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