diff --git a/src/EPPlus.Export.Pdf.Tests/PdfParallelExportTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfParallelExportTests.cs new file mode 100644 index 0000000000..d45e9ba89d --- /dev/null +++ b/src/EPPlus.Export.Pdf.Tests/PdfParallelExportTests.cs @@ -0,0 +1,94 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.Export.Pdf.Tests; +using OfficeOpenXml; +using OfficeOpenXml.Export.PdfExport; +using OfficeOpenXml.Export.PdfExport.Settings; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace EPPlusTest.PDF +{ + /// + /// Concurrent exports must not share shaping state: every export of the same workbook + /// should produce the same bytes. + /// + [TestClass] + public class PdfParallelExportTests : PdfTestBase + { + private const int ExportCount = 8; + private const int Rounds = 3; + + // PDFTest.xlsx has &D and &T in a header, and the document info has creation and + // modification dates. Pinning the export time keeps the output independent of the clock. + internal static readonly DateTime FixedExportTime = new DateTime(2026, 1, 2, 3, 4, 5); + + [TestMethod] + public void ParallelExportsOfSameWorkbookProduceIdenticalPdfTest() + { + var reference = Export(); + + for (int round = 0; round < Rounds; round++) + { + var results = new byte[ExportCount][]; + using (var start = new Barrier(ExportCount)) + { + var tasks = new Task[ExportCount]; + for (int i = 0; i < ExportCount; i++) + { + int index = i; + tasks[i] = Task.Factory.StartNew(() => + { + start.SignalAndWait(); + results[index] = Export(); + }, TaskCreationOptions.LongRunning); + } + Task.WaitAll(tasks); + } + + for (int i = 0; i < ExportCount; i++) + { + var actual = results[i]; + if (reference.AsSpan().SequenceEqual(actual)) continue; + Assert.Fail($"Round {round}, export {i}: PDF differs from the sequential export " + + $"(length {actual.Length} vs {reference.Length}). {DescribeFirstDifference(reference, actual)}"); + } + } + } + + private static byte[] Export() + { + // Each export uses its own package: a package is not meant to be shared between threads. + using var p = OpenTemplatePackage("PDFTest.xlsx"); + var wb = p.Workbook; + using var ms = new MemoryStream(); + // Same settings ExcelWorkbook.SaveAsPdf builds, with the export time pinned. + var settings = GetPdfSettings.BuildBase(wb, wb.Worksheets[wb.View.ActiveTab].PrinterSettings, null); + settings.ExportTime = FixedExportTime; + new EPPlusToPdfWriter(settings, wb).Save(ms); + return ms.ToArray(); + } + + private static string DescribeFirstDifference(byte[] expected, byte[] actual) + { + int n = Math.Min(expected.Length, actual.Length); + int at = 0; + while (at < n && expected[at] == actual[at]) at++; + int from = Math.Max(0, at - 40); + var latin1 = Encoding.GetEncoding("ISO-8859-1"); + string Excerpt(byte[] b) => latin1.GetString(b, from, Math.Min(120, b.Length - from)).Replace("\n", "\\n"); + return $"First difference at offset {at}. Expected: '{Excerpt(expected)}' Actual: '{Excerpt(actual)}'"; + } + } +} diff --git a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs index 062b7495d1..e4f276e936 100644 --- a/src/EPPlus.Export.Pdf.Tests/PdfTests.cs +++ b/src/EPPlus.Export.Pdf.Tests/PdfTests.cs @@ -364,10 +364,19 @@ public void FileAndStreamProduceSamePdfLengthTest() string tempFile = Path.GetTempFileName(); try { - wb.SaveAsPdf(tempFile); + // Builds the same settings as ExcelWorkbook.SaveAsPdf, with the export time pinned: + // PDFTest.xlsx has &D and &T in a header, so two exports in different minutes + // produce different content and can differ in length. + PdfRenderSettings Settings() + { + var s = GetPdfSettings.BuildBase(wb, wb.Worksheets[wb.View.ActiveTab].PrinterSettings, null); + s.ExportTime = PdfParallelExportTests.FixedExportTime; + return s; + } + new EPPlusToPdfWriter(Settings(), wb).Save(tempFile); long fileLength = new FileInfo(tempFile).Length; using var ms = new MemoryStream(); - wb.SaveAsPdf(ms); + new EPPlusToPdfWriter(Settings(), wb).Save(ms); Assert.AreEqual(fileLength, ms.Length, "Stream output length differs from file output length."); } finally diff --git a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs index 5150d8d7cb..fd37acfeed 100644 --- a/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs +++ b/src/EPPlus.Export.Pdf/DocumentObjects/PdfInfoObject.cs @@ -34,6 +34,7 @@ internal class PdfInfoObject : PdfObject internal string LicenseType; internal string LicenseHolder; internal string Author; + internal DateTime ExportTime; public PdfInfoObject(int objectNumber, PdfDocumentSettings documentSettings, int version = 0) : base(objectNumber, version) { @@ -41,11 +42,12 @@ public PdfInfoObject(int objectNumber, PdfDocumentSettings documentSettings, int Author = documentSettings.Author; LicenseType = documentSettings.LicenseType; LicenseHolder = documentSettings.LicenseHolder; + ExportTime = documentSettings.ExportTime == default(DateTime) ? DateTime.Now : documentSettings.ExportTime; } private string Body() { - DateTime now = DateTime.Now; + DateTime now = ExportTime; TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(now); string sign = offset < TimeSpan.Zero ? "-" : "+"; offset = offset.Duration(); diff --git a/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs b/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs index cd160c6424..b4a20a1c84 100644 --- a/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs +++ b/src/EPPlus.Export.Pdf/Resources/PdfDictionaries.cs @@ -11,11 +11,13 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 08/17/2026 EPPlus Software AB Canonical FontKey + resolve cache 08/20/2026 EPPlus Software AB Document-wide subsetting via DocumentFontSubsetBuilder + 12/04/2026 EPPlus Software AB One unsubset font provider per requested font and export *************************************************************************************************/ using EPPlus.Export.Pdf.Settings; using EPPlus.Fonts.OpenType; using EPPlus.Fonts.OpenType.Integration; using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.TextShaping; using OfficeOpenXml.Interfaces.Fonts; using System.Collections.Generic; using System.Linq; @@ -29,8 +31,13 @@ internal class PdfDictionaries internal readonly Dictionary Shadings = new Dictionary(); internal readonly Dictionary Images = new Dictionary(); internal Dictionary ShapedProviders = new Dictionary(); + // Shapers and layout engines are reused within one export only. TextShaper keeps + // per-call state and is not thread-safe, so it must not be shared between exports. + private readonly Dictionary _shapers = new Dictionary(); + private readonly Dictionary _layoutEngines = new Dictionary(); private DocumentFontSubsetBuilder _subsetBuilder; private readonly Dictionary _requestedToKey = new Dictionary(); + private readonly Dictionary _unsubsetProviders = new Dictionary(); private static string BuildRequestCacheKey(string family, FontSubFamily subFamily) { @@ -52,6 +59,54 @@ internal FontKey ResolveFontKey(PdfRenderSettings pageSettings, string family, F return key; } + /// + /// Returns a provider for the full (not subset) font, for text shaped before the subsets + /// exist. One provider per requested font and export: the shaper and layout engine are + /// cached per provider, so a new provider per text fragment would build a new shaper, with + /// its kerning data, for every fragment. + /// + internal IFontProvider GetUnsubsetProvider(PdfRenderSettings pageSettings, string family, FontSubFamily subFamily) + { + var cacheKey = BuildRequestCacheKey(family, subFamily); + IFontProvider provider; + if (!_unsubsetProviders.TryGetValue(cacheKey, out provider)) + { + var font = pageSettings.FontEngine.LoadFont(family, subFamily); + provider = new DefaultFontProvider(pageSettings.FontEngine, font); + _unsubsetProviders[cacheKey] = provider; + } + return provider; + } + + /// + /// Returns the shaper for in this export, creating it on first use. + /// + internal TextShaper GetShaper(IFontProvider provider) + { + TextShaper shaper; + if (!_shapers.TryGetValue(provider, out shaper)) + { + shaper = new TextShaper(provider); + _shapers[provider] = shaper; + } + return shaper; + } + + /// + /// Returns the layout engine for in this export, built on the + /// export's shaper for that provider. + /// + internal TextLayoutEngine GetLayoutEngine(IFontProvider provider) + { + TextLayoutEngine layoutEngine; + if (!_layoutEngines.TryGetValue(provider, out layoutEngine)) + { + layoutEngine = new TextLayoutEngine(GetShaper(provider)); + _layoutEngines[provider] = layoutEngine; + } + return layoutEngine; + } + public void AddFont(PdfRenderSettings pageSettings, string fontName, FontSubFamily subFamily, string text) { EnsureBuilder(pageSettings); diff --git a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs index 0e42188563..18ff02431e 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfDocumentSettings.cs @@ -11,6 +11,7 @@ Date Author Change 27/11/2025 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using EPPlus.Fonts.OpenType; +using System; using System.Collections.Generic; namespace EPPlus.Export.Pdf.Settings @@ -33,6 +34,7 @@ internal class PdfDocumentSettings internal string BookmarkNamePrefix; internal bool SuppressFormFieldDetection; internal PdfCompressionLevel CompressionLevel; + internal DateTime ExportTime; internal static PdfDocumentSettings From(PdfRenderSettings s) { @@ -54,6 +56,7 @@ internal static PdfDocumentSettings From(PdfRenderSettings s) BookmarkNamePrefix = s.BookmarkNamePrefix, SuppressFormFieldDetection = s.SuppressFormFieldDetection, CompressionLevel = s.CompressionLevel, + ExportTime = s.ExportTime, }; } diff --git a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs index cfe9c574d2..eb72cadf33 100644 --- a/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs +++ b/src/EPPlus.Export.Pdf/Settings/PdfRenderSettings.cs @@ -13,6 +13,7 @@ Date Author Change using EPPlus.Export.Pdf.Settings.PdfPageSizes; using EPPlus.Fonts.OpenType; using OfficeOpenXml.Interfaces.Fonts; +using System; using System.Collections.Generic; namespace EPPlus.Export.Pdf.Settings @@ -27,6 +28,13 @@ internal class PdfRenderSettings internal string LicenseType { get; set; } internal string LicenseHolder { get; set; } + /// + /// The time of this export, taken once when the settings are created. Used for the + /// header/footer date and time codes (&D, &T) and the document's creation and + /// modification dates, so every page and the metadata show the same time. + /// + internal DateTime ExportTime { get; set; } = DateTime.Now; + private OpenTypeFontEngine _fontEngine; /// /// Get the current font engine that is being used by EPPlus. diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/BenchmarkFonts.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/BenchmarkFonts.cs new file mode 100644 index 0000000000..d5e31238a8 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/BenchmarkFonts.cs @@ -0,0 +1,116 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/03/2026 EPPlus Software AB Shared font setup for the benchmarks + *************************************************************************************************/ +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// Font files and sample texts shared by the benchmarks. Every font is read from the + /// benchmark's own Fonts folder, so the results do not depend on what is installed on the + /// machine running them. + /// + internal static class BenchmarkFonts + { + public const string Roboto = "Roboto-Regular.ttf"; + public const string BizUdGothic = "BIZUDGothic-Regular.ttf"; + public const string NotoSansArabic = "NotoSansArabic-Regular.ttf"; + public const string Oi = "Oi-Regular.ttf"; + public const string SourceSans3 = "SourceSans3-Regular.otf"; + public const string EBGaramond = "EBGaramond-Regular.ttf"; + + public static string FontsPath + { + get + { + var path = Path.Combine(AppContext.BaseDirectory, "Fonts"); + if (!Directory.Exists(path)) + throw new DirectoryNotFoundException($"Fonts directory not found: {path}"); + return path; + } + } + + /// + /// An engine that only searches the given folder, or the benchmark's Fonts folder. + /// + public static OpenTypeFontEngine CreateEngine(string? folder = null, Action? configure = null) + { + var path = folder ?? FontsPath; + return new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(path); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + }); + } + + /// + /// Loads a font file directly, bypassing name resolution. + /// + public static OpenTypeFont LoadFile(OpenTypeFontEngine engine, string fileName) + { + return engine.GetFromBytes(File.ReadAllBytes(Path.Combine(FontsPath, fileName))); + } + + /// + /// The characters of the Basic Multilingual Plane that the font maps, in code point + /// order, optionally limited to the given ranges and count. + /// + public static string GetMappedChars(OpenTypeFont font, int maxCount = int.MaxValue, params (int First, int Last)[] ranges) + { + if (ranges.Length == 0) + ranges = new[] { (0x20, 0xFFFF) }; + + var sb = new StringBuilder(); + foreach (var (first, last) in ranges) + { + for (int cp = first; cp <= last && sb.Length < maxCount; cp++) + { + if (cp >= 0xD800 && cp <= 0xDFFF) + continue; + if (font.CmapTable.TryGetGlyphId((uint)cp, out var glyphId) && glyphId != 0) + sb.Append((char)cp); + } + } + return sb.ToString(); + } + + public static string Repeat(string text, int minLength) + { + var sb = new StringBuilder(minLength + text.Length); + while (sb.Length < minLength) + sb.Append(text).Append(' '); + return sb.ToString(); + } + + public const string LatinSample = + "The quick brown fox jumps over the lazy dog. Office efficiency, AVAWAY Tolerance 2026."; + + // Arabic with joining forms, lam-alef ligatures and vowel marks. + public const string ArabicSample = + "مرحبا بالعالم، هذا نص تجريبي لقياس أداء تشكيل النص العربي. " + + "اَلْكِتَابُ مُفِيدٌ جِدًّا وَالْمَكْتَبَةُ لَا تُغْلَقُ أَبَدًا."; + + // Japanese with kanji, hiragana, katakana and full-width punctuation. + public const string JapaneseSample = + "東京都の天気は晴れです。今日は午後三時から会議があります。" + + "データベースのテキストをコンピューターで計測します。"; + + // One spreadsheet cell's worth of mixed scripts: Latin, Japanese, Arabic and emoji. + public const string MixedSample = + "Total 東京支店 1 234,50 € — الإجمالي ٣٤٥ ✅ 🚀 Q3 売上高 مبيعات 👍🏽"; + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/ColdSubsetBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/ColdSubsetBenchmarks.cs new file mode 100644 index 0000000000..4dfaf1eacb --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/ColdSubsetBenchmarks.cs @@ -0,0 +1,90 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Small subsets of newly loaded fonts + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using System; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// What an export does for each embedded font: load the font and make a small subset of the + /// characters a workbook uses. LargeSubsetBenchmarks reuse a loaded font, so the cost of + /// reading glyphs the first time is not part of them. GetFromBytes does not cache, so every + /// invocation reads the font from its bytes. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 2, iterationCount: 5)] + public class ColdSubsetBenchmarks + { + public enum ColdScenario + { + /// Roboto, 1 294 glyphs, short Latin text. + RobotoShortText, + /// EB Garamond, large GSUB, short Latin text. + EBGaramondShortText, + /// BIZ UDGothic, 12 638 glyphs, a few Latin and Japanese characters. + BizUdGothicShortText, + } + + [Params(ColdScenario.RobotoShortText, ColdScenario.EBGaramondShortText, ColdScenario.BizUdGothicShortText)] + public ColdScenario Scenario { get; set; } + + private OpenTypeFontEngine _engine = null!; + private byte[] _bytes = null!; + private string _text = string.Empty; + + [GlobalSetup] + public void Setup() + { + _engine = BenchmarkFonts.CreateEngine(); + string file; + switch (Scenario) + { + case ColdScenario.RobotoShortText: + file = BenchmarkFonts.Roboto; + _text = "Sales 2026, Q1–Q4: 12 345,67 kr"; + break; + case ColdScenario.EBGaramondShortText: + file = BenchmarkFonts.EBGaramond; + _text = "Sales 2026, Q1–Q4: 12 345,67 kr"; + break; + case ColdScenario.BizUdGothicShortText: + file = BenchmarkFonts.BizUdGothic; + _text = "売上 2026 第1四半期 合計"; + break; + default: + throw new ArgumentOutOfRangeException(nameof(Scenario)); + } + _bytes = File.ReadAllBytes(Path.Combine(BenchmarkFonts.FontsPath, file)); + } + + [GlobalCleanup] + public void Cleanup() + { + _engine.Dispose(); + } + + /// Loading alone, for reference. + [Benchmark(Baseline = true)] + public OpenTypeFont Load() + { + return _engine.GetFromBytes(_bytes); + } + + [Benchmark] + public byte[] Load_Subset_Serialize() + { + return _engine.GetFromBytes(_bytes).CreateSubset(_text).Serialize(); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/EPPlus.Fonts.OpenType.Benchmarks.csproj b/src/EPPlus.Fonts.OpenType.Benchmarks/EPPlus.Fonts.OpenType.Benchmarks.csproj index f1a965d0fb..e1d5857336 100644 --- a/src/EPPlus.Fonts.OpenType.Benchmarks/EPPlus.Fonts.OpenType.Benchmarks.csproj +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/EPPlus.Fonts.OpenType.Benchmarks.csproj @@ -19,6 +19,22 @@ PreserveNewest + + PreserveNewest + + + + + + + + + + + + + diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/ExtractCharWidthsBenchmark.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/ExtractCharWidthsBenchmark.cs index f37975e81f..3e1d3a1a16 100644 --- a/src/EPPlus.Fonts.OpenType.Benchmarks/ExtractCharWidthsBenchmark.cs +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/ExtractCharWidthsBenchmark.cs @@ -3,72 +3,80 @@ using EPPlus.Fonts.OpenType.TextShaping; using OfficeOpenXml.Interfaces.Fonts; -[MemoryDiagnoser] -[SimpleJob(warmupCount: 1, iterationCount: 3)] -public class ExtractCharWidthsBenchmark +namespace EPPlus.Fonts.OpenType.Benchmarks { - private ITextShaper _shaper; - private string _shortText; - private string _mediumText; - private string _longText; - private ShapingOptions _options; - - [GlobalSetup] - public void Setup() + [MemoryDiagnoser] + [SimpleJob(warmupCount: 1, iterationCount: 3)] + public class ExtractCharWidthsBenchmark { - var fontFolders = new List { /* your font paths */ }; - var fontEngine = new OpenTypeFontEngine(x => + private OpenTypeFontEngine _fontEngine; + private ITextShaper _shaper; + private string _shortText; + private string _mediumText; + private string _longText; + private ShapingOptions _options; + + [GlobalSetup] + public void Setup() { - x.SearchSystemDirectories = true; - }); - var font = fontEngine.LoadFont("Calibri"); - _shaper = new TextShaper(fontEngine, font); - _options = ShapingOptions.Default; + // Roboto from the benchmark's Fonts folder rather than an installed font, so the + // results do not depend on the machine. + _fontEngine = BenchmarkFonts.CreateEngine(); + var font = _fontEngine.LoadFont("Roboto", FontSubFamily.Regular); + _shaper = new TextShaper(_fontEngine, font); + _options = ShapingOptions.Default; - // Short: typical Excel cell - _shortText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; // 56 chars + // Short: typical Excel cell + _shortText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; // 56 chars - // Medium: single paragraph - _mediumText = new string('x', 550); // Simulate 550 char paragraph + // Medium: single paragraph + _mediumText = new string('x', 550); // Simulate 550 char paragraph - // Long: full 20 paragraphs - _longText = new string('x', 11000); // Simulate 11k chars - } + // Long: full 20 paragraphs + _longText = new string('x', 11000); // Simulate 11k chars + } - [Benchmark] - public double[] ExtractCharWidths_Short() - { - return _shaper.ExtractCharWidths(_shortText, 11f, _options); - } + [GlobalCleanup] + public void Cleanup() + { + _fontEngine.Dispose(); + } - [Benchmark] - public double[] ExtractCharWidths_Medium() - { - return _shaper.ExtractCharWidths(_mediumText, 11f, _options); - } + [Benchmark] + public double[] ExtractCharWidths_Short() + { + return _shaper.ExtractCharWidths(_shortText, 11f, _options); + } - [Benchmark] - public double[] ExtractCharWidths_Long() - { - return _shaper.ExtractCharWidths(_longText, 11f, _options); - } + [Benchmark] + public double[] ExtractCharWidths_Medium() + { + return _shaper.ExtractCharWidths(_mediumText, 11f, _options); + } - // For comparison: what does Shape() alone allocate? - [Benchmark] - public ShapedText ShapeOnly_Short() - { - return _shaper.Shape(_shortText, _options); - } + [Benchmark] + public double[] ExtractCharWidths_Long() + { + return _shaper.ExtractCharWidths(_longText, 11f, _options); + } - [Benchmark] - public ShapedText ShapeOnly_Medium() - { - return _shaper.Shape(_mediumText, _options); - } + // For comparison: what does Shape() alone allocate? + [Benchmark] + public ShapedText ShapeOnly_Short() + { + return _shaper.Shape(_shortText, _options); + } - [Benchmark] - public ShapedText ShapeOnly_Long() - { - return _shaper.Shape(_longText, _options); + [Benchmark] + public ShapedText ShapeOnly_Medium() + { + return _shaper.Shape(_mediumText, _options); + } + + [Benchmark] + public ShapedText ShapeOnly_Long() + { + return _shaper.Shape(_longText, _options); + } } -} \ No newline at end of file +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/FallbackShapingBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/FallbackShapingBenchmarks.cs new file mode 100644 index 0000000000..90e5f15f11 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/FallbackShapingBenchmarks.cs @@ -0,0 +1,116 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/03/2026 EPPlus Software AB Shaping mixed scripts through fallback fonts + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using EPPlus.Fonts.OpenType.TextShaping; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// Shaping text that mixes Latin, Japanese, Arabic and emoji with Roboto as the primary + /// font. Characters Roboto lacks go through the script fallbacks, which point at fonts in + /// the benchmark's Fonts folder, and the built-in emoji font. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 3, iterationCount: 5)] + public class FallbackShapingBenchmarks + { + private OpenTypeFontEngine _warmEngine = null!; + private TextShaper _warmShaper = null!; + private OpenTypeFontEngine? _coldEngine; + private string _longMixed = string.Empty; + private string _longLatin = string.Empty; + + [GlobalSetup] + public void Setup() + { + _longMixed = BenchmarkFonts.Repeat(BenchmarkFonts.MixedSample, 10000); + _longLatin = BenchmarkFonts.Repeat(BenchmarkFonts.LatinSample, 10000); + + _warmEngine = CreateEngine(); + _warmShaper = CreateShaper(_warmEngine); + _warmShaper.Shape(BenchmarkFonts.MixedSample); + + // Make sure the benchmark measures what it claims: the mixed text must reach the + // Japanese, Arabic and emoji fallbacks, not fall back to .notdef. + var used = _warmShaper.GetUsedFonts().Select(f => f.FullName).ToList(); + Console.WriteLine("// Fonts used for the mixed text: " + string.Join(", ", used)); + if (used.Count < 4) + throw new InvalidOperationException("Expected the mixed text to use four fonts, got: " + string.Join(", ", used)); + } + + [GlobalCleanup] + public void Cleanup() + { + _warmEngine.Dispose(); + _coldEngine?.Dispose(); + } + + private static OpenTypeFontEngine CreateEngine() + { + return BenchmarkFonts.CreateEngine(configure: cfg => + { + cfg.SetScriptFallback(UnicodeScript.Han, "BIZ UDGothic"); + cfg.SetScriptFallback(UnicodeScript.Hiragana, "BIZ UDGothic"); + cfg.SetScriptFallback(UnicodeScript.Katakana, "BIZ UDGothic"); + cfg.SetScriptFallback(UnicodeScript.Arabic, "Noto Sans Arabic"); + }); + } + + private static TextShaper CreateShaper(OpenTypeFontEngine engine) + { + return new TextShaper(engine, engine.LoadFont("Roboto", FontSubFamily.Regular)); + } + + [IterationSetup(Target = nameof(Shape_Mixed_ColdEngine))] + public void ColdSetup() + { + _coldEngine?.Dispose(); + _coldEngine = CreateEngine(); + } + + /// + /// Latin-only text through the same shaper, as the reference. + /// + [Benchmark(Baseline = true)] + public ShapedText Shape_LatinOnly_Long() + { + return _warmShaper.Shape(_longLatin); + } + + [Benchmark] + public ShapedText Shape_Mixed_Short() + { + return _warmShaper.Shape(BenchmarkFonts.MixedSample); + } + + [Benchmark] + public ShapedText Shape_Mixed_Long() + { + return _warmShaper.Shape(_longMixed); + } + + /// + /// A new engine shapes the mixed cell text, so the primary font and every fallback font + /// is resolved and parsed again. The process-wide scanner caches are warm after the + /// first iteration; FontDirectoryScanBenchmarks measures those cold. + /// + [Benchmark] + public ShapedText Shape_Mixed_ColdEngine() + { + return CreateShaper(_coldEngine!).Shape(BenchmarkFonts.MixedSample); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/FontDirectoryScanBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/FontDirectoryScanBenchmarks.cs new file mode 100644 index 0000000000..3915f5227c --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/FontDirectoryScanBenchmarks.cs @@ -0,0 +1,151 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/03/2026 EPPlus Software AB First lookup in a folder with many fonts + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.IO; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// The first font lookup of a new engine whose font folder holds many files, as a system + /// font folder does. The folder is filled with renamed copies of the benchmark's fonts. + /// + /// The directory listing and the scanned face info are cached per process, keyed by path. + /// The "FirstInProcess" benchmarks therefore get a folder at a new path every iteration, which + /// is what a process sees the first time it looks for a font. The "NewEngine" benchmarks + /// reuse one folder, so only the engine's own caches are cold. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 2, iterationCount: 5)] + public class FontDirectoryScanBenchmarks + { + [Params(50, 500)] + public int FileCount { get; set; } + + private string _root = string.Empty; + private string _sharedFolder = string.Empty; + private string _iterationFolder = string.Empty; + private int _iteration; + private OpenTypeFontEngine? _coldEngine; + private OpenTypeFontEngine _warmEngine = null!; + + [GlobalSetup] + public void Setup() + { + _root = Path.Combine(Path.GetTempPath(), "EPPlusFontScanBenchmark_" + Guid.NewGuid().ToString("N")); + _sharedFolder = Path.Combine(_root, "shared"); + FillFolder(_sharedFolder); + + _warmEngine = BenchmarkFonts.CreateEngine(_sharedFolder); + _warmEngine.LoadFont("Roboto", FontSubFamily.Regular); + } + + [GlobalCleanup] + public void Cleanup() + { + _warmEngine.Dispose(); + _coldEngine?.Dispose(); + TryDelete(_root); + } + + private void FillFolder(string folder) + { + Directory.CreateDirectory(folder); + + // Fonts other than Roboto, so a lookup of Roboto has to look through the copies. + var sources = Directory.GetFiles(BenchmarkFonts.FontsPath) + .Where(f => (f.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".otf", StringComparison.OrdinalIgnoreCase)) + && !Path.GetFileName(f).StartsWith("Roboto", StringComparison.OrdinalIgnoreCase)) + .OrderBy(f => f, StringComparer.Ordinal) + .ToArray(); + + for (int i = 0; i < FileCount - 1; i++) + { + var source = sources[i % sources.Length]; + File.Copy(source, Path.Combine(folder, $"font{i:D4}{Path.GetExtension(source)}")); + } + File.Copy(Path.Combine(BenchmarkFonts.FontsPath, BenchmarkFonts.Roboto), Path.Combine(folder, "zz-Roboto-Regular.ttf")); + } + + private static void TryDelete(string folder) + { + try + { + if (Directory.Exists(folder)) + Directory.Delete(folder, true); + } + catch (IOException) + { + // A file still held open must not fail the run; the temp folder is cleaned later. + } + catch (UnauthorizedAccessException) + { + } + } + + [IterationSetup(Targets = new[] { nameof(FirstInProcess_ExistingFont), nameof(FirstInProcess_MissingFont) })] + public void FirstInProcessSetup() + { + _coldEngine?.Dispose(); + TryDelete(_iterationFolder); + _iterationFolder = Path.Combine(_root, "iteration" + _iteration++); + FillFolder(_iterationFolder); + _coldEngine = BenchmarkFonts.CreateEngine(_iterationFolder); + } + + [IterationSetup(Targets = new[] { nameof(NewEngine_ExistingFont), nameof(NewEngine_MissingFont) })] + public void NewEngineSetup() + { + _coldEngine?.Dispose(); + _coldEngine = BenchmarkFonts.CreateEngine(_sharedFolder); + } + + /// + /// The first lookup in a folder the process has never seen: listing and scanning every file. + /// + [Benchmark] + public OpenTypeFont FirstInProcess_ExistingFont() + { + return _coldEngine!.LoadFont("Roboto", FontSubFamily.Regular); + } + + /// + /// As above, for a name no file has, which then falls back to the built-in font. + /// + [Benchmark] + public OpenTypeFont FirstInProcess_MissingFont() + { + return _coldEngine!.LoadFont("No Such Font", FontSubFamily.Regular); + } + + [Benchmark] + public OpenTypeFont NewEngine_ExistingFont() + { + return _coldEngine!.LoadFont("Roboto", FontSubFamily.Regular); + } + + [Benchmark] + public OpenTypeFont NewEngine_MissingFont() + { + return _coldEngine!.LoadFont("No Such Font", FontSubFamily.Regular); + } + + [Benchmark(Baseline = true)] + public OpenTypeFont WarmLookup() + { + return _warmEngine.LoadFont("Roboto", FontSubFamily.Regular); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-OFL.txt b/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-OFL.txt new file mode 100644 index 0000000000..d4e170557f --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/arabic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-Regular.ttf b/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-Regular.ttf new file mode 100644 index 0000000000..72c9228c33 Binary files /dev/null and b/src/EPPlus.Fonts.OpenType.Benchmarks/Fonts/NotoSansArabic-Regular.ttf differ diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/LargeSubsetBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/LargeSubsetBenchmarks.cs new file mode 100644 index 0000000000..8942e9991e --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/LargeSubsetBenchmarks.cs @@ -0,0 +1,105 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/03/2026 EPPlus Software AB Subsets of hundreds to thousands of glyphs + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using System; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// Subsets of realistic size, from a few hundred to a few thousand glyphs, and serializing + /// them to the bytes that are embedded in a file. The existing SubsettingBenchmarks only + /// cover short Latin strings. + /// + /// Fonts with CFF outlines (.otf) are not included: the library does not subset them. Web + /// output references them by name and PDF output embeds the whole font. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 2, iterationCount: 5)] + public class LargeSubsetBenchmarks + { + public enum SubsetScenario + { + /// All kana and the first kanji of BIZ UDGothic, 500 characters. + Japanese500, + /// All kana and the first kanji of BIZ UDGothic, 2 500 characters. + Japanese2500, + /// Every BMP character in EB Garamond, with a large GSUB glyph closure. + EBGaramondAll, + /// Every BMP character in Noto Sans Arabic. + ArabicAll, + } + + [Params(SubsetScenario.Japanese500, SubsetScenario.Japanese2500, + SubsetScenario.EBGaramondAll, SubsetScenario.ArabicAll)] + public SubsetScenario Scenario { get; set; } + + private OpenTypeFontEngine _engine = null!; + private OpenTypeFont _font = null!; + private string _chars = string.Empty; + private OpenTypeFont _subset = null!; + + [GlobalSetup] + public void Setup() + { + _engine = BenchmarkFonts.CreateEngine(); + switch (Scenario) + { + case SubsetScenario.Japanese500: + case SubsetScenario.Japanese2500: + _font = BenchmarkFonts.LoadFile(_engine, BenchmarkFonts.BizUdGothic); + _chars = BenchmarkFonts.GetMappedChars(_font, + Scenario == SubsetScenario.Japanese500 ? 500 : 2500, + (0x3040, 0x30FF), (0x4E00, 0x9FFF)); + break; + case SubsetScenario.EBGaramondAll: + _font = BenchmarkFonts.LoadFile(_engine, BenchmarkFonts.EBGaramond); + _chars = BenchmarkFonts.GetMappedChars(_font); + break; + case SubsetScenario.ArabicAll: + _font = BenchmarkFonts.LoadFile(_engine, BenchmarkFonts.NotoSansArabic); + _chars = BenchmarkFonts.GetMappedChars(_font); + break; + default: + throw new ArgumentOutOfRangeException(nameof(Scenario)); + } + + _subset = _font.CreateSubset(_chars); + Console.WriteLine($"// {Scenario}: {_chars.Length} chars, {_font.GlyfTable?.Glyphs.Count ?? 0} glyphs in font, " + + $"{_subset.Serialize().Length / 1024} KB serialized subset"); + } + + [GlobalCleanup] + public void Cleanup() + { + _engine.Dispose(); + } + + [Benchmark] + public OpenTypeFont CreateSubset() + { + return _font.CreateSubset(_chars); + } + + [Benchmark] + public byte[] CreateSubset_AndSerialize() + { + return _font.CreateSubset(_chars).Serialize(); + } + + [Benchmark] + public byte[] Serialize_PrebuiltSubset() + { + return _subset.Serialize(); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/LayoutTableShapingBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/LayoutTableShapingBenchmarks.cs new file mode 100644 index 0000000000..47956ff37c --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/LayoutTableShapingBenchmarks.cs @@ -0,0 +1,117 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/03/2026 EPPlus Software AB Shaping with fonts that have heavy layout tables + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using EPPlus.Fonts.OpenType.TextShaping; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// Shaping with fonts whose GSUB and GPOS tables are much larger than Roboto's: Oi (176 KB + /// GPOS), Source Sans 3 (CFF outlines, 38 KB GSUB, 94 KB GPOS) and EB Garamond (82 KB GPOS). + /// Roboto is included as the reference. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 3, iterationCount: 5)] + public class LayoutTableShapingBenchmarks + { + [Params(BenchmarkFonts.Roboto, BenchmarkFonts.Oi, BenchmarkFonts.SourceSans3, BenchmarkFonts.EBGaramond)] + public string Font { get; set; } = BenchmarkFonts.Roboto; + + private OpenTypeFontEngine _engine = null!; + private TextShaper _shaper = null!; + private string _longLatin = string.Empty; + + [GlobalSetup] + public void Setup() + { + _engine = BenchmarkFonts.CreateEngine(); + _shaper = new TextShaper(_engine, BenchmarkFonts.LoadFile(_engine, Font)); + + _longLatin = BenchmarkFonts.Repeat(BenchmarkFonts.LatinSample, 11000); + } + + [GlobalCleanup] + public void Cleanup() + { + _engine.Dispose(); + } + + [Benchmark] + public ShapedText Shape_Short() + { + return _shaper.Shape(BenchmarkFonts.LatinSample); + } + + [Benchmark] + public ShapedText Shape_Long() + { + return _shaper.Shape(_longLatin); + } + + [Benchmark] + public double[] ExtractCharWidths_Long() + { + return _shaper.ExtractCharWidths(_longLatin, 11f, ShapingOptions.Default); + } + } + + /// + /// Shaping of complex scripts with fonts made for them: Arabic joining forms, ligatures and + /// mark positioning, and Japanese text in a font with 12 638 glyphs. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 3, iterationCount: 5)] + public class ScriptShapingBenchmarks + { + private OpenTypeFontEngine _engine = null!; + private TextShaper _arabicShaper = null!; + private TextShaper _japaneseShaper = null!; + private string _longArabic = string.Empty; + private string _longJapanese = string.Empty; + + [GlobalSetup] + public void Setup() + { + _engine = BenchmarkFonts.CreateEngine(); + _arabicShaper = new TextShaper(_engine, BenchmarkFonts.LoadFile(_engine, BenchmarkFonts.NotoSansArabic)); + _japaneseShaper = new TextShaper(_engine, BenchmarkFonts.LoadFile(_engine, BenchmarkFonts.BizUdGothic)); + _longArabic = BenchmarkFonts.Repeat(BenchmarkFonts.ArabicSample, 10000); + _longJapanese = BenchmarkFonts.Repeat(BenchmarkFonts.JapaneseSample, 2000); + } + + [GlobalCleanup] + public void Cleanup() + { + _engine.Dispose(); + } + + [Benchmark] + public ShapedText Shape_Arabic_Short() + { + return _arabicShaper.Shape(BenchmarkFonts.ArabicSample); + } + + [Benchmark] + public ShapedText Shape_Arabic_Long() + { + return _arabicShaper.Shape(_longArabic); + } + + [Benchmark] + public ShapedText Shape_Japanese_Long() + { + return _japaneseShaper.Shape(_longJapanese); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/Program.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/Program.cs index bb0446d4c0..f8f6f97eb8 100644 --- a/src/EPPlus.Fonts.OpenType.Benchmarks/Program.cs +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/Program.cs @@ -1,14 +1,26 @@ -using BenchmarkDotNet.Running; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Running; +using BenchmarkDotNet.Toolchains.InProcess.Emit; namespace EPPlus.Fonts.OpenType.Benchmarks { - // Program.cs - Entry point public class Program { public static void Main(string[] args) { - // Kör alla benchmark-klasser i assembly - BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); + // BenchmarkDotNet's own --inProcess switch adds a separate default job next to the + // [SimpleJob] of each class, so every benchmark runs twice and the default job runs + // far more iterations. Handle the switch here instead, as a mutator that only changes + // the toolchain of the jobs the classes declare. + IConfig? config = null; + if (args.Any(a => string.Equals(a, "--inProcess", StringComparison.OrdinalIgnoreCase))) + { + args = args.Where(a => !string.Equals(a, "--inProcess", StringComparison.OrdinalIgnoreCase)).ToArray(); + config = DefaultConfig.Instance.AddJob(Job.Default.WithToolchain(InProcessEmitToolchain.Instance).AsMutator()); + } + + BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config); } } -} \ No newline at end of file +} diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/TextLayoutEngineBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/TextLayoutEngineBenchmarks.cs index 0502e29325..6ac300efab 100644 --- a/src/EPPlus.Fonts.OpenType.Benchmarks/TextLayoutEngineBenchmarks.cs +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/TextLayoutEngineBenchmarks.cs @@ -29,111 +29,58 @@ namespace EPPlus.Fonts.Benchmarks [SimpleJob(warmupCount: 3, iterationCount: 5)] public class TextLayoutEngineBenchmarks { - // 20 paragraphs of 'lorem ipsum' - same as TextMeasurementBenchmarks + // 20 paragraphs of 'lorem ipsum' private const string LoremIpsum20Para = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla pulvinar interdum imperdiet. Praesent ut auctor urna. Phasellus sollicitudin quam vitae est convallis, eu mattis lorem efficitur. Mauris nulla libero, tincidunt id ipsum non, lobortis tristique mauris. Donec ut enim sed enim fermentum molestie vel quis odio. Morbi a fermentum massa, sit amet ultrices est. Aenean ante mi, fermentum nec rhoncus et, vulputate vel sapien. Donec tempus, leo quis luctus rhoncus, augue odio pharetra libero, ac blandit urna turpis sed diam. Vivamus augue purus, eleifend et justo facilisis, imperdiet rhoncus sem. Quisque accumsan pellentesque elit, eget finibus massa accumsan in.\r\n\r\nFusce eu accumsan enim. Cras pulvinar enim vel tellus lacinia, consectetur euismod tortor consectetur. Praesent tincidunt pretium eros, ac auctor magna luctus sed. Ut porta lectus quam, non ornare mauris lacinia sit amet. Nullam egestas dolor quis magna porttitor, ac iaculis nisi hendrerit. Proin at mollis lacus, in porttitor nunc. Aliquam erat volutpat. Sed vel egestas risus, at aliquam arcu. Vestibulum quis lobortis nulla. Etiam pellentesque auctor nulla, eget tincidunt felis rhoncus id. Sed metus ante, efficitur id dui eu, fermentum mollis odio. Phasellus ullamcorper iaculis augue vel consequat. Etiam fringilla euismod interdum. Ut molestie massa id fringilla lobortis. Vestibulum malesuada, ante vel mattis ultrices, sem ante molestie augue, non tristique dui mi non nibh.\r\n\r\nMaecenas dictum, sem eget convallis rhoncus, lacus enim porta neque, in posuere dui ex a sapien. Nam lacus nibh, posuere sed elit eget, condimentum facilisis ligula. Cras consectetur lacus ullamcorper velit aliquet bibendum eget vel nulla. Aenean varius ac erat quis ullamcorper. Donec laoreet arcu a lorem volutpat faucibus. Vivamus vehicula leo ut erat luctus scelerisque. Morbi posuere ex et magna egestas facilisis. Fusce scelerisque volutpat erat bibendum hendrerit. Nam blandit mi ut metus pulvinar, vel tempus lacus euismod. Quisque imperdiet sit amet sapien sed ultricies. Phasellus sodales, ipsum vitae tincidunt facilisis, nulla ligula faucibus felis, eget vehicula ante lacus eu lorem.\r\n\r\nInteger congue diam ac viverra tristique. Curabitur tristique dolor quis quam pretium, et scelerisque quam dictum. Maecenas vitae sodales ligula. Pellentesque maximus diam vel porta convallis. Ut aliquam eros quis porta pellentesque. Fusce in ex ut mi egestas cursus. Aliquam erat volutpat. Cras laoreet condimentum laoreet.\r\n\r\nSed eget facilisis tellus. Morbi viverra odio sed odio placerat mollis. Duis turpis metus, dignissim varius urna quis, viverra dignissim dui. Vivamus viverra at nisi quis convallis. Suspendisse fringilla risus et ante sollicitudin, sed eleifend sem placerat. Proin pretium blandit arcu, eget rhoncus risus hendrerit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus vulputate efficitur maximus.\r\n\r\nCras blandit nulla eu nisi auctor tempus. Sed pretium lacus ac magna vestibulum, aliquam faucibus orci luctus. Mauris enim lorem, varius ut ante quis, varius viverra lectus. Fusce blandit nibh vel feugiat efficitur. Donec maximus id justo ac mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla placerat lectus et purus dictum, id congue nisi euismod. Maecenas euismod fermentum diam, sit amet gravida magna suscipit a. Quisque consectetur arcu eu nunc sodales scelerisque. Nulla non tincidunt nulla. Pellentesque ut tortor vel enim convallis malesuada.\r\n\r\nAliquam ultricies bibendum ultrices. Mauris rutrum ac nisl vel luctus. Donec quis nibh vitae orci ultricies gravida. Aliquam vitae velit porttitor lorem bibendum fringilla volutpat a eros. Curabitur at commodo tortor. Etiam ultricies, neque et iaculis euismod, diam ligula luctus mi, vitae lobortis felis lorem eu nulla. Sed a semper ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla mauris elit, pulvinar ac tortor et, luctus hendrerit nisl. In egestas auctor urna vitae laoreet. Praesent bibendum egestas convallis. Proin non suscipit tellus.\r\n\r\nNullam at nibh in urna laoreet sodales non vel tellus. Donec in enim dui. Phasellus quis quam tincidunt, pellentesque lorem ac, scelerisque neque. Integer nec tempus urna. Donec elit massa, eleifend eu sapien sit amet, mollis pellentesque est. Nullam tristique tellus iaculis arcu consectetur pretium. Sed venenatis convallis scelerisque. Suspendisse varius urna sit amet purus accumsan, id ultricies erat efficitur. Cras non ipsum eget nulla efficitur commodo sit amet non lacus. Proin viverra enim sit amet enim tempus ullamcorper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis ac massa interdum, gravida ex egestas, finibus purus. Nunc consectetur commodo lacus, ac convallis quam lobortis eu. Sed convallis tempor commodo. Nulla sed convallis mauris.\r\n\r\nDonec venenatis nisi est, ac ullamcorper mi pretium quis. Donec vitae eros at ipsum interdum scelerisque nec vitae nisi. Sed vestibulum erat ac bibendum dapibus. Morbi nec elit id quam tristique cursus id sed sem. Praesent non ante enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent non mauris dui. Aliquam rhoncus mattis ante sed venenatis. Vivamus vehicula sed sapien sed dictum. In aliquet, urna efficitur tincidunt lobortis, nibh justo tristique purus, sed volutpat risus magna et libero.\r\n\r\nSuspendisse lectus justo, varius eget arcu et, semper laoreet erat. Quisque eget lacus ornare, pellentesque erat sit amet, vulputate felis. Duis luctus, massa a pellentesque mollis, massa elit convallis mi, vel bibendum ex ex eu purus. Suspendisse vel fermentum urna, ac commodo enim. Mauris tincidunt cursus elit, a volutpat libero commodo et. Etiam dapibus libero venenatis tellus lobortis, vel lacinia elit faucibus. Maecenas semper sed quam quis finibus. Integer efficitur, libero imperdiet sollicitudin commodo, elit arcu vulputate est, eget finibus mi urna sit amet magna. Cras ullamcorper consequat ornare. Fusce convallis nunc vel risus cursus, at maximus ligula cursus. Pellentesque vulputate risus libero, eget cursus nibh sodales sed. Donec accumsan sem et massa semper, id dignissim velit vehicula.\r\n\r\nCras cursus ipsum ac erat vehicula, nec iaculis purus dictum. Quisque lacinia elit vitae leo dictum, vel dignissim velit dapibus. Aenean sem nisi, faucibus interdum justo eu, euismod porttitor ex. Morbi et lectus lectus. Duis neque felis, suscipit at scelerisque eu, scelerisque id orci. Curabitur et placerat ipsum. Proin gravida sapien nisl, et varius ipsum mollis nec. Quisque dignissim consectetur feugiat. Aenean eros purus, laoreet interdum rutrum at, aliquet sit amet lectus. Donec gravida lorem ut tincidunt laoreet. Donec consequat viverra ligula, in accumsan mi bibendum scelerisque. Quisque ac risus justo. Morbi magna arcu, egestas nec luctus commodo, cursus eget nunc. Vivamus euismod lorem ex, et maximus felis hendrerit eget. Nullam ullamcorper euismod ligula, et iaculis ligula ultricies a. Fusce aliquam, enim vel fermentum ultrices, elit quam semper erat, vitae semper velit augue non magna.\r\n\r\nQuisque maximus semper arcu, id pellentesque est tempus a. Phasellus lacus elit, auctor sit amet lacinia a, dapibus vitae velit. Phasellus ut pharetra justo, ut ultricies erat. Sed molestie sapien vel interdum lobortis. Nulla facilisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla nec mauris quis nisi vulputate gravida quis nec velit.\r\n\r\nNam et congue ipsum. Nulla vel elit non dolor mollis aliquet vel at magna. Pellentesque nec facilisis elit. In vulputate quis sem porta suscipit. Nullam sed ex ornare nibh suscipit mattis quis non lacus. Mauris vel ex urna. Vivamus ultricies sapien sit amet sapien vehicula gravida. Donec feugiat volutpat quam. Vestibulum auctor dictum nisl, id hendrerit metus ullamcorper sed. Nulla maximus lacus vel mollis maximus. Nulla laoreet placerat quam eu viverra. Etiam feugiat accumsan nisl a condimentum. Sed ultricies ante ante, ac auctor ligula gravida nec. Praesent a neque dignissim, sagittis felis sit amet, condimentum turpis.\r\n\r\nFusce at leo vel est blandit malesuada. Pellentesque et neque non metus pellentesque imperdiet. Praesent pellentesque lacinia lorem, et tristique tellus efficitur id. Suspendisse aliquet ultricies justo vitae interdum. Cras tristique viverra quam, eget gravida mi fermentum imperdiet. Sed imperdiet vitae purus ut volutpat. Nulla lacinia elit in fermentum consectetur. Phasellus commodo ut nisl sit amet sagittis. Duis ac ornare orci.\r\n\r\nVivamus vel enim posuere, pharetra ex vel, elementum est. Vestibulum commodo luctus metus eget maximus. Suspendisse a nulla a odio eleifend faucibus. Suspendisse semper lacus non porttitor aliquet. Cras ac scelerisque magna, et pulvinar justo. Integer cursus pulvinar fringilla. Mauris imperdiet nibh sit amet tempor laoreet. Morbi tincidunt tortor ex, sit amet maximus purus tristique quis. Quisque sed hendrerit velit. Mauris mattis nibh ut eros luctus, eget mattis massa auctor. Phasellus eu neque at augue gravida sagittis nec non tortor. Etiam porttitor sem sodales mi ullamcorper gravida.\r\n\r\nIn in dictum orci. In vitae vestibulum quam. Cras augue eros, tincidunt ac elit posuere, sollicitudin efficitur lectus. Praesent quis sodales nisl. Proin sit amet molestie est. In commodo mauris vel mauris efficitur, nec mollis mauris sagittis. Cras ligula nibh, egestas sit amet eros in, lacinia tristique magna. Cras risus libero, lacinia eget libero vitae, maximus aliquet nibh. Mauris id sodales purus, vitae dictum lectus. Cras consectetur ligula velit, tempus pulvinar lacus porttitor vitae. Phasellus eget tellus ipsum.\r\n\r\nDonec interdum laoreet elit non vestibulum. Cras sed urna ullamcorper, aliquam erat eget, porta orci. Vestibulum eget congue nulla. Sed sem tortor, euismod at rutrum id, sagittis a nunc. Duis in nibh facilisis, dignissim purus ut, hendrerit magna. Sed semper ligula id massa elementum, non malesuada velit egestas. Nullam dictum, mi nec euismod sagittis, ligula leo ullamcorper dolor, quis faucibus odio metus eget magna. Ut gravida metus non metus bibendum bibendum. In sagittis eleifend aliquet.\r\n\r\nInterdum et malesuada fames ac ante ipsum primis in faucibus. Nam mollis sagittis felis, in faucibus tortor pretium vel. Nam nec enim metus. Donec in augue arcu. Proin non lobortis purus, sit amet lacinia elit. Suspendisse quis eros condimentum, blandit justo sit amet, lobortis nisl. Suspendisse maximus massa sed urna tempor ornare. Nunc malesuada purus odio, eu luctus lectus auctor nec. Morbi auctor pellentesque auctor. Sed ullamcorper, ex vitae aliquam vulputate, est diam feugiat mi, id porttitor lectus orci ac leo.\r\n\r\nDonec sit amet velit pulvinar, venenatis turpis ut, interdum ligula. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eu lacus urna. Maecenas sem nulla, accumsan eu ultricies sed, tempor vel magna. Cras aliquet sollicitudin sapien ac pulvinar. Praesent ac sodales mi. Integer vitae mauris massa. Maecenas iaculis orci et faucibus interdum.\r\n\r\nNunc nec maximus felis, sed finibus quam. Pellentesque felis massa, vestibulum in tellus vitae, congue tincidunt justo. Nunc vitae enim malesuada, bibendum ante nec, varius tellus. Praesent vitae nisi id quam auctor lacinia at non quam. Nam nec ligula sit amet felis auctor sagittis. Nunc in risus eu urna varius laoreet quis sit amet felis. Morbi varius tempor orci, eu vestibulum nunc vestibulum ac. Nunc vehicula velit eleifend consequat porta. Suspendisse maximus dapibus orci, in vulputate massa pretium ac. Quisque malesuada aliquet aliquet."; + private OpenTypeFontEngine _fontEngine; private TextLayoutEngine _layoutEngine; - // private FontMeasurerTrueType _oldMeasurer; + private TextShaper _shaper; - private const double MaxPixelWidth = 52d; - private const double MaxPointWidth = 39d; // 52 pixels ≈ 39 points (at 96 DPI) + private const double MaxPointWidth = 39d; // 52 pixels at 96 DPI private const float FontSize = 11f; private const string Family = "Roboto"; private List _fragments10; private List _texts10; - private List _fonts10; - //[GlobalSetup] - //public void Setup() - //{ - // // Setup old measurer - // _oldMeasurer = new FontMeasurerTrueType(); - // _oldMeasurer.SetFont(FontSize, Family); - - // var fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts"); - - // if (!Directory.Exists(fontsPath)) - // { - // throw new DirectoryNotFoundException($"Fonts directory not found: {fontsPath}"); - // } - - // var fontFolders = new List { fontsPath }; - - // // Setup new layout engine - // var font = OpenTypeFonts.LoadFont(Family, FontSubFamily.Regular); - // var shaper = new TextShaper(font); - // _layoutEngine = new TextLayoutEngine(shaper); - - // // Prepare 100 copies of the long text - // _fragments10 = new List(); - // _texts10 = new List(); - // _fonts10 = new List(); - - // var OpenTypeFontInfoBase = new OpenTypeFontInfoBase - // { - // Family = Family, - // Size = FontSize, - // SubFamily = OpenTypeFontInfoBaseSubFamilys.Regular - // }; - - // for (int i = 0; i < 10; i++) - // { - // _texts10.Add(LoremIpsum20Para); - // _fonts10.Add(measurementFont); - // _fragments10.Add(new TextFragment - // { - // Text = LoremIpsum20Para, - // Font = measurementFont - // }); - // } - //} - - //#region Old Implementation Benchmarks (Baseline) - - //[Benchmark(Baseline = true)] - //public List Old_Wrap_SingleParagraph() - //{ - // return _oldMeasurer.MeasureAndWrapText(LoremIpsum20Para, MaxPixelWidth); - //} - - //[Benchmark] - //public List Old_Wrap_10Paragraphs_Sequential() - //{ - // List wrapped = new List(); - // foreach (string text in _texts10) - // { - // wrapped = _oldMeasurer.MeasureAndWrapText(text, MaxPixelWidth); - // } - // return wrapped; - //} - - //[Benchmark] - //public List Old_Wrap_10Paragraphs_MultipleFragments() - //{ - // return _oldMeasurer.WrapMultipleTextFragments(_texts10, _fonts10, MaxPixelWidth); - //} - - //[Benchmark] - //public List Old_Wrap_ShortText() - //{ - // var shortText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; - // return _oldMeasurer.MeasureAndWrapText(shortText, MaxPixelWidth); - //} + [GlobalSetup] + public void Setup() + { + var fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts"); + if (!Directory.Exists(fontsPath)) + { + throw new DirectoryNotFoundException($"Fonts directory not found: {fontsPath}"); + } - //[Benchmark] - //public List Old_Wrap_WideColumn() - //{ - // return _oldMeasurer.MeasureAndWrapText(LoremIpsum20Para, 200d); - //} + // Only the benchmark's own fonts (Roboto Regular, Bold, Italic), so the results do not + // depend on what is installed on the machine. + _fontEngine = new OpenTypeFontEngine(x => + { + x.FontDirectories.Add(fontsPath); + x.SearchSystemDirectories = false; + }); + var font = _fontEngine.LoadFont(Family, FontSubFamily.Regular); + _shaper = new TextShaper(_fontEngine, font); + _layoutEngine = new TextLayoutEngine(_fontEngine, _shaper); - //[Benchmark] - //public List Old_Wrap_NarrowColumn() - //{ - // return _oldMeasurer.MeasureAndWrapText(LoremIpsum20Para, 30d); - //} + _texts10 = new List(); + _fragments10 = new List(); + for (int i = 0; i < 10; i++) + { + _texts10.Add(LoremIpsum20Para); + _fragments10.Add(new TextFragment + { + Text = LoremIpsum20Para, + Font = new FontFormatBase { Family = Family, Size = FontSize } + }); + } + } - //#endregion + [GlobalCleanup] + public void Cleanup() + { + _fontEngine.Dispose(); + } #region New Implementation Benchmarks @@ -157,15 +104,7 @@ public List New_Wrap_10Paragraphs_Sequential() [Benchmark] public double[] OnlyExtractWidths() { - var fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts"); - var fontEngine = new OpenTypeFontEngine(x => - { - x.FontDirectories.Add(fontsPath); - x.SearchSystemDirectories = false; - }); - var font = fontEngine.LoadFont(Family, FontSubFamily.Regular); - var shaper = new TextShaper(fontEngine, font); - return shaper.ExtractCharWidths(LoremIpsum20Para, FontSize, ShapingOptions.Default); + return _shaper.ExtractCharWidths(LoremIpsum20Para, FontSize, ShapingOptions.Default); } [Benchmark] diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/TextMeasurementBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/TextMeasurementBenchmarks.cs deleted file mode 100644 index cff7d6e363..0000000000 --- a/src/EPPlus.Fonts.OpenType.Benchmarks/TextMeasurementBenchmarks.cs +++ /dev/null @@ -1,123 +0,0 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 01/20/2025 EPPlus Software AB Initial implementation - *************************************************************************************************/ -using BenchmarkDotNet.Attributes; -using EPPlus.Fonts.OpenType; -using EPPlus.Fonts.OpenType.FontCache; -using OfficeOpenXml.Interfaces.Drawing.Text; -using System.Collections.Generic; - -namespace EPPlus.Fonts.Benchmarks -{ - /// - /// Benchmarks for text measurement and wrapping performance. - /// Tests measure and wrap operations on varying text lengths. - /// - [MemoryDiagnoser] - [SimpleJob(warmupCount: 3, iterationCount: 5)] - public class TextMeasurementBenchmarks - { - //// 20 paragraphs of 'lorem ipsum' - //// 1706 words, 11,800 characters (with whitespace), 10,095 characters without - //private const string LoremIpsum20Para = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla pulvinar interdum imperdiet. Praesent ut auctor urna. Phasellus sollicitudin quam vitae est convallis, eu mattis lorem efficitur. Mauris nulla libero, tincidunt id ipsum non, lobortis tristique mauris. Donec ut enim sed enim fermentum molestie vel quis odio. Morbi a fermentum massa, sit amet ultrices est. Aenean ante mi, fermentum nec rhoncus et, vulputate vel sapien. Donec tempus, leo quis luctus rhoncus, augue odio pharetra libero, ac blandit urna turpis sed diam. Vivamus augue purus, eleifend et justo facilisis, imperdiet rhoncus sem. Quisque accumsan pellentesque elit, eget finibus massa accumsan in.\r\n\r\nFusce eu accumsan enim. Cras pulvinar enim vel tellus lacinia, consectetur euismod tortor consectetur. Praesent tincidunt pretium eros, ac auctor magna luctus sed. Ut porta lectus quam, non ornare mauris lacinia sit amet. Nullam egestas dolor quis magna porttitor, ac iaculis nisi hendrerit. Proin at mollis lacus, in porttitor nunc. Aliquam erat volutpat. Sed vel egestas risus, at aliquam arcu. Vestibulum quis lobortis nulla. Etiam pellentesque auctor nulla, eget tincidunt felis rhoncus id. Sed metus ante, efficitur id dui eu, fermentum mollis odio. Phasellus ullamcorper iaculis augue vel consequat. Etiam fringilla euismod interdum. Ut molestie massa id fringilla lobortis. Vestibulum malesuada, ante vel mattis ultrices, sem ante molestie augue, non tristique dui mi non nibh.\r\n\r\nMaecenas dictum, sem eget convallis rhoncus, lacus enim porta neque, in posuere dui ex a sapien. Nam lacus nibh, posuere sed elit eget, condimentum facilisis ligula. Cras consectetur lacus ullamcorper velit aliquet bibendum eget vel nulla. Aenean varius ac erat quis ullamcorper. Donec laoreet arcu a lorem volutpat faucibus. Vivamus vehicula leo ut erat luctus scelerisque. Morbi posuere ex et magna egestas facilisis. Fusce scelerisque volutpat erat bibendum hendrerit. Nam blandit mi ut metus pulvinar, vel tempus lacus euismod. Quisque imperdiet sit amet sapien sed ultricies. Phasellus sodales, ipsum vitae tincidunt facilisis, nulla ligula faucibus felis, eget vehicula ante lacus eu lorem.\r\n\r\nInteger congue diam ac viverra tristique. Curabitur tristique dolor quis quam pretium, et scelerisque quam dictum. Maecenas vitae sodales ligula. Pellentesque maximus diam vel porta convallis. Ut aliquam eros quis porta pellentesque. Fusce in ex ut mi egestas cursus. Aliquam erat volutpat. Cras laoreet condimentum laoreet.\r\n\r\nSed eget facilisis tellus. Morbi viverra odio sed odio placerat mollis. Duis turpis metus, dignissim varius urna quis, viverra dignissim dui. Vivamus viverra at nisi quis convallis. Suspendisse fringilla risus et ante sollicitudin, sed eleifend sem placerat. Proin pretium blandit arcu, eget rhoncus risus hendrerit at. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus vulputate efficitur maximus.\r\n\r\nCras blandit nulla eu nisi auctor tempus. Sed pretium lacus ac magna vestibulum, aliquam faucibus orci luctus. Mauris enim lorem, varius ut ante quis, varius viverra lectus. Fusce blandit nibh vel feugiat efficitur. Donec maximus id justo ac mollis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla placerat lectus et purus dictum, id congue nisi euismod. Maecenas euismod fermentum diam, sit amet gravida magna suscipit a. Quisque consectetur arcu eu nunc sodales scelerisque. Nulla non tincidunt nulla. Pellentesque ut tortor vel enim convallis malesuada.\r\n\r\nAliquam ultricies bibendum ultrices. Mauris rutrum ac nisl vel luctus. Donec quis nibh vitae orci ultricies gravida. Aliquam vitae velit porttitor lorem bibendum fringilla volutpat a eros. Curabitur at commodo tortor. Etiam ultricies, neque et iaculis euismod, diam ligula luctus mi, vitae lobortis felis lorem eu nulla. Sed a semper ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla mauris elit, pulvinar ac tortor et, luctus hendrerit nisl. In egestas auctor urna vitae laoreet. Praesent bibendum egestas convallis. Proin non suscipit tellus.\r\n\r\nNullam at nibh in urna laoreet sodales non vel tellus. Donec in enim dui. Phasellus quis quam tincidunt, pellentesque lorem ac, scelerisque neque. Integer nec tempus urna. Donec elit massa, eleifend eu sapien sit amet, mollis pellentesque est. Nullam tristique tellus iaculis arcu consectetur pretium. Sed venenatis convallis scelerisque. Suspendisse varius urna sit amet purus accumsan, id ultricies erat efficitur. Cras non ipsum eget nulla efficitur commodo sit amet non lacus. Proin viverra enim sit amet enim tempus ullamcorper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis ac massa interdum, gravida ex egestas, finibus purus. Nunc consectetur commodo lacus, ac convallis quam lobortis eu. Sed convallis tempor commodo. Nulla sed convallis mauris.\r\n\r\nDonec venenatis nisi est, ac ullamcorper mi pretium quis. Donec vitae eros at ipsum interdum scelerisque nec vitae nisi. Sed vestibulum erat ac bibendum dapibus. Morbi nec elit id quam tristique cursus id sed sem. Praesent non ante enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent non mauris dui. Aliquam rhoncus mattis ante sed venenatis. Vivamus vehicula sed sapien sed dictum. In aliquet, urna efficitur tincidunt lobortis, nibh justo tristique purus, sed volutpat risus magna et libero.\r\n\r\nSuspendisse lectus justo, varius eget arcu et, semper laoreet erat. Quisque eget lacus ornare, pellentesque erat sit amet, vulputate felis. Duis luctus, massa a pellentesque mollis, massa elit convallis mi, vel bibendum ex ex eu purus. Suspendisse vel fermentum urna, ac commodo enim. Mauris tincidunt cursus elit, a volutpat libero commodo et. Etiam dapibus libero venenatis tellus lobortis, vel lacinia elit faucibus. Maecenas semper sed quam quis finibus. Integer efficitur, libero imperdiet sollicitudin commodo, elit arcu vulputate est, eget finibus mi urna sit amet magna. Cras ullamcorper consequat ornare. Fusce convallis nunc vel risus cursus, at maximus ligula cursus. Pellentesque vulputate risus libero, eget cursus nibh sodales sed. Donec accumsan sem et massa semper, id dignissim velit vehicula.\r\n\r\nCras cursus ipsum ac erat vehicula, nec iaculis purus dictum. Quisque lacinia elit vitae leo dictum, vel dignissim velit dapibus. Aenean sem nisi, faucibus interdum justo eu, euismod porttitor ex. Morbi et lectus lectus. Duis neque felis, suscipit at scelerisque eu, scelerisque id orci. Curabitur et placerat ipsum. Proin gravida sapien nisl, et varius ipsum mollis nec. Quisque dignissim consectetur feugiat. Aenean eros purus, laoreet interdum rutrum at, aliquet sit amet lectus. Donec gravida lorem ut tincidunt laoreet. Donec consequat viverra ligula, in accumsan mi bibendum scelerisque. Quisque ac risus justo. Morbi magna arcu, egestas nec luctus commodo, cursus eget nunc. Vivamus euismod lorem ex, et maximus felis hendrerit eget. Nullam ullamcorper euismod ligula, et iaculis ligula ultricies a. Fusce aliquam, enim vel fermentum ultrices, elit quam semper erat, vitae semper velit augue non magna.\r\n\r\nQuisque maximus semper arcu, id pellentesque est tempus a. Phasellus lacus elit, auctor sit amet lacinia a, dapibus vitae velit. Phasellus ut pharetra justo, ut ultricies erat. Sed molestie sapien vel interdum lobortis. Nulla facilisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla nec mauris quis nisi vulputate gravida quis nec velit.\r\n\r\nNam et congue ipsum. Nulla vel elit non dolor mollis aliquet vel at magna. Pellentesque nec facilisis elit. In vulputate quis sem porta suscipit. Nullam sed ex ornare nibh suscipit mattis quis non lacus. Mauris vel ex urna. Vivamus ultricies sapien sit amet sapien vehicula gravida. Donec feugiat volutpat quam. Vestibulum auctor dictum nisl, id hendrerit metus ullamcorper sed. Nulla maximus lacus vel mollis maximus. Nulla laoreet placerat quam eu viverra. Etiam feugiat accumsan nisl a condimentum. Sed ultricies ante ante, ac auctor ligula gravida nec. Praesent a neque dignissim, sagittis felis sit amet, condimentum turpis.\r\n\r\nFusce at leo vel est blandit malesuada. Pellentesque et neque non metus pellentesque imperdiet. Praesent pellentesque lacinia lorem, et tristique tellus efficitur id. Suspendisse aliquet ultricies justo vitae interdum. Cras tristique viverra quam, eget gravida mi fermentum imperdiet. Sed imperdiet vitae purus ut volutpat. Nulla lacinia elit in fermentum consectetur. Phasellus commodo ut nisl sit amet sagittis. Duis ac ornare orci.\r\n\r\nVivamus vel enim posuere, pharetra ex vel, elementum est. Vestibulum commodo luctus metus eget maximus. Suspendisse a nulla a odio eleifend faucibus. Suspendisse semper lacus non porttitor aliquet. Cras ac scelerisque magna, et pulvinar justo. Integer cursus pulvinar fringilla. Mauris imperdiet nibh sit amet tempor laoreet. Morbi tincidunt tortor ex, sit amet maximus purus tristique quis. Quisque sed hendrerit velit. Mauris mattis nibh ut eros luctus, eget mattis massa auctor. Phasellus eu neque at augue gravida sagittis nec non tortor. Etiam porttitor sem sodales mi ullamcorper gravida.\r\n\r\nIn in dictum orci. In vitae vestibulum quam. Cras augue eros, tincidunt ac elit posuere, sollicitudin efficitur lectus. Praesent quis sodales nisl. Proin sit amet molestie est. In commodo mauris vel mauris efficitur, nec mollis mauris sagittis. Cras ligula nibh, egestas sit amet eros in, lacinia tristique magna. Cras risus libero, lacinia eget libero vitae, maximus aliquet nibh. Mauris id sodales purus, vitae dictum lectus. Cras consectetur ligula velit, tempus pulvinar lacus porttitor vitae. Phasellus eget tellus ipsum.\r\n\r\nDonec interdum laoreet elit non vestibulum. Cras sed urna ullamcorper, aliquam erat eget, porta orci. Vestibulum eget congue nulla. Sed sem tortor, euismod at rutrum id, sagittis a nunc. Duis in nibh facilisis, dignissim purus ut, hendrerit magna. Sed semper ligula id massa elementum, non malesuada velit egestas. Nullam dictum, mi nec euismod sagittis, ligula leo ullamcorper dolor, quis faucibus odio metus eget magna. Ut gravida metus non metus bibendum bibendum. In sagittis eleifend aliquet.\r\n\r\nInterdum et malesuada fames ac ante ipsum primis in faucibus. Nam mollis sagittis felis, in faucibus tortor pretium vel. Nam nec enim metus. Donec in augue arcu. Proin non lobortis purus, sit amet lacinia elit. Suspendisse quis eros condimentum, blandit justo sit amet, lobortis nisl. Suspendisse maximus massa sed urna tempor ornare. Nunc malesuada purus odio, eu luctus lectus auctor nec. Morbi auctor pellentesque auctor. Sed ullamcorper, ex vitae aliquam vulputate, est diam feugiat mi, id porttitor lectus orci ac leo.\r\n\r\nDonec sit amet velit pulvinar, venenatis turpis ut, interdum ligula. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eu lacus urna. Maecenas sem nulla, accumsan eu ultricies sed, tempor vel magna. Cras aliquet sollicitudin sapien ac pulvinar. Praesent ac sodales mi. Integer vitae mauris massa. Maecenas iaculis orci et faucibus interdum.\r\n\r\nNunc nec maximus felis, sed finibus quam. Pellentesque felis massa, vestibulum in tellus vitae, congue tincidunt justo. Nunc vitae enim malesuada, bibendum ante nec, varius tellus. Praesent vitae nisi id quam auctor lacinia at non quam. Nam nec ligula sit amet felis auctor sagittis. Nunc in risus eu urna varius laoreet quis sit amet felis. Morbi varius tempor orci, eu vestibulum nunc vestibulum ac. Nunc vehicula velit eleifend consequat porta. Suspendisse maximus dapibus orci, in vulputate massa pretium ac. Quisque malesuada aliquet aliquet."; // INSERT LOREM IPSUM HERE - - ////private FontMeasurerTrueType _textMeasurer; - //private const double MaxPixelWidth = 52d; - //private const double FontSize = 11d; - //private const string FontFamily = "Aptos Narrow"; - - //private List _texts100; - //private List _fonts100; - - //[GlobalSetup] - //public void Setup() - //{ - // _textMeasurer = new FontMeasurerTrueType(); - // _textMeasurer.SetFont(FontSize, FontFamily); - - // // Prepare 100 copies of the long text - // _texts100 = new List(); - // _fonts100 = new List(); - - // var font = new MeasurementFont - // { - // FontFamily = FontFamily, - // Size = (float)FontSize, - // Style = MeasurementFontStyles.Regular - // }; - - // for (int i = 0; i < 100; i++) - // { - // _texts100.Add(LoremIpsum20Para); - // _fonts100.Add(font); - // } - //} - - //[Benchmark] - //public List Wrap_SingleParagraph() - //{ - // // Baseline: wrap a single 20-paragraph text - // return _textMeasurer.MeasureAndWrapText(LoremIpsum20Para, MaxPixelWidth); - //} - - //[Benchmark] - //public List Wrap_100Paragraphs_Sequential() - //{ - // // Original test: wrap 100 texts sequentially - // List wrapped = new List(); - - // foreach (string text in _texts100) - // { - // wrapped = _textMeasurer.MeasureAndWrapText(text, MaxPixelWidth); - // } - - // return wrapped; - //} - - //[Benchmark] - //public List Wrap_100Paragraphs_MultipleFragments() - //{ - // // Original multi-fragment test: wrap 100 texts in one call - // return _textMeasurer.WrapMultipleTextFragments(_texts100, _fonts100, MaxPixelWidth); - //} - - //[Benchmark] - //public List Wrap_ShortText() - //{ - // // Baseline: wrap a short text (first paragraph only) - // var shortText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; - // return _textMeasurer.MeasureAndWrapText(shortText, MaxPixelWidth); - //} - - //[Benchmark] - //public List Wrap_MediumText() - //{ - // // Medium length text (5 paragraphs, ~2950 chars) - // var mediumText = ""; // INSERT FIRST 5 PARAGRAPHS HERE - // return _textMeasurer.MeasureAndWrapText(mediumText, MaxPixelWidth); - //} - - //[Benchmark] - //public List Wrap_WideColumn() - //{ - // // Same text, but wider column (less wrapping needed) - // return _textMeasurer.MeasureAndWrapText(LoremIpsum20Para, 200d); - //} - - //[Benchmark] - //public List Wrap_NarrowColumn() - //{ - // // Same text, but narrower column (more wrapping needed) - // return _textMeasurer.MeasureAndWrapText(LoremIpsum20Para, 30d); - //} - } -} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Reading/EnglishNameLookupTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Reading/EnglishNameLookupTests.cs new file mode 100644 index 0000000000..ed07d2b243 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Reading/EnglishNameLookupTests.cs @@ -0,0 +1,114 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Tests for the English name lookup + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Name; +using System.IO; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Tests.Reading +{ + [TestClass] + public class EnglishNameLookupTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + [TestMethod] + public void EveryTestFont_MatchesPreviousRule() + { + foreach (var file in Directory.GetFiles(FontFolder, "*.*tf")) + { + var font = new OpenTypeFont(File.ReadAllBytes(file)); + var name = Path.GetFileName(file); + + Assert.AreEqual(Expected(font, NameRecordTypes.FontFamilyName), font.GetEnglishFontFamilyName(), name); + Assert.AreEqual(Expected(font, NameRecordTypes.FontSubfamilyName), font.GetEnglishFontSubFamilyName(), name); + Assert.AreEqual(Expected(font, NameRecordTypes.FullFontName), font.GetEnglishFullFontFamilyName(), name); + } + } + + [TestMethod] + public void FirstMatchOfAPriorityIsUsed_EvenWhenItsNameIsEmpty() + { + // The first Windows English record is empty. The rule takes the first record of each + // priority, so the later non-empty Windows English record is NOT used; Mac English is. + var font = FontWithRecords( + Record(3, 0x0409, ""), + Record(3, 0x0409, "Later Windows"), + Record(1, 0, "Mac"), + Record(0, 0, "Unicode")); + + Assert.AreEqual("Mac", font.GetEnglishFontFamilyName()); + Assert.AreEqual(Expected(font, NameRecordTypes.FontFamilyName), font.GetEnglishFontFamilyName()); + } + + [TestMethod] + public void FallsBackThroughThePriorities() + { + Assert.AreEqual("Windows", FontWithRecords(Record(0, 0, "Unicode"), Record(1, 0, "Mac"), Record(3, 0x0409, "Windows")).GetEnglishFontFamilyName()); + Assert.AreEqual("Unicode", FontWithRecords(Record(3, 0x041D, "Swedish"), Record(0, 0, "Unicode")).GetEnglishFontFamilyName()); + Assert.AreEqual("Swedish", FontWithRecords(Record(3, 0x041D, "Swedish"), Record(1, 5, "Other Mac")).GetEnglishFontFamilyName()); + // The last resort is the first record of the type, even when its name is empty. + Assert.AreEqual("", FontWithRecords(Record(3, 0x041D, ""), Record(1, 5, "Other Mac")).GetEnglishFontFamilyName()); + Assert.AreEqual("Other Mac", FontWithRecords(Record(1, 5, "Other Mac"), Record(3, 0x041D, "")).GetEnglishFontFamilyName()); + Assert.AreEqual("", FontWithRecords(Record(1, 5, ""), Record(0, 3, "Later")).GetEnglishFontFamilyName()); + Assert.AreEqual("", FontWithRecords().GetEnglishFontFamilyName()); + + foreach (var records in new[] + { + new[] { Record(3, 0x041D, ""), Record(1, 5, "Other Mac") }, + new[] { Record(1, 5, "Other Mac"), Record(3, 0x041D, "") }, + new[] { Record(0, 0, ""), Record(3, 0x041D, "Swedish"), Record(1, 0, "") }, + }) + { + var font = FontWithRecords(records); + Assert.AreEqual(Expected(font, NameRecordTypes.FontFamilyName), font.GetEnglishFontFamilyName()); + } + } + + private OpenTypeFont FontWithRecords(params NameRecord[] records) + { + var font = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"))); + font.NameTable.NameRecords = records; + return font; + } + + private static NameRecord Record(ushort platformId, ushort languageId, string name) + { + return new NameRecord + { + platformId = platformId, + languageID = languageId, + nameId = (ushort)NameRecordTypes.FontFamilyName, + RecordType = NameRecordTypes.FontFamilyName, + Name = name + }; + } + + /// + /// The previous implementation of the lookup, kept here as the reference. + /// + private static string Expected(OpenTypeFont font, NameRecordTypes recordType) + { + var records = font.NameTable.NameRecords; + var windowsEnglish = records.FirstOrDefault(x => x.platformId == 3 && x.languageID == 0x0409 && x.RecordType == recordType); + if (windowsEnglish != null && !string.IsNullOrEmpty(windowsEnglish.Name)) return windowsEnglish.Name; + var macEnglish = records.FirstOrDefault(x => x.platformId == 1 && x.languageID == 0 && x.RecordType == recordType); + if (macEnglish != null && !string.IsNullOrEmpty(macEnglish.Name)) return macEnglish.Name; + var unicodeEnglish = records.FirstOrDefault(x => x.platformId == 0 && x.languageID == 0 && x.RecordType == recordType); + if (unicodeEnglish != null && !string.IsNullOrEmpty(unicodeEnglish.Name)) return unicodeEnglish.Name; + var anyWindows = records.FirstOrDefault(x => x.platformId == 3 && x.RecordType == recordType); + if (anyWindows != null && !string.IsNullOrEmpty(anyWindows.Name)) return anyWindows.Name; + var any = records.FirstOrDefault(x => x.RecordType == recordType); + return any?.Name ?? string.Empty; + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Reading/FontsBinaryReaderTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Reading/FontsBinaryReaderTests.cs new file mode 100644 index 0000000000..45b3027534 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Reading/FontsBinaryReaderTests.cs @@ -0,0 +1,77 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Tests for big-endian reads + *************************************************************************************************/ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.Reading +{ + /// + /// Tests the big-endian number reads of FontsBinaryReader: values, byte counting, + /// the read budget and the end of the data. + /// + [TestClass] + public class FontsBinaryReaderTests + { + private static FontsBinaryReader Reader(params byte[] bytes) + { + return new FontsBinaryReader(new MemoryStream(bytes)); + } + + [TestMethod] + public void ReadBigEndianValues() + { + using var reader = Reader( + 0x12, 0x34, // UInt16 + 0xFF, 0xFE, // Int16 -2 + 0x80, 0x00, // Int16 -32768 + 0xAB, 0xCD, 0xEF, // UInt24 + 0xFF, 0xFF, 0xFF, 0xFD, // Int32 -3 + 0xDE, 0xAD, 0xBE, 0xEF, // UInt32 + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // Int64 + 0x00, 0x01, 0xFF, 0xFF); // UInt16 array + + Assert.AreEqual((ushort)0x1234, reader.ReadUInt16BigEndian()); + Assert.AreEqual((short)-2, reader.ReadInt16BigEndian()); + Assert.AreEqual(short.MinValue, reader.ReadInt16BigEndian()); + Assert.AreEqual(0xABCDEFu, reader.ReadUInt24BigEndian()); + Assert.AreEqual(-3, reader.ReadInt32BigEndian()); + Assert.AreEqual(0xDEADBEEFu, reader.ReadUInt32BigEndian()); + Assert.AreEqual(long.MinValue + 1, reader.ReadInt64BigEndian()); + CollectionAssert.AreEqual(new ushort[] { 1, 0xFFFF }, reader.ReadUInt16ArrayBigEndian(2)); + Assert.AreEqual(29L, reader.TotalBytesRead); + } + + [TestMethod] + public void ReadPastEnd_ThrowsEndOfStream() + { + using var reader = Reader(0x01, 0x02, 0x03); + + reader.ReadUInt16BigEndian(); + Assert.ThrowsExactly(() => reader.ReadUInt16BigEndian()); + } + + [TestMethod] + public void ReadBudget_AppliesToNumberReads() + { + using var reader = Reader(0, 1, 0, 2, 0, 3, 0, 4); + + reader.SetReadBudget(4); + reader.ReadUInt16BigEndian(); + reader.ReadUInt16BigEndian(); + Assert.ThrowsExactly(() => reader.ReadUInt16BigEndian()); + + reader.ClearReadBudget(); + Assert.AreEqual((ushort)3, reader.ReadUInt16BigEndian()); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Reading/TtfReadingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Reading/TtfReadingTests.cs index 81f1725eaf..3157d1b3a0 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Reading/TtfReadingTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Reading/TtfReadingTests.cs @@ -33,7 +33,9 @@ public void ReadRobotoRegularTtf() var cmap = font.CmapTable; Assert.AreEqual("Roboto", font.FullName); Assert.AreEqual("Regular", font.SubFamily); - Assert.AreEqual(1295, font.GlyfTable.Glyphs.Count); + // One glyph per maxp.numGlyphs (loca has one more offset than there are glyphs). + Assert.AreEqual(1294, font.GlyfTable.Glyphs.Count); + Assert.AreEqual(font.MaxpTable.numGlyphs, font.GlyfTable.Glyphs.Count); } [TestMethod] diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/CffSubsettingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/CffSubsettingTests.cs new file mode 100644 index 0000000000..8d9c6bec60 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/CffSubsettingTests.cs @@ -0,0 +1,63 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Subsetting fonts with CFF outlines + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Subsetting; +using System; +using System.Collections.Generic; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Only fonts with TrueType outlines (glyf) can be subset. A font with CFF outlines must be + /// rejected with a NotSupportedException, not fail inside the subsetter. + /// + [TestClass] + public class CffSubsettingTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private OpenTypeFont LoadCffFont() + { + return new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, "SourceSans3-Regular.otf"))); + } + + [TestMethod] + public void CreateSubset_CffFont_ThrowsNotSupported() + { + var font = LoadCffFont(); + + var ex = Assert.ThrowsExactly(() => font.CreateSubset("Hello")); + StringAssert.Contains(ex.Message, "CFF"); + } + + [TestMethod] + public void SubsetFontBuilder_CffFont_ThrowsNotSupported() + { + var font = LoadCffFont(); + + Assert.ThrowsExactly( + () => new SubsetFontBuilder().CreateSubset(font, new[] { (int)'H', (int)'i' })); + } + + [TestMethod] + public void SingleFontSubsetter_CffFont_ReturnsOriginalFont() + { + // The PDF export embeds the whole font when it cannot be subset. + var font = LoadCffFont(); + + var result = new SingleFontSubsetter().Subset(font, new HashSet { 'H', 'i' }, true); + + Assert.AreSame(font, result); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/LazyGlyfTableTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/LazyGlyfTableTests.cs new file mode 100644 index 0000000000..cc8b072c36 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/LazyGlyfTableTests.cs @@ -0,0 +1,175 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Tests for glyphs parsed on first access + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Glyph; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace EPPlus.Fonts.OpenType.Tests.Tables +{ + /// + /// Tests that the glyf table of a font read from data parses each glyph on first access, + /// gives the same result as reading all glyphs, and is safe to read from several threads. + /// + [TestClass] + public class LazyGlyfTableTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private static OpenTypeFont ReadFont(string fileName) + { + return new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName))); + } + + private static byte[] GlyphBytes(Glyph glyph) + { + if (glyph == null) + return null; + + using (var ms = new MemoryStream()) + using (var writer = new FontsBinaryWriter(ms)) + { + glyph.Serialize(writer); + writer.Flush(); + return ms.ToArray(); + } + } + + [TestMethod] + public void LoadFont_ParsesNoGlyphs() + { + var font = ReadFont("Roboto-Regular.ttf"); + + Assert.IsNotNull(font.GlyfTable); + Assert.AreEqual(0, font.GlyfTable.ParsedGlyphCount); + } + + [DataTestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("BIZUDGothic-Regular.ttf")] + public void GlyphCount_EqualsMaxpNumGlyphs(string fileName) + { + var font = ReadFont(fileName); + + Assert.AreEqual(font.MaxpTable.numGlyphs, font.GlyfTable.Glyphs.Count); + Assert.AreEqual(0, font.GlyfTable.ParsedGlyphCount, "Count must not parse glyphs."); + } + + [DataTestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("BIZUDGothic-Regular.ttf")] + public void GetGlyph_GivesSameGlyphsAsEnumeration(string fileName) + { + // Enumeration parses in order with one shared reader; GetGlyph parses each glyph with its own reader. + var enumerated = ReadFont(fileName).GlyfTable.Glyphs.Select(GlyphBytes).ToList(); + + var glyf = ReadFont(fileName).GlyfTable; + for (int id = enumerated.Count - 1; id >= 0; id--) + { + var single = GlyphBytes(glyf.GetGlyph((ushort)id)); + if (enumerated[id] == null) + Assert.IsNull(single, "Glyph " + id); + else + CollectionAssert.AreEqual(enumerated[id], single, "Glyph " + id); + } + } + + [TestMethod] + public void GetGlyph_ReturnsSameInstanceAsGlyphs() + { + var glyf = ReadFont("Roboto-Regular.ttf").GlyfTable; + + var a = glyf.GetGlyph(37); // 'A' + Assert.IsNotNull(a); + Assert.AreSame(a, glyf.Glyphs[37]); + Assert.AreEqual(1, glyf.ParsedGlyphCount, "A glyph that is already parsed must not be parsed again."); + + // Enumeration parses the glyphs before it, but must reuse the one already parsed. + Assert.AreSame(a, glyf.Glyphs.ElementAt(37)); + } + + [TestMethod] + public void GetGlyph_OutOfRange_ReturnsNull() + { + var glyf = ReadFont("Roboto-Regular.ttf").GlyfTable; + + Assert.IsNull(glyf.GetGlyph(ushort.MaxValue)); + Assert.IsNull(glyf.GetGlyph((ushort)glyf.Glyphs.Count)); + } + + [TestMethod] + public void SmallSubsetOfLargeFont_ParsesOnlyUsedGlyphs() + { + var font = ReadFont("BIZUDGothic-Regular.ttf"); + Assert.IsTrue(font.GlyfTable.Glyphs.Count > 10000, "Sanity check: the font must be large."); + + var subset = font.CreateSubset("Hej 日本語"); + + Assert.IsNotNull(subset); + Assert.IsTrue(font.GlyfTable.ParsedGlyphCount < 50, + "Expected only the used glyphs and their components to be parsed, but " + + font.GlyfTable.ParsedGlyphCount + " were parsed."); + } + + [TestMethod] + public void SubsetFromLazyFont_EqualsSubsetFromFullyParsedFont() + { + const string Text = "Hello Åäö, fine 123"; + var lazy = ReadFont("Roboto-Regular.ttf"); + var full = ReadFont("Roboto-Regular.ttf"); + full.GlyfTable.Glyphs.ToList(); // Parse every glyph first. + + CollectionAssert.AreEqual(full.CreateSubset(Text).Serialize(), lazy.CreateSubset(Text).Serialize()); + } + + [TestMethod] + public void GetGlyph_FromManyThreads_AllGetSameInstances() + { + var glyf = ReadFont("EBGaramond-Regular.ttf").GlyfTable; + int count = glyf.Glyphs.Count; + const int Threads = 8; + + var results = new Glyph[Threads][]; + Parallel.For(0, Threads, new ParallelOptions { MaxDegreeOfParallelism = Threads }, t => + { + var glyphs = new Glyph[count]; + // Different start points and directions so threads race on the same glyphs. + for (int n = 0; n < count; n++) + { + int id = t % 2 == 0 ? (n + t * 97) % count : count - 1 - ((n + t * 97) % count); + glyphs[id] = glyf.GetGlyph((ushort)id); + } + results[t] = glyphs; + }); + + for (int id = 0; id < count; id++) + { + for (int t = 1; t < Threads; t++) + Assert.AreSame(results[0][id], results[t][id], "Glyph " + id + ", thread " + t); + Assert.AreSame(results[0][id], glyf.Glyphs[id], "Glyph " + id); + } + } + + [TestMethod] + public void Glyphs_IsReadOnly() + { + var glyf = ReadFont("Roboto-Regular.ttf").GlyfTable; + + Assert.IsNotInstanceOfType(glyf.Glyphs, typeof(ICollection)); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs index d9c4d942ec..821d315c36 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 11/30/2026 EPPlus Software AB Tests for malformed PairPos format 2 class matrices + 12/04/2026 EPPlus Software AB Cells with equal values share one record *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType2; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -87,5 +88,63 @@ public void Deserialize_ValidSmallMatrix_ReadsValues() Assert.AreEqual((short)30, table.ClassMatrix[1, 0].Value1.XAdvance); Assert.AreEqual((short)40, table.ClassMatrix[1, 1].Value1.XAdvance); } + + [TestMethod] + public void Deserialize_EqualCells_ShareOneRecord() + { + var bytes = BuildSubtable(ValueFormatXAdvance, 0, 2, 3, + 0, -50, 0, + -50, 0, 10); + + var table = Deserialize(bytes); + var m = table.ClassMatrix; + + Assert.AreSame(m[0, 0], m[0, 2]); + Assert.AreSame(m[0, 0], m[1, 1]); + Assert.AreSame(m[0, 1], m[1, 0]); + Assert.AreNotSame(m[0, 0], m[0, 1]); + Assert.AreNotSame(m[0, 0], m[1, 2]); + + Assert.AreEqual((short)0, m[0, 0].Value1.XAdvance); + Assert.AreEqual((short)-50, m[0, 1].Value1.XAdvance); + Assert.AreEqual((short)10, m[1, 2].Value1.XAdvance); + } + + [TestMethod] + public void Deserialize_CellsDifferingOnlyInOneField_AreNotShared() + { + // All eight fields in Value1 and XAdvance in Value2. Each cell differs from the first + // in exactly one field, so no two cells may share a record. + const ushort AllFields = 0x00FF; + var cells = new List(); + short[] baseCell = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + cells.AddRange(baseCell); + for (int field = 0; field < baseCell.Length; field++) + { + var cell = (short[])baseCell.Clone(); + cell[field] += 100; + cells.AddRange(cell); + } + + var bytes = BuildSubtable(AllFields, ValueFormatXAdvance, 1, (ushort)(baseCell.Length + 1), cells.ToArray()); + var table = Deserialize(bytes); + + for (int a = 0; a < table.Class2Count; a++) + for (int b = a + 1; b < table.Class2Count; b++) + Assert.AreNotSame(table.ClassMatrix[0, a], table.ClassMatrix[0, b], "Cells " + a + " and " + b); + + var first = table.ClassMatrix[0, 0]; + Assert.AreEqual((short)1, first.Value1.XPlacement); + Assert.AreEqual((short)2, first.Value1.YPlacement); + Assert.AreEqual((short)3, first.Value1.XAdvance); + Assert.AreEqual((short)4, first.Value1.YAdvance); + Assert.AreEqual((ushort)5, first.Value1.XPlacementDeviceOffset); + Assert.AreEqual((ushort)6, first.Value1.YPlacementDeviceOffset); + Assert.AreEqual((ushort)7, first.Value1.XAdvanceDeviceOffset); + Assert.AreEqual((ushort)8, first.Value1.YAdvanceDeviceOffset); + Assert.AreEqual((short)9, first.Value2.XAdvance); + Assert.AreEqual((ushort)106, table.ClassMatrix[0, 6].Value1.YPlacementDeviceOffset); + Assert.AreEqual((short)109, table.ClassMatrix[0, 9].Value2.XAdvance); + } } } diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/Kerning/KernPairLookupTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/Kerning/KernPairLookupTests.cs new file mode 100644 index 0000000000..c9f9f61f1d --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/Kerning/KernPairLookupTests.cs @@ -0,0 +1,131 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Tests for the shared kern pair lookup + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Kern; +using EPPlus.Fonts.OpenType.TextShaping.Kerning; +using System.Collections.Generic; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.TextShaping.Kerning +{ + [TestClass] + public class KernPairLookupTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + [TestMethod] + public void Lookup_MatchesDictionaryRule_ForManyPairs() + { + // Overlapping pairs and zero values across three subtables. Only the subtable format + // is checked, not the horizontal bit, as before. No font in the test folder has a + // kern table, so the table is built here. + var rnd = new System.Random(7); + var table = new KernTable(); + table.SubTables.Add(Subtable(0x0001, RandomPairs(rnd, 3000))); + table.SubTables.Add(Subtable(0x0001, RandomPairs(rnd, 3000))); + table.SubTables.Add(Subtable(0x0000, RandomPairs(rnd, 500))); + + var expected = ExpectedPairs(table); + var provider = new LegacyKerningProvider(table); + + Assert.AreEqual(expected.Count, table.GetPairLookup().Count); + for (int left = 0; left < 64; left++) + { + for (int right = 0; right < 64; right++) + { + expected.TryGetValue(((uint)left << 16) | (uint)right, out short value); + Assert.AreEqual(value, provider.GetKerning((ushort)left, (ushort)right), left + "/" + right); + } + } + } + + private static KerningPair[] RandomPairs(System.Random rnd, int count) + { + var pairs = new KerningPair[count]; + for (int i = 0; i < count; i++) + { + pairs[i] = new KerningPair(null) + { + left = (ushort)rnd.Next(64), + right = (ushort)rnd.Next(64), + value = (short)(rnd.Next(5) == 0 ? 0 : rnd.Next(-200, 200)) + }; + } + return pairs; + } + + [TestMethod] + public void Lookup_IsBuiltOncePerTable() + { + var table = TableWithPairs(new KerningPair(null) { left = 1, right = 2, value = -40 }); + + Assert.AreSame(table.GetPairLookup(), table.GetPairLookup()); + Assert.AreEqual((short)-40, new LegacyKerningProvider(table).GetKerning(1, 2)); + } + + [TestMethod] + public void Lookup_LastNonZeroValueWins_ZeroValuesIgnored() + { + var table = TableWithPairs( + new KerningPair(null) { left = 1, right = 2, value = -40 }, + new KerningPair(null) { left = 1, right = 2, value = -10 }, + new KerningPair(null) { left = 1, right = 2, value = 0 }, + new KerningPair(null) { left = 3, right = 4, value = 0 }); + var provider = new LegacyKerningProvider(table); + + Assert.AreEqual((short)-10, provider.GetKerning(1, 2)); + Assert.AreEqual((short)0, provider.GetKerning(3, 4)); + Assert.AreEqual((short)0, provider.GetKerning(2, 1)); + Assert.AreEqual(1, table.GetPairLookup().Count); + } + + /// + /// The rule of the dictionary LegacyKerningProvider used to build for every shaper: + /// Format 0 subtables in order, zero values skipped, the last value wins. + /// + private static Dictionary ExpectedPairs(KernTable kern) + { + var pairs = new Dictionary(); + foreach (var subtable in kern.SubTables) + { + if (subtable.coverage.Format != 0 || subtable.Format0Subtable?.Pairs == null) + continue; + foreach (var pair in subtable.Format0Subtable.Pairs) + { + if (pair.value != 0) + pairs[((uint)pair.left << 16) | pair.right] = pair.value; + } + } + return pairs; + } + + private static KernTable TableWithPairs(params KerningPair[] pairs) + { + var table = new KernTable(); + table.SubTables.Add(Subtable(0x0001, pairs)); + return table; + } + + /// + /// A Format 0 subtable. Coverage 0x0001 is horizontal, 0x0000 vertical; both are format 0. + /// + private static KernSubTable Subtable(ushort coverage, KerningPair[] pairs) + { + var bytes = new byte[] { (byte)(coverage >> 8), (byte)coverage }; + return new KernSubTable + { + coverage = new KernCoverage(new FontsBinaryReader(new MemoryStream(bytes))), + Format0Subtable = new KernSubTableFormat0(null) { nPairs = (ushort)pairs.Length, Pairs = pairs } + }; + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MarkToBasePositioningTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MarkToBasePositioningTests.cs index f67c7210db..73bc562651 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MarkToBasePositioningTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MarkToBasePositioningTests.cs @@ -156,7 +156,9 @@ public void MarkOffset_UsesKernedAdvance_NotRawAdvance() // Simulate a kern pair having tightened the base advance by 30 font units. const short kerning = -30; - glyphs[0].XAdvance = (short)(glyphs[0].XAdvance + kerning); + var kernedBase = glyphs[0]; + kernedBase.XAdvance = (short)(kernedBase.XAdvance + kerning); + glyphs[0] = kernedBase; new MarkToBaseProvider(font!).ApplyMarkPositioning(glyphs, "latn", null); diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptAwareKerningAndMarkTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptAwareKerningAndMarkTests.cs index 8e4e15cf97..44fe24d28c 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptAwareKerningAndMarkTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptAwareKerningAndMarkTests.cs @@ -85,6 +85,34 @@ public void MarkPositioning_ForLatinScript_DoesNotPickUpArabicOnlyOffset() + "reachable through the 'arab' script's LangSys"); } + [TestMethod] + public void MarkPositioning_SameProvider_ResolvesEachScriptSeparately() + { + var font = TestFolderEngine.LoadFont("BIZUDGothic", FontSubFamily.Regular, ignoreCache: true); + Assert.IsNotNull(font, "BIZUDGothic must be present in the test font folder"); + + font.AddOrReplaceTable(BuildMarkGposTable()); + + // The active subtables are cached per script, so one provider is used for all calls. + var provider = new MarkToBaseProvider(font); + + Assert.AreEqual(0, PositionMark(provider, "latn"), "latn before arab"); + Assert.AreNotEqual(0, PositionMark(provider, "arab"), "arab"); + Assert.AreEqual(0, PositionMark(provider, "latn"), "latn after arab"); + } + + private static int PositionMark(MarkToBaseProvider provider, string script) + { + var glyphs = new List + { + new ShapedGlyph { GlyphId = GlyphA, XAdvance = 500, BaseAdvance = 500 }, + new ShapedGlyph { GlyphId = MarkGlyph, XAdvance = 0, BaseAdvance = 0 } + }; + + provider.ApplyMarkPositioning(glyphs, script, null); + return glyphs[1].YOffset; + } + /// /// Two "kern" FeatureRecords: index 0 -> 'latn', covers a pair NOT involving A/B. /// Index 1 -> 'arab', covers A+B with a large adjustment. Index 1 is last, so it is the diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptLanguageKeyTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptLanguageKeyTests.cs new file mode 100644 index 0000000000..c38b4c3047 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ScriptLanguageKeyTests.cs @@ -0,0 +1,49 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Tests for script/language cache keys + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.TextShaping; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.Tests.TextShaping +{ + [TestClass] + public class ScriptLanguageKeyTests + { + [TestMethod] + public void NullAndEmptyAreTheSameKey() + { + Assert.AreEqual(new ScriptLanguageKey(null, null), new ScriptLanguageKey("", "")); + Assert.AreEqual(new ScriptLanguageKey("latn", null), new ScriptLanguageKey("latn", "")); + Assert.AreEqual(new ScriptLanguageKey("latn", null).GetHashCode(), new ScriptLanguageKey("latn", "").GetHashCode()); + } + + [TestMethod] + public void DifferentPartsAreDifferentKeys() + { + var keys = new HashSet + { + new ScriptLanguageKey("latn", null), + new ScriptLanguageKey("latn", "TRK "), + new ScriptLanguageKey("arab", null), + new ScriptLanguageKey("liga", "latn", null), + new ScriptLanguageKey("calt", "latn", null), + // Concatenated keys could collide on the separator; these must not. + new ScriptLanguageKey("a|b", "c"), + new ScriptLanguageKey("a", "b|c"), + }; + + Assert.AreEqual(7, keys.Count); + Assert.IsTrue(keys.Contains(new ScriptLanguageKey("liga", "latn", ""))); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs b/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs index 970438b046..325b675ffc 100644 --- a/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs +++ b/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs @@ -1,4 +1,4 @@ -/************************************************************************************************* +/************************************************************************************************* Required Notice: Copyright (C) EPPlus Software AB. This software is licensed under PolyForm Noncommercial License 1.0.0 and may only be used for noncommercial purposes @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + 12/04/2026 EPPlus Software AB Big-endian reads without allocations *************************************************************************************************/ using System; using System.IO; @@ -67,43 +68,69 @@ private void CheckReadBudget(int count) throw new FontReadBudgetExceededException(_readBudget); } + /// Holds the bytes of one big-endian value, so reading a number allocates nothing. + private readonly byte[] _valueBuffer = new byte[8]; + + /// + /// Reads exactly bytes into the value buffer, with the same read budget + /// and byte count as . + /// + /// Fewer than bytes remain. + private byte[] ReadValueBytes(int count) + { + CheckReadBudget(count); + int read = 0; + while (read < count) + { + int n = BaseStream.Read(_valueBuffer, read, count - read); + if (n <= 0) + { + _totalBytesRead += read; + throw new EndOfStreamException("Unexpected end of font data."); + } + read += n; + } + _totalBytesRead += count; + return _valueBuffer; + } + internal ushort ReadUInt16BigEndian() { - var b = ReadBytes(2); - return BitConverter.ToUInt16(new byte[] { b[1], b[0] }, 0); + var b = ReadValueBytes(2); + return (ushort)((b[0] << 8) | b[1]); } + internal short ReadInt16BigEndian() { - var b = ReadBytes(2); - return BitConverter.ToInt16(new byte[] { b[1], b[0] }, 0); + var b = ReadValueBytes(2); + return (short)((b[0] << 8) | b[1]); } internal uint ReadUInt24BigEndian() { - var b = ReadBytes(3); + var b = ReadValueBytes(3); return (uint)((b[0] << 16) | (b[1] << 8) | b[2]); } - internal int ReadInt32BigEndian() { - var b = ReadBytes(4); - return BitConverter.ToInt32(new byte[] { b[3], b[2], b[1], b[0] }, 0); + var b = ReadValueBytes(4); + return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; } internal uint ReadUInt32BigEndian() { - var b = ReadBytes(4); - return BitConverter.ToUInt32(new byte[] { b[3], b[2], b[1], b[0] }, 0); + return unchecked((uint)ReadInt32BigEndian()); } internal long ReadInt64BigEndian() { - var b = ReadBytes(8); - return BitConverter.ToInt64(new byte[] { b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0] }, 0); + var b = ReadValueBytes(8); + uint high = (uint)((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]); + uint low = (uint)((b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7]); + return unchecked((long)(((ulong)high << 32) | low)); } - internal ushort[] ReadUInt16ArrayBigEndian(int count) { var result = new ushort[count]; diff --git a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs index f496c17be4..155f2c52b9 100644 --- a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs +++ b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs @@ -126,7 +126,7 @@ public TextLineCollection BuildVerticalLineCollection(List fr if (string.IsNullOrEmpty(fragment.Text)) continue; var shaper = GetShaperForFont((IFontFormatBase)fragment.RichTextOptions); - var options = fragment.Options ?? ShapingOptions.Default; + var options = fragment.Options ?? DefaultOptions; int len = fragment.Text.Length; var charWidths = GetCharWidthBuffer(len); @@ -349,7 +349,7 @@ private void ProcessFragment( { state.CharIdxRt = 0; var shaper = GetShaperForFont((IFontFormatBase)fragment.RichTextOptions); - var options = fragment.Options ?? ShapingOptions.Default; + var options = fragment.Options ?? DefaultOptions; int len = fragment.Text.Length; var charWidths = GetCharWidthBuffer(len); Array.Clear(charWidths, 0, len); diff --git a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.cs b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.cs index 4022c58ac6..07a3574f39 100644 --- a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.cs +++ b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.cs @@ -42,6 +42,20 @@ public partial class TextLayoutEngine : IDisposable // ArrayPool buffer - only ONE buffer for entire class private double[] _charWidthBuffer = null; + + // ShapingOptions.Default creates a new instance with two new lists on every access. Layout + // never modifies the options, so one instance per engine is used when the caller gives none. + private ShapingOptions _defaultOptions; + + private ShapingOptions DefaultOptions + { + get + { + if (_defaultOptions == null) + _defaultOptions = ShapingOptions.Default; + return _defaultOptions; + } + } private int _charWidthBufferCapacity = 0; // StringBuilder pooling - reuse between wrapping operations @@ -145,7 +159,7 @@ public List WrapText( return new List { string.Empty }; } - options = options ?? ShapingOptions.Default; + options = options ?? DefaultOptions; var lines = new List(); var paragraphs = text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs index 67e8371c8a..7274fcb165 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + 12/04/2026 EPPlus Software AB English name lookup in one pass without allocating *************************************************************************************************/ using EPPlus.Fonts.OpenType.FontValidation; using EPPlus.Fonts.OpenType.Integration; @@ -221,10 +222,11 @@ internal void EnsureFullyLoaded() { var gpos = GposTable; // Forces full GPOS parse (incl. MarkToBase subtables) } - if (_glyfTableLoader != null) - { - var glyf = GlyfTable; // Forces full glyph outline parse - } + // glyf is not loaded here. Glyph outlines are only needed for subsetting and + // embedding, while measuring and shaping use cmap, hmtx, GSUB, GPOS and kern. + // Parsing all outlines costs several MB per font (over 100 MB for large CJK fonts). + // GlyfTable loads on first access through its TableLoader, which serializes reader + // access with the same font-level lock, and the table is never modified after loading. if (_kernTableLoader != null) { var kern = KernTable; // Forces legacy kern table parse @@ -611,45 +613,53 @@ public string GetEnglishFontSubFamilyName() private string GetNameString(NameRecordTypes recordType) { - // Priority 1: Windows English (Platform 3, Language 0x0409) - var windowsEnglish = NameTable.NameRecords.FirstOrDefault(x => - x.platformId == 3 && - x.languageID == 0x0409 && - x.RecordType == recordType); + // One pass over the records, without allocating. For each priority the FIRST record + // that matches it is used, and its name only if not empty; otherwise the next priority + // is tried: + // 1. Windows English (platform 3, language 0x0409) + // 2. Mac English (platform 1, language 0) + // 3. Unicode English (platform 0, language 0) + // 4. Any Windows record (platform 3) + // 5. Any record, even with an empty name + NameRecord windowsEnglish = null, macEnglish = null, unicodeEnglish = null, anyWindows = null, any = null; + var records = NameTable.NameRecords; + for (int i = 0; i < records.Length; i++) + { + var record = records[i]; + if (record.RecordType != recordType) + continue; - if (windowsEnglish != null && !string.IsNullOrEmpty(windowsEnglish.Name)) - return windowsEnglish.Name; + if (any == null) + any = record; - // Priority 2: Mac English (Platform 1, Language 0) - var macEnglish = NameTable.NameRecords.FirstOrDefault(x => - x.platformId == 1 && - x.languageID == 0 && - x.RecordType == recordType); + if (record.platformId == 3) + { + if (anyWindows == null) + anyWindows = record; + if (windowsEnglish == null && record.languageID == 0x0409) + windowsEnglish = record; + } + else if (record.platformId == 1) + { + if (macEnglish == null && record.languageID == 0) + macEnglish = record; + } + else if (record.platformId == 0) + { + if (unicodeEnglish == null && record.languageID == 0) + unicodeEnglish = record; + } + } + if (windowsEnglish != null && !string.IsNullOrEmpty(windowsEnglish.Name)) + return windowsEnglish.Name; if (macEnglish != null && !string.IsNullOrEmpty(macEnglish.Name)) return macEnglish.Name; - - // Priority 3: Unicode English (Platform 0, Language 0) - var unicodeEnglish = NameTable.NameRecords.FirstOrDefault(x => - x.platformId == 0 && - x.languageID == 0 && - x.RecordType == recordType); - if (unicodeEnglish != null && !string.IsNullOrEmpty(unicodeEnglish.Name)) return unicodeEnglish.Name; - - // Priority 4: ANY Windows record of this type (fallback) - var anyWindows = NameTable.NameRecords.FirstOrDefault(x => - x.platformId == 3 && - x.RecordType == recordType); - if (anyWindows != null && !string.IsNullOrEmpty(anyWindows.Name)) return anyWindows.Name; - // Priority 5: ANY record of this type (last resort) - var any = NameTable.NameRecords.FirstOrDefault(x => - x.RecordType == recordType); - return any?.Name ?? string.Empty; } diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs index 16ded96503..f53cbf607e 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs @@ -10,8 +10,10 @@ Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 12/03/2026 EPPlus Software AB Pass the layout subsetting work limit + 12/04/2026 EPPlus Software AB NotSupportedException for fonts without glyf outlines *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting.Processors; +using EPPlus.Fonts.OpenType.Tables; using System; using System.Collections.Generic; using System.Linq; @@ -71,8 +73,17 @@ public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable uni /// Creates a subset, see , with /// the given limit for subsetting GSUB and GPOS, see . /// + /// + /// The font has no TrueType outlines (glyf and loca), for example a font with CFF or CFF2 + /// outlines. Only TrueType outlines can be subset. + /// internal OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable unicodeChars, bool removeHinting, long maxLayoutSubsetWork) { + if (originalFont == null) + throw new ArgumentNullException(nameof(originalFont)); + + EnsureTrueTypeOutlines(originalFont); + var context = new FontSubsettingContext(originalFont, unicodeChars); context.RemoveHinting = removeHinting; context.MaxLayoutSubsetWork = maxLayoutSubsetWork; @@ -100,6 +111,21 @@ internal OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable u return context.SubsetFont; } + private static void EnsureTrueTypeOutlines(OpenTypeFont font) + { + var tables = font.TableRecords; + if (tables.ContainsKey(TableNames.Glyf) && tables.ContainsKey(TableNames.Loca)) + return; + + string outlines = tables.ContainsKey(TableNames.Cff2) ? "CFF2" + : tables.ContainsKey(TableNames.Cff) ? "CFF" + : null; + + throw new NotSupportedException(outlines != null + ? string.Format("Font '{0}' has {1} outlines. Only fonts with TrueType outlines (glyf) can be subset.", font.GetEnglishFontFamilyName(), outlines) + : string.Format("Font '{0}' has no glyf and loca tables. Only fonts with TrueType outlines (glyf) can be subset.", font.GetEnglishFontFamilyName())); + } + // Creates a deterministic mapping between old and new Glyph IDs. private void BuildGlyphMapping(FontSubsettingContext context) { diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs index 279b2350fd..a85e6f5850 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs @@ -1,7 +1,7 @@ /************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes https://polyformproject.org/licenses/noncommercial/1.0.0/ A commercial license to use this software can be purchased at https://epplussoftware.com @@ -10,14 +10,15 @@ Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 12/03/2026 EPPlus Software AB Composite glyph closure examines each glyph once + 12/04/2026 EPPlus Software AB Glyphs are read one at a time on first access *************************************************************************************************/ -using EPPlus.Fonts.OpenType.Tables.Loca; +using EPPlus.Fonts.OpenType.Tables.Glyph.Serialization; using EPPlus.Fonts.OpenType.Tables.Post; using System; +using System.Collections; using System.Collections.Generic; using System.IO; -using System.Linq; -using static System.Net.Mime.MediaTypeNames; +using System.Threading; namespace EPPlus.Fonts.OpenType.Tables.Glyph { @@ -25,65 +26,165 @@ namespace EPPlus.Fonts.OpenType.Tables.Glyph /// This table contains information that describes the glyphs in the font in the TrueType outline format /// https://docs.microsoft.com/en-us/typography/opentype/spec/glyf /// + /// + /// For a font read from data, each glyph is parsed the first time it is accessed and then kept. + /// Measuring and subsetting only touch the glyphs they use, so a large font (for example a CJK + /// font with tens of thousands of glyphs) is never parsed in full unless all glyphs are enumerated. + /// The table is safe to read from several threads: each first-time read uses its own reader over + /// the immutable font data, and the parsed glyph is published atomically, so all callers get the + /// same instance. + /// public class GlyfTable : FontTableBase { - internal GlyfTable(TableLoaderSettings settings) + /// Stored in a slot whose glyph was read and is empty or malformed, so it is not read again. + private static readonly object NoGlyph = new object(); + + // Font read from data: glyphs are read on first access. + private readonly FontTableReaderFactory _readerFactory; + private readonly long _glyfOffset; + private readonly uint _glyfLength; + private readonly uint[] _locaOffsets; + private readonly object[] _slots; + private int _parsedGlyphCount; + + // Table built in memory (e.g. a subset): glyphs are given as a list. + private readonly List _glyphList; + + private readonly GlyphCollection _glyphs; + + /// + /// Creates a table that reads glyphs from the font data on first access. + /// + /// Creates readers over the font data. + /// Offset of the glyf table in the font data. + /// Length of the glyf table according to the table directory. + /// The loca offsets, one more than the number of glyphs. + internal GlyfTable(FontTableReaderFactory readerFactory, uint glyfOffset, uint glyfLength, uint[] locaOffsets) { - _tableLoaderSettings = settings; + _readerFactory = readerFactory ?? throw new ArgumentNullException(nameof(readerFactory)); + _glyfOffset = glyfOffset; + _glyfLength = glyfLength; + _locaOffsets = locaOffsets ?? new uint[0]; + _slots = new object[_locaOffsets.Length > 0 ? _locaOffsets.Length - 1 : 0]; + _glyphs = new GlyphCollection(this); } internal GlyfTable(List glyphs) { - Glyphs = glyphs ?? new List(); + _glyphList = glyphs ?? new List(); + _glyphs = new GlyphCollection(this); } - private readonly TableLoaderSettings _tableLoaderSettings; - public override string Name => TableNames.Glyf; public override bool IsEssentialTable => true; /// - /// All glyphs in the font, indexed by glyph ID. + /// All glyphs in the font, indexed by glyph ID. An empty glyph (for example a space) is null. + /// For a font read from data, glyphs are parsed as they are accessed: enumerating the whole + /// list parses every glyph, so use when only some are needed. + /// + public IReadOnlyList Glyphs => _glyphs; + + private bool ReadsFromFontData => _slots != null; + + private int GlyphCount => ReadsFromFontData ? _slots.Length : _glyphList.Count; + + /// Number of glyphs parsed from the font data so far (for tests and diagnostics). + internal int ParsedGlyphCount => Volatile.Read(ref _parsedGlyphCount); + + /// + /// Returns the glyph with the given ID, or null if the glyph is empty, malformed or out of range. /// - public List Glyphs { get; set; } + public Glyph GetGlyph(ushort glyphId) + { + if (glyphId >= GlyphCount) + return null; + + return GetGlyphAt(glyphId, null); + } + + /// A valid glyph index. + /// A reader to parse with, or null to create one for this call. + /// A shared reader must only be used by one thread. + private Glyph GetGlyphAt(int index, FontsBinaryReader sharedReader) + { + if (!ReadsFromFontData) + return _glyphList[index]; + + object slot = Volatile.Read(ref _slots[index]); + if (slot == null) + { + object parsed = (object)ReadGlyph(index, sharedReader) ?? NoGlyph; + // If another thread stored the glyph first, use its instance. + slot = Interlocked.CompareExchange(ref _slots[index], parsed, null) ?? parsed; + } + return slot as Glyph; + } + + private Glyph ReadGlyph(int index, FontsBinaryReader sharedReader) + { + uint start = _locaOffsets[index]; + uint end = _locaOffsets[index + 1]; + + if (start == end) + return null; + + // Spec: loca offsets must be ascending and point inside the glyf table. + // A malformed entry is treated as an empty glyph. + if (end < start || end > _glyfLength) + return null; + + Interlocked.Increment(ref _parsedGlyphCount); + + FontsBinaryReader reader = sharedReader ?? _readerFactory.CreateReader(); + try + { + reader.BaseStream.Position = _glyfOffset + start; + return GlyphDeserializer.Deserialize(reader, _glyfOffset + end); + } + catch (InvalidDataException) + { + // The glyph data does not fit within its loca range - treat as empty glyph. + return null; + } + finally + { + if (sharedReader == null) + reader.Dispose(); + } + } internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializationContext context) { - if (Glyphs == null || Glyphs.Count == 0) + int count = GlyphCount; + if (count == 0) return; - if (_tableLoaderSettings != null) + if (ReadsFromFontData) { - // Originalfont: use locaOffsets from loader - var locaOffsets = TableLoaders.GetLocaTableLoader(_tableLoaderSettings).Load().Offsets; - for (int i = 0; i < Glyphs.Count; i++) + // Font read from data: keep the original glyph positions by padding each glyph to its loca length. + using (var reader = _readerFactory.CreateReader()) { - long glyphStart = writer.BaseStream.Position; - Glyph glyph = Glyphs[i]; - - if (glyph != null) - glyph.Serialize(writer); + for (int i = 0; i < count; i++) + { + long glyphStart = writer.BaseStream.Position; + Glyph glyph = GetGlyphAt(i, reader); - long glyphEnd = writer.BaseStream.Position; - int writtenLength = (int)(glyphEnd - glyphStart); + if (glyph != null) + glyph.Serialize(writer); - if (i + 1 < locaOffsets.Count) - { - int expectedLength = (int)(locaOffsets[i + 1] - locaOffsets[i]); - if (expectedLength > writtenLength) - { - int padding = expectedLength - writtenLength; - for (int p = 0; p < padding; p++) - writer.Write((byte)0); - } + int writtenLength = (int)(writer.BaseStream.Position - glyphStart); + int expectedLength = (int)(_locaOffsets[i + 1] - _locaOffsets[i]); + for (int p = writtenLength; p < expectedLength; p++) + writer.Write((byte)0); } } } else { // Subset-font: align every glyph to 4 bytes - foreach (var glyph in Glyphs) + foreach (var glyph in _glyphList) { long start = writer.BaseStream.Position; glyph.Serialize(writer); @@ -99,21 +200,68 @@ internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializa internal override void Clear() { - Glyphs.Clear(); + if (ReadsFromFontData) + { + // The glyphs can be read again from the font data, so this only releases parsed glyphs. + for (int i = 0; i < _slots.Length; i++) + Volatile.Write(ref _slots[i], null); + } + else + { + _glyphList.Clear(); + } } - public Glyph GetGlyph(ushort glyphId) + /// + /// Read-only view of the glyphs. Reading an element parses that glyph if needed; enumerating + /// parses the glyphs in order with one reader. + /// + private sealed class GlyphCollection : IReadOnlyList { - if (Glyphs == null || glyphId >= Glyphs.Count) - return null; + private readonly GlyfTable _table; - return Glyphs[glyphId]; - } + internal GlyphCollection(GlyfTable table) + { + _table = table; + } + + public int Count => _table.GlyphCount; + + public Glyph this[int index] + { + get + { + if (index < 0 || index >= _table.GlyphCount) + throw new ArgumentOutOfRangeException(nameof(index)); + return _table.GetGlyphAt(index, null); + } + } + + public IEnumerator GetEnumerator() + { + if (!_table.ReadsFromFontData) + { + foreach (Glyph glyph in _table._glyphList) + yield return glyph; + yield break; + } + using (var reader = _table._readerFactory.CreateReader()) + { + for (int i = 0; i < _table._slots.Length; i++) + yield return _table.GetGlyphAt(i, reader); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } /// /// Recursively adds all component glyph IDs used by composite glyphs in the given set. - /// Uses GetGlyph() to ensure lazy-loaded glyphs are properly resolved. + /// Uses GetGlyph(), so only the glyphs in the set and their components are parsed. /// Critical for correct subsetting of fonts with composite glyphs (å, ä, ö, fi, fl, etc.). /// /// Set of glyph IDs to expand with component dependencies diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs index fc3dee0785..538b53ac55 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs @@ -9,64 +9,32 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + 12/04/2026 EPPlus Software AB Glyphs are parsed on first access *************************************************************************************************/ -using EPPlus.Fonts.OpenType.Tables.Glyph.Serialization; -using System.Collections.Generic; -using System.IO; using System.Linq; namespace EPPlus.Fonts.OpenType.Tables.Glyph { + /// + /// Creates the glyf table without parsing any glyphs. Each glyph is parsed on first access, + /// see . + /// internal class GlyfTableLoader : TableLoader { private readonly uint[] _glyphOffsets; - private readonly BoundingRectangle _emptyGlyph; + private readonly TableLoaderSettings _settings; public GlyfTableLoader(TableLoaderSettings settings) : base(settings, TableNames.Glyf) { _glyphOffsets = TableLoaders.GetLocaTableLoader(settings).Load().Offsets.ToArray(); - _emptyGlyph = TableLoaders.GetHeadTableLoader(settings).Load().GetDefaultBounds(); _settings = settings; } - - private readonly TableLoaderSettings _settings; - protected override GlyfTable LoadInternal() { - var glyphs = new Glyph[_glyphOffsets.Length]; - for (int i = 0; i < _glyphOffsets.Length - 1; i++) - { - var start = _glyphOffsets[i]; - var end = _glyphOffsets[i + 1]; - - if (start == end) - { - continue; - } - - // Spec: loca offsets must be ascending and point inside the glyf table. - // A malformed entry is treated as an empty glyph. - if (end < start || end > _length) - { - continue; - } - - long glyphEnd = (long)_offset + end; - _reader.BaseStream.Position = (long)_offset + start; - try - { - glyphs[i] = GlyphDeserializer.Deserialize(_reader, glyphEnd); - } - catch (InvalidDataException) - { - // The glyph data does not fit within its loca range - treat as empty glyph. - glyphs[i] = null; - } - } - return new GlyfTable(_settings) { Glyphs = new List(glyphs) }; + return new GlyfTable(_settings.TableReaderFactory, _offset, _length, _glyphOffsets); } } } diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat1Deserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat1Deserializer.cs index 59c02b07bd..f5537e7d17 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat1Deserializer.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat1Deserializer.cs @@ -68,8 +68,9 @@ public PairPosSubTableFormat1 Deserialize(long subtableStart) } } - // Read PairSets - table.PairSets = new List(); + // Read PairSets. Equal value records are shared across the subtable. + table.PairSets = new List(pairSetCount); + var pool = new ValueRecordPool(); for (int i = 0; i < pairSetCount; i++) { @@ -82,19 +83,19 @@ public PairPosSubTableFormat1 Deserialize(long subtableStart) long pairSetPos = subtableStart + pairSetOffsets[i]; _reader.BaseStream.Seek(pairSetPos, SeekOrigin.Begin); - var pairSet = ReadPairSet(table.ValueFormat1, table.ValueFormat2); + var pairSet = ReadPairSet(table.ValueFormat1, table.ValueFormat2, pool); table.PairSets.Add(pairSet); } return table; } - private PairSet ReadPairSet(ushort valueFormat1, ushort valueFormat2) + private PairSet ReadPairSet(ushort valueFormat1, ushort valueFormat2, ValueRecordPool pool) { var pairSet = new PairSet(); ushort pairValueCount = _reader.ReadUInt16BigEndian(); - pairSet.PairValueRecords = new List(); + pairSet.PairValueRecords = new List(pairValueCount); for (int i = 0; i < pairValueCount; i++) { @@ -104,10 +105,10 @@ private PairSet ReadPairSet(ushort valueFormat1, ushort valueFormat2) record.SecondGlyph = _reader.ReadUInt16BigEndian(); // Read Value1 (adjustments for first glyph) - record.Value1 = ValueRecord.Read(_reader, valueFormat1); + record.Value1 = pool.Read(_reader, valueFormat1); // Read Value2 (adjustments for second glyph) - record.Value2 = ValueRecord.Read(_reader, valueFormat2); + record.Value2 = pool.Read(_reader, valueFormat2); pairSet.PairValueRecords.Add(record); } diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs index 09f1837239..2c0e27ad41 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs @@ -63,21 +63,19 @@ public PairPosSubTableFormat2 Deserialize(long subtableStart) return null; } - // Read class matrix + // Read class matrix. Cells with equal values share one PairValueRecord: the matrix has + // one cell per class pair, but only a few distinct values (most cells are zero). table.ClassMatrix = new PairValueRecord[table.Class1Count, table.Class2Count]; + var pool = new ValueRecordPool(); for (int i = 0; i < table.Class1Count; i++) { for (int j = 0; j < table.Class2Count; j++) { - var value1 = ValueRecord.Read(_reader, table.ValueFormat1); - var value2 = ValueRecord.Read(_reader, table.ValueFormat2); - - table.ClassMatrix[i, j] = new PairValueRecord - { - Value1 = value1, - Value2 = value2 - }; + var value1 = pool.Read(_reader, table.ValueFormat1); + var value2 = pool.Read(_reader, table.ValueFormat2); + + table.ClassMatrix[i, j] = pool.GetPair(value1, value2); } } diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecordPool.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecordPool.cs new file mode 100644 index 0000000000..d31e09bea1 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecordPool.cs @@ -0,0 +1,163 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Shared value records when reading GPOS + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType2; +using System; +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups +{ + /// + /// Reads value records and returns one shared instance per distinct value, while one subtable + /// is read. A class kerning matrix has one cell per class pair (often tens of thousands), but + /// only a few hundred distinct values, and most cells are zero. Without sharing, every cell + /// cost three objects (about 130 bytes); with sharing it costs one reference. + /// + /// + /// The shared instances are part of a loaded (and possibly cached and shared) font, so they + /// must not be modified. Nothing in the library modifies a value record after reading it; + /// subsetting copies references. + /// + internal sealed class ValueRecordPool + { + private readonly Dictionary _records = new Dictionary(); + private readonly Dictionary _pairs = new Dictionary(); + + /// Number of distinct value records read so far (for tests and diagnostics). + internal int DistinctValueCount => _records.Count; + + /// + /// Reads a value record with the given format and returns the shared instance for its value. + /// + internal ValueRecord Read(FontsBinaryReader reader, ushort valueFormat) + { + short xPlacement = 0, yPlacement = 0, xAdvance = 0, yAdvance = 0; + ushort xPlaDevice = 0, yPlaDevice = 0, xAdvDevice = 0, yAdvDevice = 0; + + if ((valueFormat & (ushort)ValueFormatFlags.XPlacement) != 0) + xPlacement = reader.ReadInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.YPlacement) != 0) + yPlacement = reader.ReadInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.XAdvance) != 0) + xAdvance = reader.ReadInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.YAdvance) != 0) + yAdvance = reader.ReadInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.XPlacementDevice) != 0) + xPlaDevice = reader.ReadUInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.YPlacementDevice) != 0) + yPlaDevice = reader.ReadUInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.XAdvanceDevice) != 0) + xAdvDevice = reader.ReadUInt16BigEndian(); + if ((valueFormat & (ushort)ValueFormatFlags.YAdvanceDevice) != 0) + yAdvDevice = reader.ReadUInt16BigEndian(); + + var key = new ValueKey( + Pack((ushort)xPlacement, (ushort)yPlacement, (ushort)xAdvance, (ushort)yAdvance), + Pack(xPlaDevice, yPlaDevice, xAdvDevice, yAdvDevice)); + + ValueRecord record; + if (!_records.TryGetValue(key, out record)) + { + record = new ValueRecord + { + XPlacement = xPlacement, + YPlacement = yPlacement, + XAdvance = xAdvance, + YAdvance = yAdvance, + XPlacementDeviceOffset = xPlaDevice, + YPlacementDeviceOffset = yPlaDevice, + XAdvanceDeviceOffset = xAdvDevice, + YAdvanceDeviceOffset = yAdvDevice + }; + _records.Add(key, record); + } + return record; + } + + /// + /// Returns the shared class-matrix cell for two value records from . + /// Only for PairPos format 2, where a cell has no second glyph of its own. + /// + internal PairValueRecord GetPair(ValueRecord value1, ValueRecord value2) + { + var key = new PairKey(value1, value2); + PairValueRecord pair; + if (!_pairs.TryGetValue(key, out pair)) + { + pair = new PairValueRecord { Value1 = value1, Value2 = value2 }; + _pairs.Add(key, pair); + } + return pair; + } + + private static ulong Pack(ushort a, ushort b, ushort c, ushort d) + { + return ((ulong)a << 48) | ((ulong)b << 32) | ((ulong)c << 16) | d; + } + + private struct ValueKey : IEquatable + { + private readonly ulong _values; + private readonly ulong _devices; + + internal ValueKey(ulong values, ulong devices) + { + _values = values; + _devices = devices; + } + + public bool Equals(ValueKey other) + { + return _values == other._values && _devices == other._devices; + } + + public override bool Equals(object obj) + { + return obj is ValueKey && Equals((ValueKey)obj); + } + + public override int GetHashCode() + { + return _values.GetHashCode() * 31 + _devices.GetHashCode(); + } + } + + /// Key on the identity of two pooled value records (equal values are the same instance). + private struct PairKey : IEquatable + { + private readonly ValueRecord _value1; + private readonly ValueRecord _value2; + + internal PairKey(ValueRecord value1, ValueRecord value2) + { + _value1 = value1; + _value2 = value2; + } + + public bool Equals(PairKey other) + { + return ReferenceEquals(_value1, other._value1) && ReferenceEquals(_value2, other._value2); + } + + public override bool Equals(object obj) + { + return obj is PairKey && Equals((PairKey)obj); + } + + public override int GetHashCode() + { + return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(_value1) * 31 + + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(_value2); + } + } + } +} diff --git a/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTable.cs index 81375dee48..473009d336 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTable.cs @@ -9,8 +9,11 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 + 12/04/2026 EPPlus Software AB Kerning pair lookup built once per table *************************************************************************************************/ +using EPPlus.Fonts.OpenType.TextShaping.Kerning; using System.Collections.Generic; +using System.Threading; namespace EPPlus.Fonts.OpenType.Tables.Kern { @@ -25,8 +28,27 @@ public class KernTable : FontTableBase public List SubTables { get; set; } = new List(); + private KernPairLookup _pairLookup; + + /// + /// The kerning pairs for shaping, built on first use and shared by every shaper of the + /// font. The table of a loaded font is not changed after loading; + /// discards the lookup. + /// + internal KernPairLookup GetPairLookup() + { + var lookup = Volatile.Read(ref _pairLookup); + if (lookup == null) + { + lookup = KernPairLookup.Build(this); + lookup = Interlocked.CompareExchange(ref _pairLookup, lookup, null) ?? lookup; + } + return lookup; + } + internal override void Clear() { + _pairLookup = null; SubTables.Clear(); version = 0; numberOfFormat0Tables = 0; diff --git a/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs b/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs index ba8bfba213..5ff1ca1be6 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs @@ -33,5 +33,7 @@ internal static class TableNames public const string Fpgm = "fpgm"; public const string Prep = "prep"; public const string Gasp = "gasp"; + public const string Cff = "CFF "; // Note: trailing space is part of the tag + public const string Cff2 = "CFF2"; } } diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs index 8859559452..89dd71ba98 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs @@ -8,6 +8,8 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 01/20/2025 EPPlus Software AB Initial implementation + 12/04/2026 EPPlus Software AB Lookups cached per feature, copy glyphs only on substitution + 12/04/2026 EPPlus Software AB Positions skipped when no rule's first input glyph matches *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; @@ -27,6 +29,27 @@ internal class ChainingContextualProcessor private readonly SingleSubstitutionProcessor _singleSubstProcessor; private readonly LigatureProcessor _ligatureProcessor; + // Feature tag + script + language -> the Type 6 lookups to apply. The result only depends + // on the font, so it is resolved once instead of on every Shape call (which walked every + // FeatureRecord and built a new list and HashSet each time). + private readonly Dictionary> _lookupCache = + new Dictionary>(); + + // Per lookup: its Format 3 rules, and the glyphs any of them accepts as first input glyph. + private readonly Dictionary _preparedLookups = + new Dictionary(); + + private sealed class PreparedLookup + { + internal ChainingContextualSubstFormat3[] Rules; + + // True for every glyph id that is in the first input coverage of at least one rule. + // A rule can only match at a position whose glyph is in its first input coverage, so + // positions outside this set are skipped without trying any rule. Null when the set + // could not be built; every position is then tried. + internal bool[] FirstInput; + } + public ChainingContextualProcessor( OpenTypeFont font, SingleSubstitutionProcessor singleSubstProcessor, @@ -57,7 +80,12 @@ internal List ApplyContextualSubstitutions( return glyphs; // Find all Type 6 lookups for this feature - var contextualLookups = FindContextualLookupsForFeature(gsub, featureTag, script, language); + var cacheKey = new ScriptLanguageKey(featureTag, script, language); + if (!_lookupCache.TryGetValue(cacheKey, out var contextualLookups)) + { + contextualLookups = FindContextualLookupsForFeature(gsub, featureTag, script, language); + _lookupCache[cacheKey] = contextualLookups; + } if (contextualLookups.Count == 0) return glyphs; @@ -140,46 +168,50 @@ internal static List FindContextualLookupsForFeature( } /// - /// Applies a single chaining contextual lookup to the glyph sequence. + /// Applies a single chaining contextual lookup to the glyph sequence. Returns + /// itself when nothing matched; the list is copied only before + /// the first substitution, so the input list is never modified. /// private List ApplyContextualLookup(List glyphs, LookupTable lookup) { - var result = new List(glyphs); + var prepared = GetPreparedLookup(lookup); + if (prepared.Rules.Length == 0) + return glyphs; + + var firstInput = prepared.FirstInput; + var result = glyphs; int i = 0; while (i < result.Count) { - bool substituted = false; - - // Try each subtable - foreach (var subtable in lookup.SubTables) + if (firstInput != null) { - ChainingContextualSubstFormat3 contextual = null; - - if (subtable is ChainingContextualSubstFormat3 format3) + ushort glyphId = result[i].GlyphId; + if (glyphId >= firstInput.Length || !firstInput[glyphId]) { - contextual = format3; - } - else if (subtable is ExtensionSubstSubTable ext && - ext.ExtendedSubTable is ChainingContextualSubstFormat3 extFormat3) - { - contextual = extFormat3; + i++; + continue; } + } + + bool substituted = false; - if (contextual != null) + // Try each rule + foreach (var contextual in prepared.Rules) + { + // Try to match and apply contextual rule at position i + if (TryApplyContextualRule(result, i, contextual, out var newGlyphs, out int glyphsConsumed)) { - // Try to match and apply contextual rule at position i - if (TryApplyContextualRule(result, i, contextual, out var newGlyphs, out int glyphsConsumed)) - { - // Replace glyphs at position i with the result - result.RemoveRange(i, glyphsConsumed); - result.InsertRange(i, newGlyphs); - - // Move past the substituted sequence - i += newGlyphs.Count; - substituted = true; - break; - } + // Replace glyphs at position i with the result + if (ReferenceEquals(result, glyphs)) + result = new List(glyphs); + result.RemoveRange(i, glyphsConsumed); + result.InsertRange(i, newGlyphs); + + // Move past the substituted sequence + i += newGlyphs.Count; + substituted = true; + break; } } @@ -192,6 +224,68 @@ private List ApplyContextualLookup(List glyphs, Lookup return result; } + private PreparedLookup GetPreparedLookup(LookupTable lookup) + { + if (_preparedLookups.TryGetValue(lookup, out var prepared)) + return prepared; + + var rules = new List(); + foreach (var subtable in lookup.SubTables) + { + if (subtable is ChainingContextualSubstFormat3 format3) + { + rules.Add(format3); + } + else if (subtable is ExtensionSubstSubTable ext && + ext.ExtendedSubTable is ChainingContextualSubstFormat3 extFormat3) + { + rules.Add(extFormat3); + } + } + + prepared = new PreparedLookup + { + Rules = rules.ToArray(), + FirstInput = BuildFirstInputSet(rules) + }; + _preparedLookups[lookup] = prepared; + return prepared; + } + + private static bool[] BuildFirstInputSet(List rules) + { + var covered = new List(rules.Count); + int maxGlyphId = -1; + foreach (var rule in rules) + { + // A rule without input glyphs never matches (see TryApplyContextualRule). + if (rule.InputCoverages == null || rule.InputCoverages.Count == 0) + continue; + + var coverage = rule.InputCoverages[0]; + if (coverage == null) + return null; + + var glyphIds = coverage.GetCoveredGlyphs(); + covered.Add(glyphIds); + foreach (var glyphId in glyphIds) + { + if (glyphId > maxGlyphId) + maxGlyphId = glyphId; + } + } + + var set = new bool[maxGlyphId + 1]; + foreach (var glyphIds in covered) + { + foreach (var glyphId in glyphIds) + { + set[glyphId] = true; + } + } + return set; + } + /// /// Attempts to match and apply a contextual rule starting at the given position. /// diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs index ed75d19b94..49759badcf 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs @@ -41,7 +41,7 @@ public IndexedSubtable(int featureIndex, PairPosSubTable subtable) private readonly GposTable _gpos; private readonly List _subtables; - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary> _activeIndexCache = new Dictionary>(); public GposKerningProvider(GposTable gposTable) { @@ -84,7 +84,7 @@ public short GetKerning(ushort leftGlyph, ushort rightGlyph, string script, stri private HashSet GetActiveIndices(string script, string language) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + var cacheKey = new ScriptLanguageKey(script, language); if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) { diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KernPairLookup.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KernPairLookup.cs new file mode 100644 index 0000000000..b9281843a9 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KernPairLookup.cs @@ -0,0 +1,92 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Kerning pairs of a kern table, built once per font + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Kern; +using System; +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.TextShaping.Kerning +{ + /// + /// The horizontal kerning pairs of a legacy 'kern' table as two sorted arrays, searched with a + /// binary search. Built once per and shared by every shaper of the + /// font, so creating a shaper does not copy the font's kerning pairs. About 6 bytes per pair. + /// + internal sealed class KernPairLookup + { + internal static readonly KernPairLookup Empty = new KernPairLookup(new uint[0], new short[0]); + + private readonly uint[] _keys; + private readonly short[] _values; + + private KernPairLookup(uint[] keys, short[] values) + { + _keys = keys; + _values = values; + } + + internal int Count => _keys.Length; + + /// + /// Returns the kerning value for the pair, or 0 when the pair is not kerned. + /// + internal short GetKerning(ushort leftGlyph, ushort rightGlyph) + { + int index = Array.BinarySearch(_keys, PairKey(leftGlyph, rightGlyph)); + return index >= 0 ? _values[index] : (short)0; + } + + /// + /// Collects the pairs of every Format 0 subtable (the coverage direction bits are not + /// checked). Pairs with value 0 are left out. When a pair occurs more than once, the last + /// non-zero value wins. + /// + internal static KernPairLookup Build(KernTable kernTable) + { + if (kernTable?.SubTables == null) + return Empty; + + var pairs = new Dictionary(); + foreach (var subtable in kernTable.SubTables) + { + if (subtable == null || subtable.coverage.Format != 0 || subtable.Format0Subtable?.Pairs == null) + continue; + + foreach (var pair in subtable.Format0Subtable.Pairs) + { + if (pair != null && pair.value != 0) + pairs[PairKey(pair.left, pair.right)] = pair.value; + } + } + + if (pairs.Count == 0) + return Empty; + + var keys = new uint[pairs.Count]; + var values = new short[pairs.Count]; + int i = 0; + foreach (var kv in pairs) + { + keys[i] = kv.Key; + values[i] = kv.Value; + i++; + } + Array.Sort(keys, values); + return new KernPairLookup(keys, values); + } + + private static uint PairKey(ushort leftGlyph, ushort rightGlyph) + { + return ((uint)leftGlyph << 16) | rightGlyph; + } + } +} diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/LegacyKerningProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/LegacyKerningProvider.cs index eba2b218e8..7927da12ba 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/LegacyKerningProvider.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/LegacyKerningProvider.cs @@ -1,5 +1,16 @@ -using EPPlus.Fonts.OpenType.Tables.Kern; -using System.Collections.Generic; +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Pairs shared per font instead of copied per shaper + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Kern; namespace EPPlus.Fonts.OpenType.TextShaping.Kerning { @@ -9,77 +20,20 @@ namespace EPPlus.Fonts.OpenType.TextShaping.Kerning /// internal class LegacyKerningProvider { - private readonly Dictionary _kerningPairs; + // Shared by every shaper of the font; see KernTable.GetPairLookup. + private readonly KernPairLookup _pairs; public LegacyKerningProvider(KernTable kernTable) { - _kerningPairs = BuildKerningDictionary(kernTable); + _pairs = kernTable != null ? kernTable.GetPairLookup() : KernPairLookup.Empty; } /// /// Gets kerning adjustment for a glyph pair from kern table. - /// O(1) lookup via pre-built dictionary. /// public short GetKerning(ushort leftGlyph, ushort rightGlyph) { - ulong key = MakeKey(leftGlyph, rightGlyph); - - if (_kerningPairs.TryGetValue(key, out short value)) - return value; - - return 0; - } - - /// - /// Builds a dictionary of all kerning pairs from the kern table. - /// Called once during construction. - /// - private Dictionary BuildKerningDictionary(KernTable kernTable) - { - var pairs = new Dictionary(); - - if (kernTable?.SubTables == null) - return pairs; - - foreach (var subtable in kernTable.SubTables) - { - // Only support Format 0 (horizontal kerning) - if (subtable.coverage.Format == 0 && subtable.Format0Subtable != null) - { - AddPairsFromFormat0(pairs, subtable.Format0Subtable); - } - } - - return pairs; - } - - /// - /// Adds all kerning pairs from a Format 0 subtable to the dictionary. - /// - private void AddPairsFromFormat0( - Dictionary pairs, - KernSubTableFormat0 format0) - { - if (format0.Pairs == null) - return; - - foreach (var pair in format0.Pairs) - { - ulong key = MakeKey(pair.left, pair.right); - - // Last value wins if duplicate keys - // (matches original behavior of returning first non-zero) - if (pair.value != 0) - { - pairs[key] = pair.value; - } - } - } - - private static ulong MakeKey(ushort leftGlyph, ushort rightGlyph) - { - // Combine two ushorts into one ulong for fast dictionary lookup - return ((ulong)leftGlyph << 16) | rightGlyph; + return _pairs.GetKerning(leftGlyph, rightGlyph); } } -} \ No newline at end of file +} diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs index 93aa9cbd73..bde260f459 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs @@ -14,6 +14,7 @@ Date Author Change hardcoded "liga"; unwrap extension-wrapped (Type 7) ligature lookups, which GSUB does not flatten the way GPOS does + 12/04/2026 EPPlus Software AB Ligature sets sorted once, not per glyph *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Scripts; @@ -47,7 +48,12 @@ public IndexedLookup(int featureIndex, LookupTable lookup) // for every tag the font defines, not just "liga" - which tags are actually applied is // decided per call via the featureTags parameter, driven by ShapingOptions.GsubFeatures. private readonly Dictionary> _lookupsByFeatureTag; - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary> _activeIndexCache = new Dictionary>(); + + // Ligature set -> its ligatures with the longest first. Sorted once per set instead of on + // every glyph that starts a possible ligature. + private readonly Dictionary _sortedLigatures = + new Dictionary(); public LigatureProcessor(OpenTypeFont font) { @@ -168,7 +174,7 @@ private static LigatureSubstSubTable UnwrapLigatureSubtable(Tables.FontTableElem private HashSet GetActiveIndices(string script, string language) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + var cacheKey = new ScriptLanguageKey(script, language); if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) { @@ -197,9 +203,7 @@ private bool TryApplyLigatureInPlace( return false; // Try longer ligatures first, as recommended by the OpenType spec - var sortedLigs = ligSet.Ligatures - .OrderByDescending(l => 1 + (l.Components?.Length ?? 0)) - .ToList(); + var sortedLigs = GetLigaturesLongestFirst(ligSet); foreach (var lig in sortedLigs) { @@ -232,6 +236,22 @@ private bool TryApplyLigatureInPlace( return false; } + /// + /// Returns the ligatures of with the longest first. The sort is + /// stable, so ligatures of the same length keep the font's order of preference. + /// + private LigatureTable[] GetLigaturesLongestFirst(LigatureSetTable ligSet) + { + if (!_sortedLigatures.TryGetValue(ligSet, out var sorted)) + { + sorted = ligSet.Ligatures + .OrderByDescending(l => 1 + (l.Components?.Length ?? 0)) + .ToArray(); + _sortedLigatures[ligSet] = sorted; + } + return sorted; + } + /// /// Builds a map from feature tag to every ligature-relevant lookup recorded under that /// tag (LookupType 4, or 7 wrapping 4), together with each lookup's original FeatureList diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs index a234c08acc..679684cba1 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs @@ -11,6 +11,8 @@ Date Author Change 01/20/2025 EPPlus Software AB Mark-to-Base positioning 09/07/2026 EPPlus Software AB Pen-relative, additive mark offsets 09/07/2026 EPPlus Software AB Filter by ScriptList/LangSys, not just tag + 12/04/2026 EPPlus Software AB Active subtables resolved once per script, marks prefiltered + 12/04/2026 EPPlus Software AB Positioned mark written back, ShapedGlyph is a struct *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables.Common.Layout.Scripts; using EPPlus.Fonts.OpenType.Tables.Gpos; @@ -41,7 +43,11 @@ public IndexedSubtable(int featureIndex, MarkToBaseSubTableFormat1 subtable) private readonly GposTable _gpos; private readonly List _subtables; - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary _activeSubtableCache = new Dictionary(); + + // True for every glyph id that is in the mark coverage of at least one subtable. Most + // glyphs in a text are not marks, and for those no subtable has to be searched. + private readonly bool[] _isMark; public MarkToBaseProvider(OpenTypeFont font) { @@ -55,6 +61,8 @@ public MarkToBaseProvider(OpenTypeFont font) { _subtables = new List(); } + + _isMark = BuildMarkGlyphSet(_subtables); } /// @@ -72,43 +80,108 @@ public void ApplyMarkPositioning(List glyphs, string script, string if (_subtables.Count == 0 || glyphs.Count < 2) return; - HashSet activeIndices = GetActiveIndices(script, language); + MarkToBaseSubTableFormat1[] activeSubtables = GetActiveSubtables(script, language); + if (activeSubtables.Length == 0) + return; // Process glyphs left-to-right for (int i = 1; i < glyphs.Count; i++) { - var baseGlyph = glyphs[i - 1]; var markGlyph = glyphs[i]; + // A glyph outside every mark coverage cannot be positioned by any subtable. + if (markGlyph.GlyphId >= _isMark.Length || !_isMark[markGlyph.GlyphId]) + continue; + + var baseGlyph = glyphs[i - 1]; + // Try each subtable reachable from the active script until we find positioning + foreach (var subtable in activeSubtables) + { + if (TryPositionMark(subtable, baseGlyph, ref markGlyph)) + { + // ShapedGlyph is a value type: store the positioned copy. + glyphs[i] = markGlyph; + break; + } + } + } + } + + /// + /// Returns the subtables reachable from the given script and language, in feature order. + /// A font often has one "mark" feature per script and language, all pointing at the same + /// lookups, so the same subtable is listed only once. Trying it again could not change the + /// result: it is only reached again after it failed for the same pair of glyphs. + /// + private MarkToBaseSubTableFormat1[] GetActiveSubtables(string script, string language) + { + var cacheKey = new ScriptLanguageKey(script, language); + + if (!_activeSubtableCache.TryGetValue(cacheKey, out var active)) + { + // null means "no ScriptList to filter by" - keep every entry, matching the + // previous behavior rather than discarding marks we cannot resolve. + HashSet activeIndices = ScriptFeatureResolver.GetActiveFeatureIndices(_gpos?.ScriptList, script, language); + + var list = new List(); foreach (var entry in _subtables) { - // null activeIndices means "no ScriptList to filter by" - keep every entry, - // matching the previous behavior rather than discarding marks we cannot resolve. if (activeIndices != null && !activeIndices.Contains(entry.FeatureIndex)) - { continue; - } - if (TryPositionMark(entry.Subtable, baseGlyph, markGlyph)) - { - break; - } + if (!ContainsReference(list, entry.Subtable)) + list.Add(entry.Subtable); } + + active = list.ToArray(); + _activeSubtableCache[cacheKey] = active; } + + return active; } - private HashSet GetActiveIndices(string script, string language) + private static bool ContainsReference(List list, MarkToBaseSubTableFormat1 subtable) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + foreach (var item in list) + { + if (ReferenceEquals(item, subtable)) + return true; + } + return false; + } - if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) + private static bool[] BuildMarkGlyphSet(List subtables) + { + var unique = new List(); + foreach (var entry in subtables) { - indices = ScriptFeatureResolver.GetActiveFeatureIndices(_gpos?.ScriptList, script, language); - _activeIndexCache[cacheKey] = indices; + if (entry.Subtable.MarkCoverage != null && !ContainsReference(unique, entry.Subtable)) + unique.Add(entry.Subtable); + } + + var covered = new List(unique.Count); + int maxGlyphId = -1; + foreach (var subtable in unique) + { + var glyphIds = subtable.MarkCoverage.GetCoveredGlyphs(); + covered.Add(glyphIds); + foreach (var glyphId in glyphIds) + { + if (glyphId > maxGlyphId) + maxGlyphId = glyphId; + } } - return indices; + var isMark = new bool[maxGlyphId + 1]; + foreach (var glyphIds in covered) + { + foreach (var glyphId in glyphIds) + { + isMark[glyphId] = true; + } + } + return isMark; } /// @@ -117,7 +190,7 @@ private HashSet GetActiveIndices(string script, string language) private bool TryPositionMark( MarkToBaseSubTableFormat1 subtable, ShapedGlyph baseGlyph, - ShapedGlyph markGlyph) + ref ShapedGlyph markGlyph) { // Check if base glyph is in base coverage int baseIndex = subtable.BaseCoverage?.GetGlyphIndex(baseGlyph.GlyphId) ?? -1; diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs index 64a35bb4c5..cad7631411 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs @@ -53,7 +53,7 @@ public IndexedSubtable(int featureIndex, GposSubTableBase subtable) // Active-index sets are per (script, language), not per font, so they are cached // separately rather than recomputed on every call - a TextShaper instance is reused // across many Shape() calls that may each specify a different script. - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary> _activeIndexCache = new Dictionary>(); public SingleAdjustmentProvider(OpenTypeFont font) { @@ -120,7 +120,7 @@ public bool TryGetAdjustment(ushort glyphId, List features, string scrip private HashSet GetActiveIndices(string script, string language) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + var cacheKey = new ScriptLanguageKey(script, language); if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) { diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/ScriptLanguageKey.cs b/src/EPPlus.Fonts.OpenType/TextShaping/ScriptLanguageKey.cs new file mode 100644 index 0000000000..c905b76c90 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/TextShaping/ScriptLanguageKey.cs @@ -0,0 +1,63 @@ +/************************************************************************************************* + Required Notice: Copyright (C) EPPlus Software AB. + This software is licensed under PolyForm Noncommercial License 1.0.0 + and may only be used for noncommercial purposes + https://polyformproject.org/licenses/noncommercial/1.0.0/ + + A commercial license to use this software can be purchased at https://epplussoftware.com + ************************************************************************************************* + Date Author Change + ************************************************************************************************* + 12/04/2026 EPPlus Software AB Cache keys without string concatenation + *************************************************************************************************/ +using System; + +namespace EPPlus.Fonts.OpenType.TextShaping +{ + /// + /// Cache key for data resolved per script and language system, optionally per feature tag. + /// Replaces keys built by string concatenation, which allocated a string on every shaping + /// call (and in kerning, on every glyph pair not yet cached). Null and empty are treated as + /// the same value, as the concatenated keys did. + /// + internal struct ScriptLanguageKey : IEquatable + { + private readonly string _feature; + private readonly string _script; + private readonly string _language; + + internal ScriptLanguageKey(string script, string language) + : this(null, script, language) + { + } + + internal ScriptLanguageKey(string feature, string script, string language) + { + _feature = feature ?? string.Empty; + _script = script ?? string.Empty; + _language = language ?? string.Empty; + } + + public bool Equals(ScriptLanguageKey other) + { + return string.Equals(_feature, other._feature, StringComparison.Ordinal) + && string.Equals(_script, other._script, StringComparison.Ordinal) + && string.Equals(_language, other._language, StringComparison.Ordinal); + } + + public override bool Equals(object obj) + { + return obj is ScriptLanguageKey && Equals((ScriptLanguageKey)obj); + } + + public override int GetHashCode() + { + unchecked + { + int hash = StringComparer.Ordinal.GetHashCode(_feature); + hash = hash * 31 + StringComparer.Ordinal.GetHashCode(_script); + return hash * 31 + StringComparer.Ordinal.GetHashCode(_language); + } + } + } +} diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs index e7bf5e6256..3e8a099302 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs @@ -54,7 +54,7 @@ public IndexedSubtable(int featureIndex, MultipleSubstSubTable subtable) // FeatureList index lets ApplySubstitutions filter down to what the requested script can // actually reach. private readonly Dictionary> _featureSubtables; - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary> _activeIndexCache = new Dictionary>(); public MultipleSubstitutionProcessor(OpenTypeFont font) { @@ -155,7 +155,7 @@ public List ApplySubstitutions(List glyphs, List GetActiveIndices(string script, string language) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + var cacheKey = new ScriptLanguageKey(script, language); if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) { diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs index c2c835603d..7b2869b7ef 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs @@ -46,7 +46,7 @@ public IndexedSubtable(int featureIndex, SingleSubstSubTable subtable) // requested script can actually reach - unlike the tag alone, which collapses every // script's data for the same tag into one bucket. private readonly Dictionary> _featureSubtables; - private readonly Dictionary> _activeIndexCache = new Dictionary>(); + private readonly Dictionary> _activeIndexCache = new Dictionary>(); public SingleSubstitutionProcessor(OpenTypeFont font) { @@ -135,7 +135,7 @@ public List ApplySubstitutions(List glyphs, List GetActiveIndices(string script, string language) { - string cacheKey = (script ?? string.Empty) + "|" + (language ?? string.Empty); + var cacheKey = new ScriptLanguageKey(script, language); if (!_activeIndexCache.TryGetValue(cacheKey, out var indices)) { diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/TextShaper.cs b/src/EPPlus.Fonts.OpenType/TextShaping/TextShaper.cs index 836f6f9f56..c2f5f1e2a4 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/TextShaper.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/TextShaper.cs @@ -578,7 +578,7 @@ private void ApplyPositioning(List glyphs, ShapingOptions options) /// private void ApplySingleAdjustment(List glyphs, ShapingOptions options) { - List features = options.GposFeatures ?? new List(); + List features = options.GposFeatures; // null is treated as no features for (int i = 0; i < glyphs.Count; i++) { diff --git a/src/EPPlus.Interfaces/Fonts/ShapedGlyph.cs b/src/EPPlus.Interfaces/Fonts/ShapedGlyph.cs index fe05a6a18e..d1a6f0f1b6 100644 --- a/src/EPPlus.Interfaces/Fonts/ShapedGlyph.cs +++ b/src/EPPlus.Interfaces/Fonts/ShapedGlyph.cs @@ -11,6 +11,7 @@ Date Author Change 01/15/2025 EPPlus Software AB Initial implementation 01/24/2026 EPPlus Software AB Optimized to struct (79% memory reduction) 01/31/2026 EPPlus Software AB Added BaseAdvance for kerning optimization + 12/04/2026 EPPlus Software AB Struct instead of class, FontId is a field *************************************************************************************************/ using System.Diagnostics; using System.Runtime.InteropServices; @@ -20,10 +21,19 @@ namespace OfficeOpenXml.Interfaces.Fonts /// /// Represents a shaped glyph with positioning information. /// All measurements are in font units (not PDF points or pixels). - /// OPTIMIZED: Changed to struct for 79% memory reduction (56 bytes → 12 bytes). /// + /// + /// A 16 byte value type, so an array of shaped glyphs is one allocation instead of one object + /// per glyph. Because it is a value type, reading an element from a list or array gives a copy: + /// to change a glyph, change the copy and assign it back + /// (var g = glyphs[i]; g.XAdvance += kern; glyphs[i] = g;). Array elements can also be + /// changed in place (array[i].XAdvance += kern;). + /// new ShapedGlyph() sets to 1, but default(ShapedGlyph) + /// and the elements of a new array have every field set to 0. + /// [DebuggerDisplay("GlyphId: {GlyphId}, XAdvance: {XAdvance}, BaseAdvance: {BaseAdvance}, CharCount: {CharCount}")] - public class ShapedGlyph + [StructLayout(LayoutKind.Sequential)] + public struct ShapedGlyph { /// /// The glyph ID in the font. @@ -84,14 +94,11 @@ public class ShapedGlyph public byte CharCount; /// - /// Reserved byte for future use and perfect alignment. + /// Index of the font the glyph comes from: 0 = primary, 1+ = fallbacks. /// - public byte Reserved; + public byte FontId; - // Total size: 16 bytes (perfectly aligned for 64-bit systems) - // Previous version (without BaseAdvance): 14 bytes - // Memory cost: +2 bytes per glyph (+14% increase) - // Performance gain: 8-10x faster PDF kerning rendering + // Total size: 16 bytes. /// /// Gets the kerning adjustment applied to this glyph. @@ -99,10 +106,6 @@ public class ShapedGlyph /// public short Kerning => (short)(XAdvance - BaseAdvance); - /// - /// 0 = primary, 1+ = fallbacks - /// - public byte FontId { get; set; } /// /// Creates a new shaped glyph with specified glyph ID and advance width. /// Other fields are initialized to default values. @@ -117,7 +120,7 @@ public ShapedGlyph(ushort glyphId, int xAdvance) YOffset = 0; ClusterIndex = 0; CharCount = 1; - Reserved = 0; + FontId = 0; } /// @@ -134,7 +137,7 @@ public ShapedGlyph(ushort glyphId, short baseAdvance, short xAdvance, YOffset = 0; ClusterIndex = clusterIndex; CharCount = charCount; - Reserved = 0; + FontId = 0; } /// @@ -151,7 +154,7 @@ public ShapedGlyph(ushort glyphId, short baseAdvance, short xAdvance, short yAdv YOffset = yOffset; ClusterIndex = clusterIndex; CharCount = charCount; - Reserved = 0; + FontId = 0; } /// diff --git a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs index 2293efbf18..550021bbcd 100644 --- a/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs +++ b/src/EPPlus/Export/PdfExport/TextMapping/PdfHeaderFooterTextBuilder.cs @@ -76,7 +76,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P text += ws.Name; break; case ExcelHeaderFooterFormattingCodes.CurrentDate: - text += DateTime.Now.ToString($"yyyy-MM-dd"); + text += pageSettings.ExportTime.ToString($"yyyy-MM-dd"); break; case ExcelHeaderFooterFormattingCodes.FileName: text += ws._package.File?.Name ?? ""; @@ -90,7 +90,7 @@ internal static PdfHeaderFooter GetTextFormats(PdfRenderSettings pageSettings, P PageNumberIndexes.Add(i - 1); break; case ExcelHeaderFooterFormattingCodes.CurrentTime: - text += DateTime.Now.ToString("HH:mm"); + text += pageSettings.ExportTime.ToString("HH:mm"); break; case ExcelHeaderFooterFormattingCodes.FilePath: text += ws._package.File?.Directory != null ? ws._package.File.Directory.FullName + "\\" : ""; diff --git a/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs b/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs index c0233331f7..ae51741905 100644 --- a/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs +++ b/src/EPPlus/Export/PdfExport/TextShaping/PdfTextShaper.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 27/11/2025 EPPlus Software AB EPPlus 9 + 12/04/2026 EPPlus Software AB Reuse the unsubset font provider within an export *************************************************************************************************/ using EPPlus.Export.Pdf.Layout; using EPPlus.Export.Pdf.Resources; @@ -19,7 +20,6 @@ Date Author Change using OfficeOpenXml.Export.PdfExport.Data; using OfficeOpenXml.Interfaces.Fonts; using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -28,9 +28,6 @@ namespace OfficeOpenXml.Export.PdfExport.TextShaping { internal static class PdfTextShaper { - private static ConcurrentDictionary shaperCache = new ConcurrentDictionary(); - private static ConcurrentDictionary layoutEngineCache = new ConcurrentDictionary(); - public static void ShapeText(PdfRenderSettings pageSettings, PdfDictionaries dictionaries, PdfCell cell) { var totalTextLength = 0d; @@ -46,12 +43,11 @@ public static void ShapeText(PdfRenderSettings pageSettings, PdfDictionaries dic IFontProvider provider; if (!dictionaries.ShapedProviders.TryGetValue(key, out provider)) { - var font = pageSettings.FontEngine.LoadFont(tf.Font.Family, tf.Font.SubFamily); - provider = new DefaultFontProvider(pageSettings.FontEngine, font); + provider = dictionaries.GetUnsubsetProvider(pageSettings, tf.Font.Family, tf.Font.SubFamily); } st.FontProvider = provider; - var shaper = shaperCache.GetOrAdd(st.FontProvider, fp => new TextShaper(fp)); - var layoutEngine = layoutEngineCache.GetOrAdd(st.FontProvider, fp => new TextLayoutEngine(shaper)); + var shaper = dictionaries.GetShaper(st.FontProvider); + var layoutEngine = dictionaries.GetLayoutEngine(st.FontProvider); var options = BuildShapingOptions(pageSettings); var shaped = shaper.Shape(tf.Text, options); var usedFonts = shaper.GetUsedFonts().ToList(); @@ -125,16 +121,8 @@ public static void ShapeText(PdfRenderSettings pageSettings, PdfDictionaries dic continue; } st.FontProvider = provider; - if (!shaperCache.TryGetValue(st.FontProvider, out var shaper)) - { - shaper = new TextShaper(st.FontProvider); - shaperCache[st.FontProvider] = shaper; - } - if (!layoutEngineCache.TryGetValue(st.FontProvider, out var layoutEngine)) - { - layoutEngine = new TextLayoutEngine(shaper); - layoutEngineCache[st.FontProvider] = layoutEngine; - } + var shaper = dictionaries.GetShaper(st.FontProvider); + var layoutEngine = dictionaries.GetLayoutEngine(st.FontProvider); var options = BuildShapingOptions(pageSettings); var shaped = shaper.Shape(tf.Text, options); var usedFonts = shaper.GetUsedFonts().ToList();