diff --git a/src/EPPlus.Fonts.OpenType.Benchmarks/FontCacheBenchmarks.cs b/src/EPPlus.Fonts.OpenType.Benchmarks/FontCacheBenchmarks.cs new file mode 100644 index 000000000..6b1eaad06 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Benchmarks/FontCacheBenchmarks.cs @@ -0,0 +1,113 @@ +/************************************************************************************************* + 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 Benchmarks for the font and kerning caches + *************************************************************************************************/ +using BenchmarkDotNet.Attributes; +using EPPlus.Fonts.OpenType.TextShaping; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.IO; +using System.Text; + +namespace EPPlus.Fonts.OpenType.Benchmarks +{ + /// + /// Benchmarks for the caches that keep memory use bounded: parsed fonts shared between font + /// names that resolve to the same file, and the kerning cache of a shaper. + /// + [MemoryDiagnoser] + [SimpleJob(warmupCount: 3, iterationCount: 5)] + public class FontCacheBenchmarks + { + private const int UnknownNameCount = 200; + private const string SampleText = "The quick brown fox jumps over the lazy dog. AVAWAY Tolerance."; + + private string _fontsPath = string.Empty; + private string _longVariedText = string.Empty; + private OpenTypeFontEngine _engine = null!; + private OpenTypeFont _roboto = null!; + private TextShaper _warmShaper = null!; + + [GlobalSetup] + public void Setup() + { + _fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts"); + if (!Directory.Exists(_fontsPath)) + throw new DirectoryNotFoundException($"Fonts directory not found: {_fontsPath}"); + + _engine = CreateEngine(); + _roboto = _engine.LoadFont("Roboto", FontSubFamily.Regular); + _warmShaper = new TextShaper(_engine, _roboto); + _warmShaper.Shape(SampleText); + + // Latin text with many distinct glyph pairs, more than the kerning cache holds. + var random = new Random(1); + var text = new StringBuilder(); + for (int i = 0; i < 200000; i++) + text.Append((char)random.Next(0x21, 0x17F)); + _longVariedText = text.ToString(); + } + + [GlobalCleanup] + public void Cleanup() + { + _engine.Dispose(); + } + + private OpenTypeFontEngine CreateEngine() + { + return new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(_fontsPath); + cfg.SearchSystemDirectories = false; + }); + } + + /// + /// A new engine loads 200 font names it cannot find. Every name falls back to the same + /// built-in font, which is parsed once and shared. + /// + [Benchmark] + public int LoadFont_ManyUnknownNames() + { + using (var engine = CreateEngine()) + { + int loaded = 0; + for (int i = 0; i < UnknownNameCount; i++) + { + if (engine.LoadFont("NoSuchFont" + i, FontSubFamily.Regular) != null) + loaded++; + } + return loaded; + } + } + + /// + /// A new shaper shapes 200 000 characters of varied Latin text. The kerning cache fills up + /// and starts over. + /// + [Benchmark] + public ShapedText Shape_LongVariedText() + { + return new TextShaper(_engine, _roboto).Shape(_longVariedText); + } + + /// + /// A shaper whose kerning cache already holds every pair of the text shapes it again, + /// the common case. + /// + [Benchmark] + public ShapedText Shape_WarmKerningCache() + { + return _warmShaper.Shape(SampleText); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontCache/FontStoreContentSharingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontCache/FontStoreContentSharingTests.cs new file mode 100644 index 000000000..b8249f9b9 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/FontCache/FontStoreContentSharingTests.cs @@ -0,0 +1,157 @@ +/************************************************************************************************* + 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/02/2026 EPPlus Software AB Tests for sharing parsed fonts between names + *************************************************************************************************/ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Collections.Generic; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.FontCache +{ + /// + /// Tests that the font store parses a font file once, even when it is requested under many + /// names. Every name the resolver cannot find falls back to the same font, and a spreadsheet + /// can use any number of distinct font names, so without sharing each name would keep its own + /// parsed copy of the same font. + /// + [TestClass] + public class FontStoreContentSharingTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + /// + /// Returns a new copy of the bytes registered for a name on every call, like a resolver + /// that reads the font file from disk. + /// + private class CopyingResolver : IFontResolver + { + private readonly Dictionary _fonts = new Dictionary(StringComparer.OrdinalIgnoreCase); + + internal void Add(string fontName, byte[] bytes) + { + _fonts[fontName] = bytes; + } + + public byte[] ResolveFont(string fontName, FontSubFamily subFamily) + { + byte[] bytes; + return _fonts.TryGetValue(fontName, out bytes) ? (byte[])bytes.Clone() : null; + } + } + + private static byte[] ReadTestFont(string fileName) + { + return File.ReadAllBytes(Path.Combine(FontFolder, fileName)); + } + + private static OpenTypeFontEngine CreateEngine(IFontResolver resolver) + { + return new OpenTypeFontEngine(cfg => cfg.FontResolver = resolver); + } + + private static OpenTypeFontEngine CreateTestFolderEngine() + { + return new OpenTypeFontEngine(cfg => + { + foreach (var folder in FontFolders) + cfg.FontDirectories.Add(folder); + cfg.SearchSystemDirectories = false; + }); + } + + [TestMethod] + public void LoadFont_UnknownNamesFallingBackToSameFont_ShareParsedFont() + { + using (var engine = CreateTestFolderEngine()) + { + var font1 = engine.LoadFont("NoSuchFont1"); + var font2 = engine.LoadFont("NoSuchFont2"); + + Assert.IsNotNull(font1); + Assert.AreEqual("Archivo Narrow", font1.GetEnglishFontFamilyName()); + Assert.AreSame(font1, font2); + } + } + + [TestMethod] + public void LoadFont_ResolverReturningFreshCopies_SharesParsedFont() + { + var roboto = ReadTestFont("Roboto-Regular.ttf"); + var resolver = new CopyingResolver(); + resolver.Add("Name1", roboto); + resolver.Add("Name2", roboto); + + using (var engine = CreateEngine(resolver)) + { + var font1 = engine.LoadFont("Name1"); + var font2 = engine.LoadFont("Name2"); + + Assert.IsNotNull(font1); + Assert.AreSame(font1, font2); + // A repeated name is still answered from the cache by name. + Assert.AreSame(font1, engine.LoadFont("Name1")); + } + } + + [TestMethod] + public void LoadFont_SameLengthDifferentContent_DoesNotShare() + { + var roboto = ReadTestFont("Roboto-Regular.ttf"); + // Change the checksum of the first table record. The font still parses, and the two + // files have the same length but different content. + var changed = (byte[])roboto.Clone(); + changed[12 + 4] ^= 0xFF; + var resolver = new CopyingResolver(); + resolver.Add("Original", roboto); + resolver.Add("Changed", changed); + + using (var engine = CreateEngine(resolver)) + { + var original = engine.LoadFont("Original"); + var other = engine.LoadFont("Changed"); + + Assert.IsNotNull(original); + Assert.IsNotNull(other); + Assert.AreNotSame(original, other); + } + } + + [TestMethod] + public void LoadFont_DifferentFonts_DoNotShare() + { + using (var engine = CreateTestFolderEngine()) + { + var roboto = engine.LoadFont("Roboto"); + var openSans = engine.LoadFont("Open Sans"); + + Assert.AreEqual("Roboto", roboto.GetEnglishFontFamilyName()); + Assert.AreEqual("Open Sans", openSans.GetEnglishFontFamilyName()); + Assert.AreNotSame(roboto, openSans); + } + } + + [TestMethod] + public void ClearFontCache_ThenLoad_ParsesAgain() + { + using (var engine = CreateTestFolderEngine()) + { + var before = engine.LoadFont("NoSuchFont1"); + engine.ClearFontCache(); + var after = engine.LoadFont("NoSuchFont2"); + + Assert.IsNotNull(after); + Assert.AreNotSame(before, after); + } + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontCache/ShaperCacheLifetimeTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontCache/ShaperCacheLifetimeTests.cs new file mode 100644 index 000000000..a221a97d9 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/FontCache/ShaperCacheLifetimeTests.cs @@ -0,0 +1,228 @@ +/************************************************************************************************* + 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/02/2026 EPPlus Software AB Tests for releasing cached shapers + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.TextShaping; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace EPPlus.Fonts.OpenType.Tests.FontCache +{ + /// + /// Tests that the shapers an engine caches per thread, and the fonts they hold, are released + /// when the engine is disposed or abandoned, also on threads that stay alive afterwards, such as + /// thread-pool threads. They are also still cached per thread while the engine is in use. + /// + [TestClass] + public class ShaperCacheLifetimeTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + /// + /// A thread that stays alive and runs work items on request, like a thread-pool thread. + /// + private sealed class LiveThread : IDisposable + { + private readonly BlockingCollection _work = new BlockingCollection(); + private readonly Thread _thread; + + internal LiveThread() + { + _thread = new Thread(() => + { + while (RunNext()) + { + } + }); + _thread.IsBackground = true; + _thread.Start(); + } + + /// + /// Takes one work item and runs it. A separate method that is not inlined, so the item, + /// and what it captured, is no longer referenced from the thread's stack once it has + /// run. A local in the thread's own loop can stay reachable in an optimized build while + /// the thread waits for the next item. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private bool RunNext() + { + Action? action; + if (!_work.TryTake(out action, Timeout.Infinite)) + return false; + action(); + return true; + } + + internal T Run(Func func) + { + T result = default(T)!; + Exception? error = null; + using (var done = new ManualResetEventSlim()) + { + _work.Add(() => + { + try { result = func(); } + catch (Exception ex) { error = ex; } + finally { done.Set(); } + }); + done.Wait(); + } + if (error != null) + throw new AssertFailedException("Work on the live thread failed.", error); + return result; + } + + public void Dispose() + { + _work.CompleteAdding(); + _thread.Join(); + _work.Dispose(); + } + } + + private static OpenTypeFontEngine CreateEngine() + { + return new OpenTypeFontEngine(cfg => + { + foreach (var folder in FontFolders) + cfg.FontDirectories.Add(folder); + cfg.SearchSystemDirectories = false; + }); + } + + /// + /// Shapes text with the engine on the calling thread and returns a weak reference to the + /// shaper. Not inlined, so no strong reference to the shaper is left in the caller. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference ShapeAndGetShaperReference(OpenTypeFontEngine engine) + { + var shaper = engine.GetTextShaper("Roboto", FontSubFamily.Regular); + shaper.Shape("Hello World"); + return new WeakReference(shaper); + } + + /// + /// Creates an engine that is only referenced from this method, shapes text with it on + /// (or the calling thread if null) and abandons it. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference ShapeWithAbandonedEngine(LiveThread? thread) + { + var engine = CreateEngine(); + return thread != null + ? thread.Run(() => ShapeAndGetShaperReference(engine)) + : ShapeAndGetShaperReference(engine); + } + + private static void CollectGarbage() + { + // Twice around the finalizers: an abandoned engine's cache is released by a finalizer. + for (int i = 0; i < 2; i++) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + } + GC.Collect(); + } + + [TestMethod] + public void Dispose_ReleasesShapersCreatedOnOtherThreads() + { + using (var thread = new LiveThread()) + { + var engine = CreateEngine(); + var shaper = thread.Run(() => ShapeAndGetShaperReference(engine)); + + engine.Dispose(); + CollectGarbage(); + + // The engine itself is still referenced: Dispose alone must release the shaper. + Assert.IsFalse(shaper.IsAlive, "The shaper cached on the other thread was not released by Dispose."); + GC.KeepAlive(engine); + } + } + + [TestMethod] + public void AbandonedEngine_ReleasesShapersCreatedOnOtherThreads() + { + using (var thread = new LiveThread()) + { + var shaper = ShapeWithAbandonedEngine(thread); + + CollectGarbage(); + + Assert.IsFalse(shaper.IsAlive, "The shaper cached on the other thread was kept alive after the engine was abandoned."); + } + } + + [TestMethod] + public void AbandonedEngine_ReleasesShapersCreatedOnSameThread() + { + var shaper = ShapeWithAbandonedEngine(null); + + CollectGarbage(); + + Assert.IsFalse(shaper.IsAlive, "The shaper cached on this thread was kept alive after the engine was abandoned."); + } + + [TestMethod] + public void Shapers_AreCachedPerThread() + { + using (var thread = new LiveThread()) + using (var engine = CreateEngine()) + { + var first = engine.GetTextShaper("Roboto", FontSubFamily.Regular); + var second = engine.GetTextShaper("Roboto", FontSubFamily.Regular); + var onOtherThread = thread.Run(() => engine.GetTextShaper("Roboto", FontSubFamily.Regular)); + var onOtherThreadAgain = thread.Run(() => engine.GetTextShaper("Roboto", FontSubFamily.Regular)); + + Assert.AreSame(first, second); + Assert.AreSame(onOtherThread, onOtherThreadAgain); + Assert.AreNotSame(first, onOtherThread); + } + } + + [TestMethod] + public void ClearFontCache_ClearsCurrentThreadOnly() + { + using (var thread = new LiveThread()) + using (var engine = CreateEngine()) + { + var before = engine.GetTextShaper("Roboto", FontSubFamily.Regular); + var otherBefore = thread.Run(() => engine.GetTextShaper("Roboto", FontSubFamily.Regular)); + + engine.ClearFontCache(); + + var after = engine.GetTextShaper("Roboto", FontSubFamily.Regular); + var otherAfter = thread.Run(() => engine.GetTextShaper("Roboto", FontSubFamily.Regular)); + + Assert.AreNotSame(before, after); + Assert.AreSame(otherBefore, otherAfter); + } + } + + [TestMethod] + public void GetTextShaper_AfterDispose_Throws() + { + var engine = CreateEngine(); + engine.GetTextShaper("Roboto", FontSubFamily.Regular); + engine.Dispose(); + + Assert.ThrowsExactly(() => engine.GetTextShaper("Roboto", FontSubFamily.Regular)); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs index 2637e1292..50cabe017 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs @@ -93,7 +93,6 @@ private static byte[] ReadFromTempFile(byte[] fileBytes, long offsetInFile) } [TestMethod] - [Timeout(5000)] public void ReadFontBytes_ValidTtc_ExtractsLoadableFont() { var ttc = BuildRobotoTtc(out var originalBytes); @@ -113,7 +112,6 @@ public void ReadFontBytes_ValidTtc_ExtractsLoadableFont() } [TestMethod] - [Timeout(5000)] public void ReadFontBytes_TableLengthBeyondFile_Throws() { var ttc = BuildRobotoTtc(out _); @@ -124,7 +122,6 @@ public void ReadFontBytes_TableLengthBeyondFile_Throws() } [TestMethod] - [Timeout(5000)] public void ReadFontBytes_OverlappingTables_Throws() { // A small TTC where 1000 table records all point to the whole file. @@ -147,7 +144,6 @@ public void ReadFontBytes_OverlappingTables_Throws() } [TestMethod] - [Timeout(5000)] public void ReadFontBytes_DirectoryBeyondFile_Throws() { // The SFNT header claims 10 tables, but the file ends right after the header. diff --git a/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs index eb5f64c5b..ccf41b8e7 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs @@ -72,7 +72,6 @@ private static long ReadUInt32(byte[] b, int pos) => ((long)b[pos] << 24) | ((long)b[pos + 1] << 16) | ((long)b[pos + 2] << 8) | b[pos + 3]; [TestMethod] - [Timeout(60000)] public void Subset_LargeGpos_RoundTripsWithSameKerning() { // The GPOS of this subset is about 85 KB. Oi itself uses an Extension lookup for that. @@ -98,7 +97,6 @@ public void Subset_LargeGpos_RoundTripsWithSameKerning() } [TestMethod] - [Timeout(10000)] public void Subset_SmallLayoutTables_WrittenWithoutExtensionLookups() { var font = LoadTestFont("Roboto-Regular.ttf"); @@ -112,7 +110,6 @@ public void Subset_SmallLayoutTables_WrittenWithoutExtensionLookups() } [TestMethod] - [Timeout(10000)] public void LookupList_OverflowingGsub_WrittenAsExtensionLookups() { // Three lookups of about 60 KB each: the third lookup starts beyond 64 KB. diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/DocumentFontSubsetBuilderTagTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/DocumentFontSubsetBuilderTagTests.cs index 8ea838cd7..f948fd69a 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/DocumentFontSubsetBuilderTagTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/DocumentFontSubsetBuilderTagTests.cs @@ -4,8 +4,10 @@ using OfficeOpenXml.Interfaces.Fonts; using System.Text.RegularExpressions; +namespace EPPlus.Fonts.OpenType.Tests.Subsetting; + [TestClass] -public class DocumentFontSubsetBuilderTagTests : FontTestBase // adjust to your base class +public class DocumentFontSubsetBuilderTagTests : FontTestBase { private static readonly Regex TaggedName = new Regex("^[A-Z]{6}\\+.+$"); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GlyphClosureLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GlyphClosureLimitTests.cs new file mode 100644 index 000000000..506302f0d --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GlyphClosureLimitTests.cs @@ -0,0 +1,196 @@ +/************************************************************************************************* + 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 Tests for the glyph closure work in subsetting + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Tables.Glyph; +using EPPlus.Fonts.OpenType.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Tests that finding the glyphs a subset needs (components of composite glyphs and glyphs GSUB + /// can substitute in) does work in proportion to the glyphs found, and that a malformed font that + /// chains substitutions across many lookups is stopped at FontSubsettingContext.MaxLayoutSubsetWork. + /// The GSUB fonts are Roboto-Regular.ttf with a crafted GSUB table appended to the end of the file. + /// + [TestClass] + public class GlyphClosureLimitTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private static void WriteUInt16(byte[] b, int pos, int v) + { + b[pos] = (byte)(v >> 8); + b[pos + 1] = (byte)v; + } + + private static void WriteUInt32(byte[] b, int pos, uint v) + { + b[pos] = (byte)(v >> 24); + b[pos + 1] = (byte)(v >> 16); + b[pos + 2] = (byte)(v >> 8); + b[pos + 3] = (byte)v; + } + + /// Returns Roboto with as its GSUB table. + private static OpenTypeFont RobotoWithGsub(byte[] gsub) + { + var font = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf")); + int table = (font.Length + 3) & ~3; + var bytes = new byte[table + gsub.Length]; + Array.Copy(font, bytes, font.Length); + Array.Copy(gsub, 0, bytes, table, gsub.Length); + int record = GsubTestFontBuilder.RecordPosition(bytes, "GSUB"); + WriteUInt32(bytes, record + 8, (uint)table); + WriteUInt32(bytes, record + 12, (uint)gsub.Length); + return new OpenTypeFont(bytes); + } + + /// + /// A GSUB with one SingleSubst format 2 lookup that substitutes glyph i with glyph i + 1 for + /// every glyph below : a chain 0 -> 1 -> ... -> length. + /// + private static byte[] SingleLookupChain(int length) + { + const int lookupList = 10, lookup = 14, subtable = 22; + int coverage = subtable + 6 + 2 * length; + var t = new byte[coverage + 10]; + WriteUInt16(t, 0, 1); // version 1.0, no ScriptList or FeatureList + WriteUInt16(t, 8, lookupList); + WriteUInt16(t, lookupList, 1); // one lookup + WriteUInt16(t, lookupList + 2, lookup - lookupList); + WriteUInt16(t, lookup, 1); // type 1, one subtable + WriteUInt16(t, lookup + 4, 1); + WriteUInt16(t, lookup + 6, subtable - lookup); + WriteUInt16(t, subtable, 2); // format 2: coverage, count, substitutes + WriteUInt16(t, subtable + 2, coverage - subtable); + WriteUInt16(t, subtable + 4, length); + for (int i = 0; i < length; i++) + WriteUInt16(t, subtable + 6 + 2 * i, i + 1); + WriteUInt16(t, coverage, 2); // coverage format 2: one range 0..length-1 + WriteUInt16(t, coverage + 2, 1); + WriteUInt16(t, coverage + 4, 0); + WriteUInt16(t, coverage + 6, length - 1); + WriteUInt16(t, coverage + 8, 0); + return t; + } + + /// + /// A GSUB with lookups, where lookup k substitutes glyph + /// (lookups - k - 1) with glyph (lookups - k): a chain 0 -> 1 -> ... -> lookups listed in + /// reverse order, so every pass over the lookups advances the chain a single step. + /// + private static byte[] ChainAcrossLookups(int lookups) + { + const int lookupList = 10; + const int perLookup = 8 + 6 + 6; // lookup, SingleSubst format 1, coverage + int first = lookupList + 2 + 2 * lookups; + var t = new byte[first + perLookup * lookups]; + WriteUInt16(t, 0, 1); + WriteUInt16(t, 8, lookupList); + WriteUInt16(t, lookupList, lookups); + for (int k = 0; k < lookups; k++) + { + int lookup = first + perLookup * k, subtable = lookup + 8, coverage = subtable + 6; + WriteUInt16(t, lookupList + 2 + 2 * k, lookup - lookupList); + WriteUInt16(t, lookup, 1); // type 1, one subtable + WriteUInt16(t, lookup + 4, 1); + WriteUInt16(t, lookup + 6, subtable - lookup); + WriteUInt16(t, subtable, 1); // format 1: coverage, delta +1 + WriteUInt16(t, subtable + 2, coverage - subtable); + WriteUInt16(t, subtable + 4, 1); + WriteUInt16(t, coverage, 1); // coverage format 1: one glyph + WriteUInt16(t, coverage + 2, 1); + WriteUInt16(t, coverage + 4, lookups - k - 1); + } + return t; + } + + [TestMethod] + public void ResolveCompositeGlyphs_ChainOfComposites_ExaminesEachGlyphOnce() + { + // Glyph i is a composite of glyph i + 1: a chain of 2000 composite glyphs. + const int length = 2000; + var glyphs = new List(); + for (int i = 0; i < length; i++) + { + glyphs.Add(new Glyph + { + Header = new GlyphHeader(-1, default), + CompositeData = new CompositeGlyph { Components = { new GlyphComponent { GlyphIndex = (ushort)(i + 1) } } } + }); + } + var glyphSet = new HashSet { 0 }; + + int examined = new GlyfTable(glyphs).ResolveCompositeGlyphsCountingExamined(glyphSet); + + Assert.AreEqual(length + 1, glyphSet.Count); + Assert.AreEqual(length + 1, examined); + } + + [TestMethod] + public void Discover_SubstitutionChainInOneLookup_WorkGrowsLinearly() + { + const int length = 2000; + var font = RobotoWithGsub(SingleLookupChain(length)); + var context = new FontSubsettingContext(font, new int[0]); + context.IncludedGlyphs.Add(0); + + new GsubSubsetProcessor().Discover(context); + + for (int g = 0; g <= length; g++) + Assert.IsTrue(context.IncludedGlyphs.Contains((ushort)g), "Glyph " + g + " of the chain is missing."); + // One pass finds the chain and a second pass finds nothing new: about two units per glyph. + Assert.IsTrue(context.LayoutSubsetWork <= 3 * (length + 1), "Closure work " + context.LayoutSubsetWork + " for a chain of " + length + "."); + } + + [TestMethod] + public void CreateSubset_ChainAcrossLookups_StopsAtWorkLimit() + { + const int lookups = 1000; + const long limit = 10000; + var font = RobotoWithGsub(ChainAcrossLookups(lookups)); + var context = new FontSubsettingContext(font, new int[0]) { MaxLayoutSubsetWork = limit }; + context.IncludedGlyphs.Add(0); + + new GsubSubsetProcessor().Discover(context); + + Assert.IsTrue(context.LayoutSubsetWorkExceeded); + Assert.IsTrue(context.LayoutSubsetWork <= limit + 1, "Closure work " + context.LayoutSubsetWork + " beyond the limit " + limit + "."); + Assert.IsTrue(context.IncludedGlyphs.Count < lookups, "The search should have stopped before the end of the chain."); + + // A subset made with the same limit is still a valid font. The limit is also used up for + // rewriting GSUB and GPOS, so the subset can have no layout tables left. + var subset = font.CreateSubset("a".ToCharArray(), new SubsetOptions { MaxLayoutSubsetWork = limit }); + var reparsed = new OpenTypeFont(subset.Serialize()); + Assert.IsTrue(reparsed.CmapTable.TryGetGlyphId('a', out _)); + Assert.IsTrue(subset.SubsetGlyphMapping.Count < lookups, "The subset should not contain the whole chain."); + } + + [TestMethod] + public void CreateSubset_ChainAcrossLookupsWithinLimit_IncludesWholeChain() + { + const int lookups = 50; + var font = RobotoWithGsub(ChainAcrossLookups(lookups)); + + var subset = font.CreateSubset("a".ToCharArray()); + + for (int g = 0; g <= lookups; g++) + Assert.IsTrue(subset.SubsetGlyphMapping.ContainsKey((ushort)g), "Glyph " + g + " of the chain is missing."); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs index 01d8c31d6..ec8ae1726 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs @@ -78,7 +78,6 @@ private static int WriteChainingSubtable(byte[] b, int pos, ushort[] coverageGly } [TestMethod] - [Timeout(5000)] public void CreateSubset_SelfReferencingChainingLookup_Completes() { var bytes = PrepareGsub(out int gsub, out var original); @@ -102,7 +101,6 @@ public void CreateSubset_SelfReferencingChainingLookup_Completes() } [TestMethod] - [Timeout(5000)] public void CreateSubset_ChainingLookupReferencingSingleSubst_IncludesSubstitute() { var bytes = PrepareGsub(out int gsub, out var original); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutRewriteLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutRewriteLimitTests.cs new file mode 100644 index 000000000..adc942fec --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutRewriteLimitTests.cs @@ -0,0 +1,172 @@ +/************************************************************************************************* + 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 Tests for the work of rewriting GSUB and GPOS subtables + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Linq; +using System.Text; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Tests that rewriting a GSUB or GPOS subtable for a subset does work in proportion to the + /// subset size, not to the 65535 possible glyph IDs or to everything the coverage lists, and that a + /// malformed font that references the same subtable many times is stopped at + /// FontSubsettingContext.MaxLayoutSubsetWork. The fonts are Roboto-Regular.ttf with a crafted GSUB + /// or GPOS table appended to the end of the file: one lookup with offsets + /// to the same subtable, whose coverage lists every glyph ID. + /// + [TestClass] + public class LayoutRewriteLimitTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private const int References = 1000; + + private static void WriteUInt16(byte[] b, int pos, int v) + { + b[pos] = (byte)(v >> 8); + b[pos + 1] = (byte)v; + } + + private static void WriteUInt32(byte[] b, int pos, uint v) + { + b[pos] = (byte)(v >> 24); + b[pos + 1] = (byte)(v >> 16); + b[pos + 2] = (byte)(v >> 8); + b[pos + 3] = (byte)v; + } + + /// + /// Returns Roboto whose table has one feature + /// with one lookup of , which has + /// offsets to one subtable. is the + /// subtable without its coverage; its coverage offset (bytes 2-3) is filled in and points to a + /// format 2 coverage of glyphs 0-65534 written after it. + /// + private static OpenTypeFont BuildFont(string tableTag, string featureTag, int lookupType, int[] subtable) + { + var font = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf")); + int table = (font.Length + 3) & ~3; + const int featureList = 10; + const int feature = featureList + 8; + const int lookupList = feature + 6; + const int lookup = lookupList + 4; + int sub = lookup + 6 + 2 * References; + int coverage = sub + 2 * subtable.Length; + int length = coverage + 10; + + var bytes = new byte[table + length]; + Array.Copy(font, bytes, font.Length); + int record = GsubTestFontBuilder.RecordPosition(bytes, tableTag); + WriteUInt32(bytes, record + 8, (uint)table); + WriteUInt32(bytes, record + 12, (uint)length); + + // Header: version 1.0, no ScriptList, FeatureList and LookupList + WriteUInt16(bytes, table, 1); + WriteUInt16(bytes, table + 6, featureList); + WriteUInt16(bytes, table + 8, lookupList); + // FeatureList: one feature that uses lookup 0 + WriteUInt16(bytes, table + featureList, 1); + Encoding.ASCII.GetBytes(featureTag).CopyTo(bytes, table + featureList + 2); + WriteUInt16(bytes, table + featureList + 6, feature - featureList); + WriteUInt16(bytes, table + feature + 2, 1); + // LookupList: one lookup with References offsets to the same subtable + WriteUInt16(bytes, table + lookupList, 1); + WriteUInt16(bytes, table + lookupList + 2, lookup - lookupList); + WriteUInt16(bytes, table + lookup, lookupType); + WriteUInt16(bytes, table + lookup + 4, References); + for (int i = 0; i < References; i++) + WriteUInt16(bytes, table + lookup + 6 + 2 * i, sub - lookup); + // The subtable and its coverage: one range 0-65534 + for (int i = 0; i < subtable.Length; i++) + WriteUInt16(bytes, table + sub + 2 * i, subtable[i]); + WriteUInt16(bytes, table + sub + 2, coverage - sub); + WriteUInt16(bytes, table + coverage, 2); + WriteUInt16(bytes, table + coverage + 2, 1); + WriteUInt16(bytes, table + coverage + 4, 0); + WriteUInt16(bytes, table + coverage + 6, 65534); + WriteUInt16(bytes, table + coverage + 8, 0); + return new OpenTypeFont(bytes); + } + + // SinglePos format 1: format, coverage offset, ValueFormat (XAdvance), XAdvance -5 + private static OpenTypeFont SharedSinglePosFont() + { + return BuildFont("GPOS", "kern", 1, new[] { 1, 0, 4, -5 }); + } + + // SingleSubst format 1: format, coverage offset, delta 0 (every glyph substitutes itself) + private static OpenTypeFont SharedSingleSubstFont() + { + return BuildFont("GSUB", "liga", 1, new[] { 1, 0, 0 }); + } + + /// + /// Runs the layout steps of subsetting for the subset of .notdef and 'a' and returns the + /// context, to read the work counted. + /// + private static FontSubsettingContext RewriteLayoutTables(OpenTypeFont font) + { + var context = new FontSubsettingContext(font, new[] { (int)'a' }); + Assert.IsTrue(font.CmapTable.TryGetGlyphId('a', out ushort a)); + foreach (ushort glyph in new ushort[] { 0, a }) + { + context.IncludedGlyphs.Add(glyph); + context.OldToNewGlyphId[glyph] = (ushort)context.NewToOldGlyphId.Count; + context.NewToOldGlyphId.Add(glyph); + } + new GsubSubsetProcessor().Rewrite(context); + new GposSubsetProcessor().Rewrite(context); + return context; + } + + [TestMethod] + public void Rewrite_SharedSinglePosSubtable_WorkGrowsWithSubsetSize() + { + var context = RewriteLayoutTables(SharedSinglePosFont()); + + int subsetSize = context.NewToOldGlyphId.Count; + Assert.IsTrue(context.LayoutSubsetWork <= References * (subsetSize + 1), + "Rewrite work " + context.LayoutSubsetWork + " for " + References + " references and " + subsetSize + " glyphs."); + Assert.AreEqual(References, context.SubsetFont.GposTable.LookupList.Lookups.Single().SubTables.Count); + } + + [TestMethod] + public void Rewrite_SharedSingleSubstSubtable_WorkGrowsWithSubsetSize() + { + var context = RewriteLayoutTables(SharedSingleSubstFont()); + + int subsetSize = context.NewToOldGlyphId.Count; + Assert.IsTrue(context.LayoutSubsetWork <= References * (subsetSize + 1), + "Rewrite work " + context.LayoutSubsetWork + " for " + References + " references and " + subsetSize + " glyphs."); + Assert.AreEqual(References, context.SubsetFont.GsubTable.LookupList.Lookups.Single().SubTables.Count); + } + + [TestMethod] + public void CreateSubset_SharedSubtableBeyondLimit_StopsAndStaysValid() + { + const long limit = 500; + var font = SharedSinglePosFont(); + + var subset = font.CreateSubset("a".ToCharArray(), new SubsetOptions { MaxLayoutSubsetWork = limit }); + var reparsed = new OpenTypeFont(subset.Serialize()); + + Assert.IsTrue(reparsed.CmapTable.TryGetGlyphId('a', out _)); + int subtables = reparsed.GposTable?.LookupList?.Lookups.Sum(l => l.SubTables.Count) ?? 0; + Assert.IsTrue(subtables < References, subtables + " subtables were rewritten; the limit should have stopped the rewrite."); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs index 095c31c30..770a2283b 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs @@ -87,7 +87,6 @@ private static string CharRange(params (int first, int last)[] ranges) } [TestMethod] - [Timeout(10000)] public void Subset_ClassKerning_KeptAsFormat2WithSameAdjustments() { var font = LoadTestFont("Roboto-Regular.ttf"); @@ -100,7 +99,6 @@ public void Subset_ClassKerning_KeptAsFormat2WithSameAdjustments() } [TestMethod] - [Timeout(10000)] public void Subset_ClassKerning_UnusedClassesRemoved() { var font = LoadTestFont("Roboto-Regular.ttf"); @@ -124,7 +122,6 @@ public void Subset_ClassKerning_UnusedClassesRemoved() } [TestMethod] - [Timeout(10000)] public void Subset_ClassKerning_SameGlyphPairKept() { var font = LoadTestFont("Roboto-Regular.ttf"); @@ -139,7 +136,6 @@ public void Subset_ClassKerning_SameGlyphPairKept() } [TestMethod] - [Timeout(60000)] public void Subset_ClassKerningWithManyGlyphs_RoundTripsWithSameAdjustments() { // Expanded to glyph pairs, this subset of Oi's class kerning no longer fit the 16-bit offsets @@ -223,22 +219,21 @@ private static byte[] AppendClassKerningForEveryGlyph(byte[] font) } [TestMethod] - [Timeout(30000)] - public void Subset_ClassKerningCoveringEveryGlyph_CompletesQuickly() + public void Subset_ClassKerningCoveringEveryGlyph_KeptAsOneByOneClassMatrix() { - // A GSUB substitution pulls all 5130 glyphs of the font into the subset and one class - // kerning rule covers every glyph. Expanded to glyph pairs that is about 26 million pairs - // (and grows with the square of the glyph count, up to 65535); kept as format 2 it is a - // 1x1 class matrix. + // A GSUB substitution pulls 200 glyphs into the subset and one class kerning rule covers + // every glyph. Expanded to glyph pairs that grows with the square of the subset size (a + // subset can have up to 65535 glyphs); kept as format 2 it is a 1x1 class matrix whatever + // the size, so a small subset is enough to show it. + const int SubstitutedGlyphs = 200; var bytes = File.ReadAllBytes(Path.Combine(FontFolder, "NotoSansMath-Regular.ttf")); - int numGlyphs = new OpenTypeFont(bytes).MaxpTable.numGlyphs; - var sequence = Enumerable.Range(1, numGlyphs - 1).Select(g => (ushort)g).ToArray(); + var sequence = Enumerable.Range(1, SubstitutedGlyphs).Select(g => (ushort)g).ToArray(); bytes = GsubTestFontBuilder.AppendMultipleSubst(bytes, 'a', sequence); var font = new OpenTypeFont(AppendClassKerningForEveryGlyph(bytes)); var subset = font.CreateSubset("a".ToCharArray()); - Assert.AreEqual(numGlyphs, subset.SubsetGlyphMapping.Count); + Assert.IsTrue(sequence.All(subset.SubsetGlyphMapping.ContainsKey), "Every substituted glyph must be in the subset."); var table = subset.GposTable.LookupList.Lookups.SelectMany(l => l.SubTables).OfType().Single(); Assert.AreEqual(1, table.Class1Count); Assert.AreEqual(1, table.Class2Count); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs index 3a2cd1226..3ba8c3dd2 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs @@ -38,7 +38,6 @@ private static byte[] BuildFontWithMultipleSubst(ushort[] sequence) } [TestMethod] - [Timeout(10000)] public void CreateSubset_SubstitutionToEveryGlyphId_Completes() { // Glyphs 1..65535; together with .notdef that is every possible glyph ID. @@ -56,7 +55,6 @@ public void CreateSubset_SubstitutionToEveryGlyphId_Completes() } [TestMethod] - [Timeout(10000)] public void CreateSubset_SubstitutionToMissingGlyphs_OnlyExistingGlyphsIncluded() { var font = new OpenTypeFont(BuildFontWithMultipleSubst(new ushort[] { 5, 60000, 60001 })); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetTagTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetTagTests.cs index c24098f4d..fa4563f00 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetTagTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetTagTests.cs @@ -6,6 +6,8 @@ using OfficeOpenXml.Interfaces.Fonts; using System.Text.RegularExpressions; +namespace EPPlus.Fonts.OpenType.Tests.Subsetting; + [TestClass] public class SubsetTagTests : FontTestBase { diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs index 76acbcb6c..22630b956 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs @@ -196,7 +196,6 @@ private static byte[] BuildFontWithAmplifyingName() } [TestMethod] - [Timeout(5000)] public void Load_AmplifyingKern_TableIgnoredWithWarning() { var font = new OpenTypeFont(BuildFontWithAmplifyingKern()); @@ -211,7 +210,6 @@ public void Load_AmplifyingKern_TableIgnoredWithWarning() } [TestMethod] - [Timeout(5000)] public void Load_AmplifyingCmap_ThrowsInvalidDataException() { var bytes = BuildFontWithAmplifyingCmap(); @@ -225,7 +223,6 @@ public void Load_AmplifyingCmap_ThrowsInvalidDataException() } [TestMethod] - [Timeout(5000)] public void Load_AmplifyingName_ThrowsInvalidDataException() { var bytes = BuildFontWithAmplifyingName(); @@ -239,7 +236,6 @@ public void Load_AmplifyingName_ThrowsInvalidDataException() } [TestMethod] - [Timeout(5000)] public void ScanSingleFace_AmplifyingName_ThrowsInvalidDataException() { string path = Path.Combine(Path.GetTempPath(), "epplus-budgettest-" + Guid.NewGuid().ToString("N") + ".ttf"); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs index 4e75ecba2..d0c493400 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs @@ -41,7 +41,6 @@ private static CmapSubtable12 CreateSubtable(params (uint start, uint end, uint } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_EndCharCodeMaxUInt_TerminatesAndClampsToUnicodeMax() { var subtable = CreateSubtable((0x10FFF0u, 0xFFFFFFFFu, 1u)); @@ -54,7 +53,6 @@ public void GetGlyphMappings_EndCharCodeMaxUInt_TerminatesAndClampsToUnicodeMax( } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_EndBeforeStart_GroupIsIgnored() { var subtable = CreateSubtable((0x50u, 0x40u, 1u)); @@ -66,7 +64,6 @@ public void GetGlyphMappings_EndBeforeStart_GroupIsIgnored() } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_OverlappingGroups_FirstGroupWinsAndNoDuplicates() { // Both groups cover A-Z, with different glyph ids. @@ -87,7 +84,6 @@ public void GetGlyphMappings_OverlappingGroups_FirstGroupWinsAndNoDuplicates() } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_ValidGroups_MappedAsBefore() { var subtable = CreateSubtable( diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs index 74bb9af18..feeac6ca2 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs @@ -39,7 +39,6 @@ private static CmapSubtable4 CreateSubtable( } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_ManyOverlappingFullRangeSegments_NoDuplicates() { // 1000 segments covering 0x0000-0xFFFE, followed by the required 0xFFFF segment. @@ -67,7 +66,6 @@ public void GetGlyphMappings_ManyOverlappingFullRangeSegments_NoDuplicates() } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_OverlappingSegments_MatchesMapCodePointToGlyph() { // Two segments both covering A-Z with different deltas. @@ -88,7 +86,6 @@ public void GetGlyphMappings_OverlappingSegments_MatchesMapCodePointToGlyph() } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_EndBeforeStart_SegmentIsIgnored() { var subtable = CreateSubtable( @@ -104,7 +101,6 @@ public void GetGlyphMappings_EndBeforeStart_SegmentIsIgnored() } [TestMethod] - [Timeout(5000)] public void GetGlyphMappings_ValidSegmentsWithGlyphIdArray_MappedAsBefore() { // Segment 0: A-C via GlyphIdArray. idRangeOffset 4 -> index = 4/2 + (c - start) - (2 - 0) = c - start. diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs index 972c66ee4..26efbeb6e 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs @@ -46,7 +46,6 @@ private static void WriteGlyphHeader(List bytes, short numberOfContours) // --------------------------------------------------------------------------------- [TestMethod] - [Timeout(5000)] public void Deserialize_SimpleGlyphFlagsBeyondGlyphEnd_Throws() { var bytes = new List(); @@ -66,7 +65,6 @@ public void Deserialize_SimpleGlyphFlagsBeyondGlyphEnd_Throws() } [TestMethod] - [Timeout(5000)] public void Deserialize_CompositeComponentsBeyondGlyphEnd_Throws() { const int MoreComponents = 0x0020; @@ -87,7 +85,6 @@ public void Deserialize_CompositeComponentsBeyondGlyphEnd_Throws() } [TestMethod] - [Timeout(5000)] public void Deserialize_ValidSimpleGlyph_ReadsWithinRange() { var bytes = new List(); @@ -140,7 +137,6 @@ private static void WriteLoca16(byte[] bytes, int locaOffset, int index, int val } [TestMethod] - [Timeout(5000)] public void Load_LocaOffsetsNotAscending_GlyphIsNullOthersLoad() { var bytes = LoadRobotoBytes(out int locaOffset, out int numGlyphs); @@ -164,23 +160,31 @@ public void Load_LocaOffsetsNotAscending_GlyphIsNullOthersLoad() } [TestMethod] - [Timeout(5000)] - public void Load_LocaWithTinyOverlappingRegions_CompletesQuickly() + public void Load_LocaWithTinyOverlappingRegions_StopsAtEachGlyphRange() { var bytes = LoadRobotoBytes(out int locaOffset, out int numGlyphs); var original = new OpenTypeFont((byte[])bytes.Clone()); int originalNonEmpty = original.GlyfTable.Glyphs.Count(g => g != null); - // Ascending entries 16 bytes apart: each glyph gets a range too small for its - // real data, so parsing must stop at the range end instead of expanding further. + // Ascending entries 16 bytes apart for the first glyphs: each gets a range too small for + // its real data, so parsing must stop at the range end instead of reading further. The + // remaining glyphs get empty ranges and are not parsed. + const int Broken = 64; + const int RangeLength = 16; for (int i = 0; i <= numGlyphs; i++) - WriteLoca16(bytes, locaOffset, i, i * 8); // short loca stores offset / 2 + WriteLoca16(bytes, locaOffset, i, System.Math.Min(i, Broken) * RangeLength / 2); // short loca stores offset / 2 var font = new OpenTypeFont(bytes); var glyf = font.GlyfTable; Assert.IsNotNull(glyf); Assert.IsTrue(glyf.Glyphs.Count(g => g != null) < originalNonEmpty); + for (int i = 0; i < Broken; i++) + { + var glyph = glyf.Glyphs[i]; + Assert.IsTrue(glyph == null || glyph.GetSize() <= RangeLength, + "Glyph " + i + " was read beyond its " + RangeLength + " byte range."); + } } } } diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs index f68f0dd91..f77a9c032 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs @@ -38,7 +38,6 @@ private static void Write(List bytes, ushort v) } [TestMethod] - [Timeout(5000)] public void Deserialize_ZeroMarkClassCount_ReturnsNull() { var bytes = new List(); @@ -54,7 +53,6 @@ public void Deserialize_ZeroMarkClassCount_ReturnsNull() } [TestMethod] - [Timeout(5000)] public void Deserialize_ValidSubtable_ReadAsBefore() { var bytes = new List(); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs index c904f2136..d9c4d942e 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs @@ -56,7 +56,6 @@ private static PairPosSubTableFormat2 Deserialize(byte[] bytes) } [TestMethod] - [Timeout(5000)] public void Deserialize_EmptyValueFormatsWithHugeClassCounts_ReturnsNull() { var bytes = BuildSubtable(0, 0, 65535, 65535); @@ -66,7 +65,6 @@ public void Deserialize_EmptyValueFormatsWithHugeClassCounts_ReturnsNull() } [TestMethod] - [Timeout(5000)] public void Deserialize_ClassCountsExceedingAvailableData_ReturnsNull() { var bytes = BuildSubtable(ValueFormatXAdvance, 0, 65535, 65535); @@ -75,7 +73,6 @@ public void Deserialize_ClassCountsExceedingAvailableData_ReturnsNull() } [TestMethod] - [Timeout(5000)] public void Deserialize_ValidSmallMatrix_ReadsValues() { var bytes = BuildSubtable(ValueFormatXAdvance, 0, 2, 2, 10, 20, 30, 40); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs index 0e3d5d442..fa6b0cca3 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs @@ -66,7 +66,6 @@ private static SinglePosSubTableFormat2 Deserialize(byte[] bytes) } [TestMethod] - [Timeout(5000)] public void Deserialize_ZeroValueFormatWithHugeValueCount_DoesNotAllocateRecords() { var subtable = Deserialize(BuildSubtable(0, 65535, new short[0], null)); @@ -77,7 +76,6 @@ public void Deserialize_ZeroValueFormatWithHugeValueCount_DoesNotAllocateRecords } [TestMethod] - [Timeout(5000)] public void TryGetAdjustment_ZeroValueFormat_CoveredGlyphReturnsEmptyAdjustment() { var subtable = Deserialize(BuildSubtable(0, 2, new short[0], new ushort[] { 5, 7 })); @@ -94,7 +92,6 @@ public void TryGetAdjustment_ZeroValueFormat_CoveredGlyphReturnsEmptyAdjustment( } [TestMethod] - [Timeout(5000)] public void Deserialize_ValueCountExceedingAvailableData_ReturnsNull() { var subtable = Deserialize(BuildSubtable(ValueFormatXAdvance, 65535, new short[0], null)); @@ -103,7 +100,6 @@ public void Deserialize_ValueCountExceedingAvailableData_ReturnsNull() } [TestMethod] - [Timeout(5000)] public void Deserialize_ValidRecords_ReadAsBefore() { var subtable = Deserialize(BuildSubtable(ValueFormatXAdvance, 2, new short[] { 10, 20 }, new ushort[] { 5, 7 })); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs index 996b842fc..dcf5d7eff 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs @@ -92,7 +92,6 @@ private static LigatureSubstSubTable Deserialize(byte[] bytes) } [TestMethod] - [Timeout(5000)] public void Deserialize_OverlappingCoverageRanges_ExpandsOnlyLigatureSetCount() { // 65535 ranges each covering every glyph: fully expanded that is over 4 billion glyphs. @@ -107,7 +106,6 @@ public void Deserialize_OverlappingCoverageRanges_ExpandsOnlyLigatureSetCount() } [TestMethod] - [Timeout(5000)] public void Deserialize_DuplicateGlyphInCoverage_KeepsFirstSet() { var subTable = Deserialize(BuildSubtable(CoverageFormat1(5, 5), 100, 200)); @@ -117,7 +115,6 @@ public void Deserialize_DuplicateGlyphInCoverage_KeepsFirstSet() } [TestMethod] - [Timeout(5000)] public void Deserialize_ValidSubtable_MapsLigatureSetsAsBefore() { var subTable = Deserialize(BuildSubtable(CoverageFormat2((5, 6, 0)), 100, 200)); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs index f2fba32a9..34b071ef6 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs @@ -93,7 +93,6 @@ private static byte[] BuildFontWithAmplifyingGpos() } [TestMethod] - [Timeout(5000)] public void Load_AmplifyingGpos_TableIgnoredWithWarning() { var font = new OpenTypeFont(BuildFontWithAmplifyingGpos()); @@ -107,7 +106,6 @@ public void Load_AmplifyingGpos_TableIgnoredWithWarning() } [TestMethod] - [Timeout(5000)] public void GetFromBytes_AmplifyingGpos_LogsFontTableIgnoredWarning() { var log = new CollectingFontLogger(); @@ -127,7 +125,6 @@ public void GetFromBytes_AmplifyingGpos_LogsFontTableIgnoredWarning() } [TestMethod] - [Timeout(5000)] public void GetFromBytes_ValidFont_NoWarningsAndTablesLoaded() { var log = new CollectingFontLogger(); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs index 34282aa5d..d1c47c7f7 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs @@ -63,7 +63,6 @@ private static byte[] RobotoWithHugeNameLength() } [TestMethod] - [Timeout(5000)] public void Constructor_TableLengthBeyondData_Throws() { var bytes = RobotoWithHugeNameLength(); @@ -73,7 +72,6 @@ public void Constructor_TableLengthBeyondData_Throws() } [TestMethod] - [Timeout(5000)] public void Constructor_TableOffsetBeyondData_Throws() { var bytes = LoadRoboto(); @@ -84,7 +82,6 @@ public void Constructor_TableOffsetBeyondData_Throws() } [TestMethod] - [Timeout(5000)] public void Constructor_DirectoryBeyondData_Throws() { // A 20-byte font whose header claims 10 tables (160 bytes of directory). @@ -97,7 +94,6 @@ public void Constructor_DirectoryBeyondData_Throws() } [TestMethod] - [Timeout(5000)] public void Constructor_DuplicateTag_Throws() { var bytes = LoadRoboto(); @@ -109,7 +105,6 @@ public void Constructor_DuplicateTag_Throws() } [TestMethod] - [Timeout(5000)] public void ScanSingleFace_TableLengthBeyondFile_Throws() { string path = Path.Combine(Path.GetTempPath(), "epplus-dirtest-" + Guid.NewGuid().ToString("N") + ".ttf"); @@ -126,7 +121,6 @@ public void ScanSingleFace_TableLengthBeyondFile_Throws() } [TestMethod] - [Timeout(5000)] public void GetAllScannedFontsInPath_CorruptFont_IsSkipped() { string dir = Path.Combine(Path.GetTempPath(), "epplus-dirtest-" + Guid.NewGuid().ToString("N")); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs index ebacc2379..085563d6d 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs @@ -57,7 +57,6 @@ private static TestTableLoader CreateLoader() } [TestMethod] - [Timeout(5000)] public void Load_AfterFailedLoad_NextCallDoesNotHang() { var loader = CreateLoader(); @@ -77,7 +76,6 @@ public void Load_AfterFailedLoad_NextCallDoesNotHang() } [TestMethod] - [Timeout(5000)] public void Load_FailedLoad_ReleasesWaitingThread() { var loader = CreateLoader(); @@ -117,7 +115,6 @@ public void Load_FailedLoad_ReleasesWaitingThread() } [TestMethod] - [Timeout(5000)] public void Load_Success_IsCachedAsBefore() { var loader = CreateLoader(); diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/KerningCacheTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/KerningCacheTests.cs new file mode 100644 index 000000000..a15e3e90c --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/KerningCacheTests.cs @@ -0,0 +1,123 @@ +/************************************************************************************************* + 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 Tests for the kerning cache + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.TextShaping; +using EPPlus.Fonts.OpenType.TextShaping.Kerning; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using OfficeOpenXml.Interfaces.Fonts; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Tests.TextShaping +{ + /// + /// Tests that the kerning cache keeps values apart per glyph pair, script and language, holds + /// at most KerningCache.MaxEntries pairs, and that starting over never changes kerning. + /// + [TestClass] + public class KerningCacheTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private const string SampleText = "AVAWAY To Ta Ty Yo We Wa LT P. F, V. \"Tolerance\""; + + [TestMethod] + public void TryGet_ReturnsStoredValue() + { + var cache = new KerningCache(); + cache.Set(10, 20, "latn", null, -42); + + Assert.IsTrue(cache.TryGet(10, 20, "latn", null, out short value)); + Assert.AreEqual((short)-42, value); + } + + [TestMethod] + public void TryGet_MissingPair_ReturnsFalse() + { + var cache = new KerningCache(); + cache.Set(10, 20, "latn", null, -42); + + Assert.IsFalse(cache.TryGet(10, 21, "latn", null, out _)); + Assert.IsFalse(cache.TryGet(10, 20, "grek", null, out _)); + } + + [TestMethod] + public void Values_AreKeptPerScriptAndLanguage() + { + var cache = new KerningCache(); + cache.Set(1, 2, "latn", null, 1); + cache.Set(1, 2, "cyrl", null, 2); + cache.Set(1, 2, "latn", "TRK", 3); + cache.Set(1, 2, null, null, 4); + + Assert.IsTrue(cache.TryGet(1, 2, "latn", null, out short latin)); + Assert.IsTrue(cache.TryGet(1, 2, "cyrl", null, out short cyrillic)); + Assert.IsTrue(cache.TryGet(1, 2, "latn", "TRK", out short turkish)); + Assert.IsTrue(cache.TryGet(1, 2, null, null, out short noScript)); + Assert.AreEqual((short)1, latin); + Assert.AreEqual((short)2, cyrillic); + Assert.AreEqual((short)3, turkish); + Assert.AreEqual((short)4, noScript); + Assert.AreEqual(4, cache.Count); + } + + [TestMethod] + public void Values_DistinguishGlyphOrder() + { + var cache = new KerningCache(); + cache.Set(1, 2, "latn", null, -10); + cache.Set(2, 1, "latn", null, -20); + + Assert.IsTrue(cache.TryGet(1, 2, "latn", null, out short forward)); + Assert.IsTrue(cache.TryGet(2, 1, "latn", null, out short backward)); + Assert.AreEqual((short)-10, forward); + Assert.AreEqual((short)-20, backward); + } + + [TestMethod] + public void Set_BeyondMaxEntries_StaysWithinLimit() + { + var cache = new KerningCache(); + int pairs = KerningCache.MaxEntries + 1; + for (int i = 0; i < pairs; i++) + cache.Set((ushort)(i >> 8), (ushort)(i & 0xFF), "latn", null, (short)(i & 0x7FFF)); + + Assert.IsTrue(cache.Count <= KerningCache.MaxEntries, "Count " + cache.Count + " exceeds MaxEntries."); + int last = pairs - 1; + Assert.IsTrue(cache.TryGet((ushort)(last >> 8), (ushort)(last & 0xFF), "latn", null, out short value)); + Assert.AreEqual((short)(last & 0x7FFF), value); + } + + [TestMethod] + public void GetKerning_AfterCacheHasStartedOver_GivesSameValues() + { + var font = TestFolderEngine.LoadFont("Roboto", FontSubFamily.Regular); + var glyphs = new TextShaper(TestFolderEngine, font).Shape(SampleText).Glyphs.Select(g => g.GlyphId).ToArray(); + + var reference = new KerningProvider(font); + var used = new KerningProvider(font); + // More distinct pairs than the cache holds, so it starts over at least once. + for (int left = 0; left < 300; left++) + for (int right = 0; right < 300; right++) + used.GetKerning((ushort)left, (ushort)right, "latn", null); + + int kerned = 0; + for (int i = 0; i + 1 < glyphs.Length; i++) + { + short expected = reference.GetKerning(glyphs[i], glyphs[i + 1], "latn", null); + Assert.AreEqual(expected, used.GetKerning(glyphs[i], glyphs[i + 1], "latn", null)); + if (expected != 0) + kerned++; + } + Assert.IsTrue(kerned > 0, "The sample text should contain kerned pairs."); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs index e7aa79a5b..3bbd012cb 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs @@ -68,7 +68,6 @@ private OpenTypeFont LoadFontWithSequence(int sequenceLength, out ushort glyphId } [TestMethod] - [Timeout(5000)] public void Shape_SequenceLongerThanLimit_GlyphNotExpanded() { var font = LoadFontWithSequence(65535, out ushort glyphIdX, out _); @@ -81,7 +80,6 @@ public void Shape_SequenceLongerThanLimit_GlyphNotExpanded() } [TestMethod] - [Timeout(5000)] public void Shape_SequenceAtLimit_IsExpanded() { int limit = MultipleSubstitutionProcessor.MaxSequenceLength; diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs index 1fb8d2f87..17209d029 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs @@ -9,11 +9,16 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 12/01/2026 EPPlus Software AB Tests for the shaping subtable reference limit + 12/03/2026 EPPlus Software AB Assert the limit instead of the time taken *************************************************************************************************/ using EPPlus.Fonts.OpenType.TextShaping; +using EPPlus.Fonts.OpenType.TextShaping.Contextual; +using EPPlus.Fonts.OpenType.TextShaping.Kerning; +using EPPlus.Fonts.OpenType.TextShaping.Ligatures; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; +using System.Linq; using System.Text; namespace EPPlus.Fonts.OpenType.Tests.TextShaping @@ -21,7 +26,7 @@ namespace EPPlus.Fonts.OpenType.Tests.TextShaping /// /// Tests that a font whose feature lists the same lookup many times, with a lookup that has many /// offsets to the same subtable, cannot make building and using a TextShaper grow with the square - /// of the table size (ShapingLimits.MaxSubtableReferences). + /// of the table size: the processors stop collecting at ShapingLimits.MaxSubtableReferences. /// The fonts are Roboto-Regular.ttf with a crafted GPOS or GSUB table appended to the end of the file. /// [TestClass] @@ -29,8 +34,10 @@ public class ShapingLookupReferenceLimitTests : FontTestBase { public override TestContext? TestContext { get; set; } - // 30000 lookup references x 30000 subtable offsets = 900 million subtable references. - private const int RepeatCount = 30000; + // 300 lookup references x 300 subtable offsets = 90000 subtable references, more than + // ShapingLimits.MaxSubtableReferences. Kept small so the tests stay fast; a malformed + // font can repeat far more, and without the limit the work grows with the square. + private const int RepeatCount = 300; private static void WriteUInt16(byte[] b, int pos, int v) { @@ -101,44 +108,45 @@ private static byte[] BuildFont(string tableTag, string featureTag, int lookupTy return bytes; } + // Lookups whose subtables are all collected (ligature and contextual lookups) count as + // RepeatCount references each, so only this many fit within the limit. + private const int WholeLookupsWithinLimit = ShapingLimits.MaxSubtableReferences / RepeatCount; + [TestMethod] - [Timeout(5000)] - public void TextShaper_RepeatedGposLookupReferences_BuildsAndShapesQuickly() + public void GposKerning_RepeatedLookupReferences_StopsAtSubtableReferenceLimit() { // PairPos format 1: format, coverage offset, ValueFormat1 (XAdvance), ValueFormat2, PairSetCount 0 var font = new OpenTypeFont(BuildFont("GPOS", "kern", 2, new[] { 1, 0, 4, 0, 0 }, true, RepeatCount)); - var shaper = new TextShaper(TestFolderEngine, font); - var shaped = shaper.Shape("AVAV"); + var subtables = GposKerningProvider.FindAllKerningSubtables(font.GposTable); - Assert.AreEqual(4, shaped.Glyphs.Length); + Assert.AreEqual(ShapingLimits.MaxSubtableReferences, subtables.Count); + Assert.AreEqual(4, new TextShaper(TestFolderEngine, font).Shape("AVAV").Glyphs.Length); } [TestMethod] - [Timeout(5000)] - public void TextShaper_RepeatedGsubLookupReferences_BuildsAndShapesQuickly() + public void Ligatures_RepeatedLookupReferences_StopsAtSubtableReferenceLimit() { // LigatureSubst format 1: format, coverage offset, LigatureSetCount 0 var font = new OpenTypeFont(BuildFont("GSUB", "liga", 4, new[] { 1, 0, 0 }, true, RepeatCount)); - var shaper = new TextShaper(TestFolderEngine, font); - var shaped = shaper.Shape("office"); + var lookups = LigatureProcessor.BuildLookupsByFeatureTag(font.GsubTable); - Assert.AreEqual(6, shaped.Glyphs.Length); + Assert.AreEqual(WholeLookupsWithinLimit, lookups["liga"].Count); + Assert.AreEqual(6, new TextShaper(TestFolderEngine, font).Shape("office").Glyphs.Length); } [TestMethod] - [Timeout(5000)] - public void TextShaper_RepeatedGsubContextualLookupReferences_ShapesQuickly() + public void ContextualSubstitution_RepeatedLookupReferences_StopsAtSubtableReferenceLimit() { // ChainContextSubst format 3 with no glyph sequences: format, backtrack count 0, input count 0, - // lookahead count 0, substitution count 0. ChainingContextualProcessor collects these lookups - // on every call, so shape several times. + // lookahead count 0, substitution count 0. var font = new OpenTypeFont(BuildFont("GSUB", "calt", 6, new[] { 3, 0, 0, 0, 0 }, false, RepeatCount)); - var shaper = new TextShaper(TestFolderEngine, font); - for (int i = 0; i < 5; i++) - Assert.AreEqual(4, shaper.Shape("text").Glyphs.Length); + var lookups = ChainingContextualProcessor.FindContextualLookupsForFeature(font.GsubTable, "calt", null, null); + + Assert.AreEqual(WholeLookupsWithinLimit, lookups.Count); + Assert.AreEqual(4, new TextShaper(TestFolderEngine, font).Shape("text").Glyphs.Length); } } } diff --git a/src/EPPlus.Fonts.OpenType.Tests/VariableFonts/VariableFontMatchingTests .cs b/src/EPPlus.Fonts.OpenType.Tests/VariableFonts/VariableFontMatchingTests.cs similarity index 100% rename from src/EPPlus.Fonts.OpenType.Tests/VariableFonts/VariableFontMatchingTests .cs rename to src/EPPlus.Fonts.OpenType.Tests/VariableFonts/VariableFontMatchingTests.cs diff --git a/src/EPPlus.Fonts.OpenType/FontCache/ShaperCache.cs b/src/EPPlus.Fonts.OpenType/FontCache/ShaperCache.cs index 672ccdf10..07eea4712 100644 --- a/src/EPPlus.Fonts.OpenType/FontCache/ShaperCache.cs +++ b/src/EPPlus.Fonts.OpenType/FontCache/ShaperCache.cs @@ -9,11 +9,13 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 09/02/2026 EPPlus Software AB Extracted from OpenTypeFontEngine + 12/02/2026 EPPlus Software AB Per-instance thread-local storage, released on Dispose *************************************************************************************************/ using EPPlus.Fonts.OpenType.TextShaping; using OfficeOpenXml.Interfaces.Drawing.Text; using OfficeOpenXml.Interfaces.Fonts; using System.Collections.Generic; +using System.Threading; namespace EPPlus.Fonts.OpenType.FontCache { @@ -29,16 +31,16 @@ namespace EPPlus.Fonts.OpenType.FontCache /// Rendering and measurement shapers are kept in separate dictionaries. A measurement request /// may store a metrics-only shaper, and a shared dictionary keyed only on font name and /// subfamily would let a later rendering request find it. + /// + /// The storage is a owned by this instance, not a static + /// thread-static field. releases the shapers on every thread, and if the + /// engine is abandoned without Dispose, the ThreadLocal's finalizer does the same. A static + /// per-thread map kept every engine's shapers, and so its fonts, alive for as long as each + /// thread lived, which for thread-pool threads is the life of the process. /// internal class ShaperCache { - /// - /// Keyed on the cache instance rather than the engine. Keying on the engine would leave - /// this class depending on the one it was extracted from, and the engine already owns - /// exactly one of these. - /// - [System.ThreadStatic] - private static Dictionary _threadLocal; + private readonly ThreadLocal _entries = new ThreadLocal(() => new Entries()); private class Entries { @@ -51,48 +53,41 @@ private class Entries internal bool TryGetRendering(string key, out TextShaper shaper) { - return GetOrCreateEntries().Rendering.TryGetValue(key, out shaper); + return _entries.Value.Rendering.TryGetValue(key, out shaper); } internal void AddRendering(string key, TextShaper shaper) { - GetOrCreateEntries().Rendering[key] = shaper; + _entries.Value.Rendering[key] = shaper; } internal bool TryGetMeasurement(string key, out ITextShaper shaper) { - return GetOrCreateEntries().Measurement.TryGetValue(key, out shaper); + return _entries.Value.Measurement.TryGetValue(key, out shaper); } internal void AddMeasurement(string key, ITextShaper shaper) { - GetOrCreateEntries().Measurement[key] = shaper; + _entries.Value.Measurement[key] = shaper; } /// - /// Clears this cache for the calling thread only. Other threads see no entry for this - /// cache on their next access and rebuild from scratch. + /// Clears this cache for the calling thread only. Shapers cached on other threads are kept: + /// clearing them while those threads may be using them would not be thread-safe. /// internal void ClearCurrentThread() { - if (_threadLocal != null) - _threadLocal.Remove(this); + if (_entries.IsValueCreated) + _entries.Value = new Entries(); } - private Entries GetOrCreateEntries() + /// + /// Releases the shapers cached on every thread. Called from the engine's Dispose; the cache + /// cannot be used afterwards. + /// + internal void Dispose() { - // [ThreadStatic] field initializers only run on the primary thread. Every other - // thread sees null and must initialize on first use. - if (_threadLocal == null) - _threadLocal = new Dictionary(); - - Entries entries; - if (!_threadLocal.TryGetValue(this, out entries)) - { - entries = new Entries(); - _threadLocal[this] = entries; - } - return entries; + _entries.Dispose(); } } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/FontStore.cs b/src/EPPlus.Fonts.OpenType/FontStore.cs index 1946a4d92..4e0b5f318 100644 --- a/src/EPPlus.Fonts.OpenType/FontStore.cs +++ b/src/EPPlus.Fonts.OpenType/FontStore.cs @@ -10,6 +10,7 @@ Date Author Change ************************************************************************************************* 09/02/2026 EPPlus Software AB Extracted from OpenTypeFontEngine 10/08/2026 EPPlus Software AB Font logging + 12/02/2026 EPPlus Software AB Share parsed fonts between names with the same content *************************************************************************************************/ using EPPlus.Fonts.OpenType.FontResolver; using EPPlus.Fonts.OpenType.Logging; @@ -36,6 +37,12 @@ internal class FontStore : IFontSource private readonly IFontResolver _resolver; private readonly EpplusFontConfiguration _configuration; + // Parsed fonts by content. The font cache above is keyed by the requested name, and many + // names can resolve to the same file: every name the resolver cannot find falls back to + // the same font, and a spreadsheet can use any number of distinct names. Without this, + // each name would parse and keep its own copy of the same font (about 1 MB each). + private readonly Dictionary> _fontsByContent = new Dictionary>(); + // DefaultFontResolver logs the reason for each decision itself. A custom resolver does // not, so for those the store reports a substitution it can observe from the outside. private readonly bool _resolverExplainsItself; @@ -101,14 +108,12 @@ internal OpenTypeFont LoadFont(string fontName, FontSubFamily subFamily, bool ig _fontCache.BeginCache(lockKey); - var font = ResolveAndCreate(_resolver, fontName, subFamily); - - // Only reached on a cache miss, so this reports each font once per engine. - // Held under the per-font lock, which only blocks other loads of the same font. - LogLoaded(fontName, subFamily, font); - - if (font == null) + var bytes = _resolver.ResolveFont(fontName, subFamily); + if (bytes == null) { + // Only reached on a cache miss, so this reports each font once per engine. + LogLoaded(fontName, subFamily, null); + // BeginCache left a not-loaded placeholder. Nothing will ever complete it, // so remove it — otherwise every later GetFromCache for this key spends the // full two-second Monitor.Wait timeout before giving up. @@ -116,9 +121,15 @@ internal OpenTypeFont LoadFont(string fontName, FontSubFamily subFamily, bool ig return null; } - font.EnsureFullyLoaded(); - FontLog.WriteLoadWarnings(Logger, font, fontName); - font.IsReadOnly = true; + bool parsedNow; + var font = GetOrParse(bytes, out parsedNow); + + // Only reached on a cache miss, so this reports each font once per engine. + // Held under the per-font lock, which only blocks other loads of the same font. + LogLoaded(fontName, subFamily, font); + if (parsedNow) + FontLog.WriteLoadWarnings(Logger, font, fontName); + _fontCache.AddToCache(font, lockKey); return font; } @@ -194,6 +205,7 @@ internal void Clear() _fontCache.Clear(); _fontLocks.Clear(); _availability.Clear(); + _fontsByContent.Clear(); } } @@ -280,6 +292,119 @@ internal static string BuildCacheKey(string fontName, FontSubFamily subFamily) return string.Format("{0}_{1}", fontName, subFamily); } + /// + /// Returns the parsed font for . If a font with exactly the same + /// content was parsed before, under any name, that instance is returned and + /// is false. Otherwise the font is parsed, fully loaded and + /// made read-only, and is true. + /// + private OpenTypeFont GetOrParse(byte[] bytes, out bool parsedNow) + { + ulong hash = ComputeContentHash(bytes); + + lock (_syncRoot) + { + var existing = FindParsed(hash, bytes); + if (existing != null) + { + parsedNow = false; + return existing; + } + } + + // Parsed outside the lock so loads of other fonts are not blocked. Callers hold the + // per-name lock only, so two names with the same content can get here at the same time. + var font = new OpenTypeFont(bytes); + font.EnsureFullyLoaded(); + font.IsReadOnly = true; + + lock (_syncRoot) + { + // If another thread parsed the same content meanwhile, use its instance. + var existing = FindParsed(hash, bytes); + if (existing != null) + { + parsedNow = false; + return existing; + } + + List fonts; + if (!_fontsByContent.TryGetValue(hash, out fonts)) + { + fonts = new List(); + _fontsByContent[hash] = fonts; + } + fonts.Add(new ParsedFont(bytes, font)); + } + + parsedNow = true; + return font; + } + + /// + /// Finds a parsed font with the given hash and exactly the same bytes. The bytes are + /// compared, so two different fonts with the same hash are never confused. Call under _syncRoot. + /// + private OpenTypeFont FindParsed(ulong hash, byte[] bytes) + { + List fonts; + if (!_fontsByContent.TryGetValue(hash, out fonts)) + return null; + + foreach (var parsed in fonts) + { + if (BytesEqual(parsed.Bytes, bytes)) + return parsed.Font; + } + return null; + } + + /// + /// 64-bit FNV-1a hash of the font bytes. Not a cryptographic hash: matches are confirmed by + /// comparing the bytes. SHA-256 is avoided because it throws on .NET Framework machines with + /// the FIPS policy enabled. + /// + private static ulong ComputeContentHash(byte[] bytes) + { + ulong hash = 14695981039346656037UL; + for (int i = 0; i < bytes.Length; i++) + { + hash ^= bytes[i]; + hash *= 1099511628211UL; + } + return hash; + } + + private static bool BytesEqual(byte[] a, byte[] b) + { + if (ReferenceEquals(a, b)) + return true; + if (a.Length != b.Length) + return false; + for (int i = 0; i < a.Length; i++) + { + if (a[i] != b[i]) + return false; + } + return true; + } + + /// + /// A parsed font and the bytes it was parsed from. Keeping the bytes costs no memory: + /// already holds a reference to the same array. + /// + private sealed class ParsedFont + { + internal readonly byte[] Bytes; + internal readonly OpenTypeFont Font; + + internal ParsedFont(byte[] bytes, OpenTypeFont font) + { + Bytes = bytes; + Font = font; + } + } + private static OpenTypeFont ResolveAndCreate(IFontResolver resolver, string fontName, FontSubFamily subFamily) { var bytes = resolver.ResolveFont(fontName, subFamily); diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs index 60a7bdc13..67e8371c8 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs @@ -703,7 +703,7 @@ internal OpenTypeFont CreateSubset(IEnumerable usedChars, SubsetOptions op var subsetBuilder = new SubsetFontBuilder(); var codePoints = CodePointUtil.ExtractCodePoints(usedChars); - var newFont = subsetBuilder.CreateSubset(this, codePoints, options.RemoveHinting); + var newFont = subsetBuilder.CreateSubset(this, codePoints, options.RemoveHinting, options.MaxLayoutSubsetWork); if (options.AddSubsetTag) { diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs index 492d5c339..f945d74ce 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs @@ -11,6 +11,7 @@ Date Author Change 05/13/2026 EPPlus Software AB Per-instance font engine. Replaces static OpenTypeFonts. 09/02/2026 EPPlus Software AB Extracted FontStore and ShaperCache; added measurement shaper 10/08/2026 EPPlus Software AB Font logging; replaced Debug.WriteLine in ResolveEmbeddingDecision + 12/02/2026 EPPlus Software AB Dispose releases cached shapers on all threads *************************************************************************************************/ using EPPlus.Fonts.OpenType.FontCache; using EPPlus.Fonts.OpenType.FontResolver; @@ -318,10 +319,9 @@ public void Dispose() if (_disposed) return; _disposed = true; - // Best-effort cleanup of this engine's shaper entries on the disposing thread. - // Entries on other threads are dropped when those threads next touch their map, - // since they will find no entry for this cache and rebuild. - _shaperCache.ClearCurrentThread(); + // Releases this engine's shapers on every thread that used it, not only the + // disposing thread. Each shaper holds a parsed font. + _shaperCache.Dispose(); // Marks the store disposed as well as clearing it, so a DefaultFontProvider that // holds the store directly cannot keep loading fonts after this point. diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs b/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs index 5bd9c700b..1705d91ae 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.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/03/2026 EPPlus Software AB Limit for the work of subsetting GSUB and GPOS *************************************************************************************************/ using System; using System.Collections.Generic; @@ -43,6 +44,58 @@ public class FontSubsettingContext /// internal bool RemoveHinting { get; set; } + /// + /// Default for . + /// About 12 times the most measured for real fonts: 21.5 million for Gabriola subset with + /// all its glyphs, 11.5 million for SansSerifCollection (measured on 560 font faces). A unit + /// takes about 20-60 ns, so a malformed font is stopped after some seconds. + /// + internal const long DefaultMaxLayoutSubsetWork = 256000000; + + /// + /// Maximum work for subsetting the layout tables (GSUB and GPOS): every glyph, ligature or + /// lookup examined when finding the glyphs GSUB and GPOS add, and every glyph examined when a + /// subtable is rewritten for the subset, counts as one. A malformed font can chain + /// substitutions across many lookups so that every pass over the lookups adds a single glyph, + /// or reference the same subtable many times so it is rewritten many times, which makes the + /// work grow with the square of the table size or worse. When the limit is reached the search + /// stops and the remaining subtables are left out; the subset is still a valid font but can + /// lack substitutions or positioning. + /// + internal long MaxLayoutSubsetWork { get; set; } = DefaultMaxLayoutSubsetWork; + + /// + /// The work counted so far, see . + /// + internal long LayoutSubsetWork { get; private set; } + + /// + /// True when the work has reached . + /// + internal bool LayoutSubsetWorkExceeded + { + get { return LayoutSubsetWork >= MaxLayoutSubsetWork; } + } + + /// + /// Counts units of layout subsetting work. Returns false when the + /// limit has been reached and the work should stop. + /// + internal bool CountLayoutSubsetWork(int amount) + { + LayoutSubsetWork += amount; + return LayoutSubsetWork < MaxLayoutSubsetWork; + } + + /// + /// Counts the work of rewriting one subtable, which examines every glyph of the subset once. + /// Returns false when the limit has been reached and the subtable should be left out. + /// + internal bool CountSubtableRewrite() + { + return CountLayoutSubsetWork(Math.Max(1, NewToOldGlyphId.Count)); + } + /// /// Creates a new subsetting context and initializes all collections. /// diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/GsubSubsetProcessor.cs b/src/EPPlus.Fonts.OpenType/Subsetting/GsubSubsetProcessor.cs index ea457b703..65aae234d 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/GsubSubsetProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/GsubSubsetProcessor.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/03/2026 EPPlus Software AB Glyph closure: work list and work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; using EPPlus.Fonts.OpenType.Tables.Gsub.Handlers; @@ -62,12 +63,15 @@ public void Discover(FontSubsettingContext context) foreach (var lookup in gsub.LookupList.Lookups) { - int beforeCount = context.IncludedGlyphs.Count; + // Every lookup examined counts as layout subsetting work, also when it adds nothing. + if (!context.CountLayoutSubsetWork(1)) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. DiscoverLookup(context, lookup); - int afterCount = context.IncludedGlyphs.Count; } - } while (context.IncludedGlyphs.Count > previousGlyphCount); + // A substitution can make another lookup apply, so repeat until nothing is added. + // Every pass examines every lookup again, so the work limit also bounds the passes. + } while (context.IncludedGlyphs.Count > previousGlyphCount && !context.LayoutSubsetWorkExceeded); // .NET 3.5 compatible sorting List finalGlyphs = new List(context.IncludedGlyphs); diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs index 2f197519b..16ded9650 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.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/03/2026 EPPlus Software AB Pass the layout subsetting work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting.Processors; using System; @@ -62,9 +63,19 @@ public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable uni /// The code points the subset must contain. /// True to create an unhinted subset, see . public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable unicodeChars, bool removeHinting) + { + return CreateSubset(originalFont, unicodeChars, removeHinting, FontSubsettingContext.DefaultMaxLayoutSubsetWork); + } + + /// + /// Creates a subset, see , with + /// the given limit for subsetting GSUB and GPOS, see . + /// + internal OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable unicodeChars, bool removeHinting, long maxLayoutSubsetWork) { var context = new FontSubsettingContext(originalFont, unicodeChars); context.RemoveHinting = removeHinting; + context.MaxLayoutSubsetWork = maxLayoutSubsetWork; var processors = Processors; // Step 1: Discovery Phase - All processors identify required glyphs diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetOptions.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetOptions.cs index 6bc430dea..c1e54235f 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetOptions.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetOptions.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 11/23/2026 EPPlus Software AB Unhinted subsets for web output + 12/03/2026 EPPlus Software AB Limit for the work of subsetting GSUB and GPOS *************************************************************************************************/ namespace EPPlus.Fonts.OpenType.Subsetting { @@ -31,5 +32,11 @@ internal sealed class SubsetOptions /// functions in a missing fpgm make the font invalid. /// internal bool RemoveHinting { get; set; } + + /// + /// Maximum work for subsetting GSUB and GPOS, see + /// . + /// + internal long MaxLayoutSubsetWork { get; set; } = FontSubsettingContext.DefaultMaxLayoutSubsetWork; } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs index 12edeee2e..279b2350f 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTable.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/03/2026 EPPlus Software AB Composite glyph closure examines each glyph once *************************************************************************************************/ using EPPlus.Fonts.OpenType.Tables.Loca; using EPPlus.Fonts.OpenType.Tables.Post; @@ -117,32 +118,36 @@ public Glyph GetGlyph(ushort glyphId) /// /// Set of glyph IDs to expand with component dependencies public void ResolveCompositeGlyphs(HashSet glyphSet) + { + ResolveCompositeGlyphsCountingExamined(glyphSet); + } + + /// + /// Adds the components of the composite glyphs in , and their + /// components in turn, and returns the number of glyphs examined. Every glyph is examined + /// once: only glyphs that were just added are examined again, so a long chain of composite + /// glyphs costs time in proportion to its length instead of its square. + /// + internal int ResolveCompositeGlyphsCountingExamined(HashSet glyphSet) { if (glyphSet == null) throw new ArgumentNullException("glyphSet"); - bool addedNew; - do + var pending = new Stack(glyphSet); + int examined = 0; + while (pending.Count > 0) { - addedNew = false; - ushort[] currentGlyphs = new List(glyphSet).ToArray(); // Snapshot for iteration + examined++; + Glyph glyph = this.GetGlyph(pending.Pop()); + if (glyph == null || glyph.Header.numberOfContours >= 0 || glyph.CompositeData == null) + continue; - foreach (ushort gid in currentGlyphs) + foreach (GlyphComponent component in glyph.CompositeData.Components) { - Glyph glyph = this.GetGlyph(gid); - if (glyph != null && - glyph.Header.numberOfContours < 0 && - glyph.CompositeData != null) - { - foreach (GlyphComponent component in glyph.CompositeData.Components) - { - if (glyphSet.Add(component.GlyphIndex)) - { - addedNew = true; - } - } - } + if (glyphSet.Add(component.GlyphIndex)) + pending.Push(component.GlyphIndex); } - } while (addedNew); + } + return examined; } public string GetGlyphName(ushort glyphId, OpenTypeFont font) diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/MarkToBaseHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/MarkToBaseHandler.cs index e7872046d..51ef76641 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/MarkToBaseHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/MarkToBaseHandler.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 01/12/2026 EPPlus Software AB GPOS Type 4 (MarkToBase) handler + 12/03/2026 EPPlus Software AB Rewrite from the subset's glyphs, with a work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -55,6 +56,10 @@ private void DiscoverMarkToBaseSubtable(FontSubsettingContext context, MarkToBas if (subtable.BaseCoverage == null || subtable.MarkCoverage == null) return; + // Examines up to every included glyph and every covered mark. + if (!context.CountLayoutSubsetWork(context.IncludedGlyphs.Count)) + return; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + // Check if any included base glyph exists in this subtable bool hasIncludedBase = false; @@ -73,16 +78,15 @@ private void DiscoverMarkToBaseSubtable(FontSubsettingContext context, MarkToBas // If we have at least one included base, include ALL marks from this subtable if (hasIncludedBase) { - // MarkCoverage.GetGlyphIndex() returns -1 if glyph is not covered - // We need to iterate through all possible glyph IDs to find covered marks - for (ushort markGlyph = 0; markGlyph < 65535; markGlyph++) + // The covered marks, instead of every possible glyph ID. + ushort[] marks = subtable.MarkCoverage.GetCoveredGlyphs(); + if (!context.CountLayoutSubsetWork(marks.Length)) + return; + foreach (ushort markGlyph in marks) { - int markIndex = subtable.MarkCoverage.GetGlyphIndex(markGlyph); - if (markIndex >= 0) - { - // This is a mark glyph - add it to included glyphs + // Glyph 65535 was never examined by the loop over all glyph IDs this replaces. + if (markGlyph != 65535) context.IncludedGlyphs.Add(markGlyph); - } } } } @@ -102,6 +106,9 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable lookup) foreach (var subtable in lookup.SubTables) { + if (!context.CountSubtableRewrite()) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + if (subtable is MarkToBaseSubTableFormat1 format1) { var rewritten = RewriteFormat1(context, format1); @@ -160,7 +167,8 @@ private MarkArray FilterMarkArray(FontSubsettingContext context, MarkToBaseSubTa { var includedRecords = new List(); - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { int coverageIndex = original.MarkCoverage.GetGlyphIndex(oldGlyphId); if (coverageIndex >= 0 && coverageIndex < original.MarkArray.MarkCount) @@ -190,7 +198,8 @@ private BaseArray FilterBaseArray(FontSubsettingContext context, MarkToBaseSubTa { var includedRecords = new List(); - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { int coverageIndex = original.BaseCoverage.GetGlyphIndex(oldGlyphId); if (coverageIndex >= 0 && coverageIndex < original.BaseArray.BaseCount) @@ -223,8 +232,8 @@ private CoverageTable FilterCoverage(FontSubsettingContext context, CoverageTabl var includedGlyphs = new List(); - // Iterate through all glyphs in original coverage - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { if (original.GetGlyphIndex(oldGlyphId) >= 0) { diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs index df1a63eff..127071392 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs @@ -10,6 +10,7 @@ Date Author Change ************************************************************************************************* 01/12/2026 EPPlus Software AB GPOS Type 2 (PairPos) handler 09/07/2026 EPPlus Software AB Sort expanded pair records by second glyph + 12/03/2026 EPPlus Software AB Rewrite from the subset's glyphs, with a work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.ClassDef; @@ -60,6 +61,9 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable lookup) foreach (var subtable in lookup.SubTables) { + if (!context.CountSubtableRewrite()) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + GposSubTableBase rewritten = null; if (subtable is PairPosSubTableFormat1 format1) @@ -88,7 +92,9 @@ private PairPosSubTableFormat1 RewriteFormat1(FontSubsettingContext context, Pai // Build list of included first glyphs with their coverage indices var includedGlyphs = new List(); - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order, so the cost follows the + // subset size instead of the 65535 possible glyph IDs. + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { int coverageIndex = original.Coverage.GetGlyphIndex(oldGlyphId); if (coverageIndex >= 0 && coverageIndex < original.PairSets.Count) diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs index 971a239b3..9456a2907 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 01/12/2026 EPPlus Software AB GPOS Type 1 (SinglePos) handler + 12/03/2026 EPPlus Software AB Rewrite from the subset's glyphs, with a work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -52,6 +53,9 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable lookup) foreach (var subtable in lookup.SubTables) { + if (!context.CountSubtableRewrite()) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + GposSubTableBase rewritten = null; if (subtable is SinglePosSubTableFormat1 format1) @@ -106,7 +110,9 @@ private SinglePosSubTableFormat2 RewriteFormat2(FontSubsettingContext context, S // ValueFormat 0: records are empty and not stored by the deserializer. bool isEmptyFormat = original.ValueFormat == 0; - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order, so the cost follows the + // subset size instead of the 65535 possible glyph IDs. + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { int coverageIndex = original.Coverage.GetGlyphIndex(oldGlyphId); if (coverageIndex >= 0 && (isEmptyFormat ? coverageIndex < original.ValueCount @@ -149,8 +155,8 @@ private CoverageTable FilterCoverage(FontSubsettingContext context, CoverageTabl var includedGlyphs = new List(); - // Iterate through all glyphs in original coverage - for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++) + // The subset's glyphs in ascending original glyph ID order + foreach (ushort oldGlyphId in context.NewToOldGlyphId) { if (original.GetGlyphIndex(oldGlyphId) >= 0) { diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.cs index 340a2e167..022320468 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.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/03/2026 EPPlus Software AB Subset coverages from the subset's glyphs, with a work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -116,15 +117,16 @@ private List RewriteCoverageList(List oldCoverages var newCoverages = new List(); foreach (var cov in oldCoverages) { - var oldGids = cov.GetCoveredGlyphs(); - var validNewGids = new List(); + // The subset's glyphs are examined instead of every glyph the coverage lists, so the + // cost follows the subset size. + if (!context.CountSubtableRewrite()) + return null; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. - foreach (var oldGid in oldGids) + var validNewGids = new List(); + foreach (var oldGid in context.NewToOldGlyphId) { - if (context.OldToNewGlyphId.TryGetValue(oldGid, out ushort newGid)) - { - validNewGids.Add(newGid); - } + if (cov.GetGlyphIndex(oldGid) >= 0) + validNewGids.Add(context.OldToNewGlyphId[oldGid]); } // Om en hel position i sekvensen försvinner, blir regeln ogiltig diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/LigatureSubstHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/LigatureSubstHandler.cs index 54ffdc3f4..7904d1412 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/LigatureSubstHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/LigatureSubstHandler.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/03/2026 EPPlus Software AB Glyph closure and rewrite: work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -40,6 +41,10 @@ public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubs foreach (var kvp in ligSubtable.LigatureSets) { + // Every ligature set and every ligature examined counts as layout subsetting work. + if (!context.CountLayoutSubsetWork(1)) + return; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + ushort firstGlyphId = kvp.Key; if (!context.IncludedGlyphs.Contains(firstGlyphId)) @@ -47,6 +52,9 @@ public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubs foreach (var lig in kvp.Value.Ligatures) { + if (!context.CountLayoutSubsetWork(1)) + return; + if (context.IncludedGlyphs.Contains(lig.LigatureGlyph)) continue; @@ -97,6 +105,10 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) if (oldLigSubtable == null) continue; if (oldLigSubtable.LigatureSets == null) continue; + // Every ligature set examined counts as layout subsetting work. + if (!context.CountLayoutSubsetWork(System.Math.Max(1, oldLigSubtable.LigatureSets.Count))) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + var newSubTable = new LigatureSubstSubTable(); newSubTable.SubtableFormat = 1; newSubTable.LigatureSets = new Dictionary(); diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/MultipleSubstHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/MultipleSubstHandler.cs index b8b34a0af..40737cf2d 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/MultipleSubstHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/MultipleSubstHandler.cs @@ -9,6 +9,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 Date Author Change ************************************************************************************************* 09/09/2026 EPPlus Software AB GSUB Multiple Substitution (Type 2) support + 12/03/2026 EPPlus Software AB Glyph closure and rewrite: work list, subset-sized loops, work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -32,39 +33,34 @@ internal class MultipleSubstHandler : IGsubLookupHandler public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubsetProcessor processor) { - // Loop until no new glyphs are added, in case a substituted glyph is itself the - // trigger for another lookup's substitution (transitive chains), same as - // SingleSubstHandler does. - bool addedAny; - do + // A substituted glyph can itself be substituted (transitive chains). Followed with a work + // list, as in SingleSubstHandler: every glyph is examined once, and a glyph of a sequence + // is examined when it is added. + var subtables = lookup.SubTables.OfType().ToList(); + if (subtables.Count == 0) + return; + + var pending = new Stack(context.IncludedGlyphs); + while (pending.Count > 0) { - addedAny = false; - var currentGlyphs = context.IncludedGlyphs.ToArray(); + if (!context.CountLayoutSubsetWork(subtables.Count)) + return; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. - foreach (var subtable in lookup.SubTables.OfType()) + ushort gid = pending.Pop(); + foreach (var subtable in subtables) { - var coveredGids = subtable.Coverage?.GetCoveredGlyphs(); - if (coveredGids == null) continue; + ushort[] sequence = subtable.GetSubstitution(gid); + if (sequence == null) continue; - foreach (ushort gid in coveredGids) + if (!context.CountLayoutSubsetWork(sequence.Length)) + return; + foreach (ushort outGid in sequence) { - if (!context.IncludedGlyphs.Contains(gid)) - continue; - - ushort[] sequence = subtable.GetSubstitution(gid); - if (sequence == null) continue; - - foreach (ushort outGid in sequence) - { - if (!context.IncludedGlyphs.Contains(outGid)) - { - context.IncludedGlyphs.Add(outGid); - addedAny = true; - } - } + if (context.IncludedGlyphs.Add(outGid)) + pending.Push(outGid); } } - } while (addedAny); + } } public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) @@ -78,17 +74,18 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) foreach (var oldSubtable in oldLookup.SubTables.OfType()) { - var coveredGids = oldSubtable.Coverage?.GetCoveredGlyphs(); - if (coveredGids == null) continue; + if (!context.CountSubtableRewrite()) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + if (oldSubtable.Coverage == null) continue; var newInputs = new List(); var newSequences = new List(); - foreach (ushort oldInputGid in coveredGids) + // 1. Only triggering glyphs that are part of the subset: the subset's glyphs are + // examined instead of every glyph the coverage lists, so the cost follows the subset size. + foreach (ushort oldInputGid in context.NewToOldGlyphId) { - // 1. Is the triggering glyph itself part of the subset? - if (!context.OldToNewGlyphId.TryGetValue(oldInputGid, out ushort newInputGid)) - continue; + ushort newInputGid = context.OldToNewGlyphId[oldInputGid]; ushort[] oldSequence = oldSubtable.GetSubstitution(oldInputGid); if (oldSequence == null) continue; diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/SingleSubstHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/SingleSubstHandler.cs index 3e62d9877..abf0f9ab0 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/SingleSubstHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/SingleSubstHandler.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/03/2026 EPPlus Software AB Glyph closure and rewrite: work list, subset-sized loops, work limit *************************************************************************************************/ using EPPlus.Fonts.OpenType.Subsetting; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; @@ -25,27 +26,27 @@ internal class SingleSubstHandler : IGsubLookupHandler public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubsetProcessor processor) { - // Loop until no new glyphs are added to capture transitive substitution chains - bool glyphsAdded; - do + // Transitive substitution chains (a -> b -> c) are followed with a work list: every glyph + // is examined once, and a substitute is examined when it is added. Re-examining every + // glyph until nothing changes would grow with the square of the chain length. + var subtables = lookup.SubTables.OfType().ToList(); + if (subtables.Count == 0) + return; + + var pending = new Stack(context.IncludedGlyphs); + while (pending.Count > 0) { - glyphsAdded = false; - var currentGlyphs = context.IncludedGlyphs.ToArray(); + if (!context.CountLayoutSubsetWork(subtables.Count)) + return; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. - foreach (var subtable in lookup.SubTables.OfType()) + ushort gid = pending.Pop(); + foreach (var subtable in subtables) { - foreach (ushort gid in currentGlyphs) - { - ushort substitute = subtable.GetSubstitution(gid); - - if (substitute != 0 && !context.IncludedGlyphs.Contains(substitute)) - { - context.IncludedGlyphs.Add(substitute); - glyphsAdded = true; - } - } + ushort substitute = subtable.GetSubstitution(gid); + if (substitute != 0 && context.IncludedGlyphs.Add(substitute)) + pending.Push(substitute); } - } while (glyphsAdded); + } } public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) @@ -54,7 +55,10 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) foreach (var subtable in oldLookup.SubTables.OfType()) { - var oldMappings = GetMappings(subtable); + if (!context.CountSubtableRewrite()) + break; // Malformed font: see FontSubsettingContext.MaxLayoutSubsetWork. + + var oldMappings = GetMappings(context, subtable); var validMappings = new List(); // Remap to subset glyph IDs, keeping only mappings where both input and output glyphs are included @@ -83,12 +87,15 @@ public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) return newLookup.SubTables.Count > 0 ? newLookup : null; } - private Dictionary GetMappings(SingleSubstSubTable subtable) + /// + /// The substitutions of the subtable whose input glyph is in the subset. The subset's glyphs + /// are examined instead of every glyph the coverage lists, so the cost follows the subset size. + /// + private Dictionary GetMappings(FontSubsettingContext context, SingleSubstSubTable subtable) { var mappings = new Dictionary(); - var inputGids = subtable.Coverage.GetCoveredGlyphs(); - foreach (var oldGid in inputGids) + foreach (var oldGid in context.NewToOldGlyphId) { ushort substitutedGid = subtable.GetSubstitution(oldGid); diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs index 504e2ca15..885955945 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs @@ -76,7 +76,7 @@ internal List ApplyContextualSubstitutions( /// legitimately share a tag (one per script); the ScriptList/LangSys lookup is what tells /// them apart, since the tag alone does not. /// - private List FindContextualLookupsForFeature( + internal static List FindContextualLookupsForFeature( GsubTable gsub, string featureTag, string script, string language) { var lookups = new List(); diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs index 4b8ba839b..ed75d19b9 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs @@ -27,7 +27,7 @@ namespace EPPlus.Fonts.OpenType.TextShaping.Kerning /// internal class GposKerningProvider { - private readonly struct IndexedSubtable + internal readonly struct IndexedSubtable { public readonly int FeatureIndex; public readonly PairPosSubTable Subtable; @@ -100,7 +100,7 @@ private HashSet GetActiveIndices(string script, string language) /// index, across all scripts, so GetKerning can filter by script later. Two FeatureRecords /// can legitimately share the "kern" tag (one per script); both are kept. /// - private List FindAllKerningSubtables(GposTable gpos) + internal static List FindAllKerningSubtables(GposTable gpos) { var subtables = new List(); diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KerningCache.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KerningCache.cs index 4b65f10da..3fa61a06c 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KerningCache.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/KerningCache.cs @@ -10,7 +10,9 @@ Date Author Change ************************************************************************************************* 01/15/2025 EPPlus Software AB Initial implementation 09/07/2026 EPPlus Software AB Fold script/language into the cache key + 12/03/2026 EPPlus Software AB Two-level key and a maximum number of entries *************************************************************************************************/ +using System; using System.Collections.Generic; namespace EPPlus.Fonts.OpenType.TextShaping.Kerning @@ -23,14 +25,38 @@ namespace EPPlus.Fonts.OpenType.TextShaping.Kerning /// single cache instance is reused across many Shape() calls that may each specify a different /// script. Keying on the glyph pair alone would let a value computed for one script leak into /// a lookup for another. + /// + /// Stored in two levels: one table per script/language, keyed by the glyph pair packed into a + /// uint. A lookup allocates nothing, and an entry costs about 20 bytes instead of about 115 + /// for a string key. The cache holds at most pairs, so text that + /// uses a very large number of distinct pairs cannot make it grow without bound. /// internal class KerningCache { - private readonly Dictionary _cache; + /// + /// Maximum number of glyph pairs in the cache, about 1.3 MB. When it is full the cache + /// starts over: values are only recomputed, so results never change. Ordinary text uses a + /// few thousand distinct pairs. + /// + internal const int MaxEntries = 65536; + + private readonly Dictionary> _tables = + new Dictionary>(StringComparer.Ordinal); + private int _count; - public KerningCache() + // The table used by the previous call. All pairs in one Shape call share the same + // script and language, so the table key is only built when they change. + private bool _hasLast; + private string _lastScript; + private string _lastLanguage; + private Dictionary _lastTable; + + /// + /// Number of glyph pairs in the cache. + /// + internal int Count { - _cache = new Dictionary(); + get { return _count; } } /// @@ -38,8 +64,13 @@ public KerningCache() /// public bool TryGet(ushort leftGlyph, ushort rightGlyph, string script, string language, out short value) { - string key = MakeKey(leftGlyph, rightGlyph, script, language); - return _cache.TryGetValue(key, out value); + var table = GetTable(script, language, false); + if (table == null) + { + value = 0; + return false; + } + return table.TryGetValue(PairKey(leftGlyph, rightGlyph), out value); } /// @@ -47,8 +78,21 @@ public bool TryGet(ushort leftGlyph, ushort rightGlyph, string script, string la /// public void Set(ushort leftGlyph, ushort rightGlyph, string script, string language, short value) { - string key = MakeKey(leftGlyph, rightGlyph, script, language); - _cache[key] = value; + uint key = PairKey(leftGlyph, rightGlyph); + var table = GetTable(script, language, true); + if (table.ContainsKey(key)) + { + table[key] = value; + return; + } + + if (_count >= MaxEntries) + { + Clear(); + table = GetTable(script, language, true); + } + table.Add(key, value); + _count++; } /// @@ -56,15 +100,43 @@ public void Set(ushort leftGlyph, ushort rightGlyph, string script, string langu /// public void Clear() { - _cache.Clear(); + _tables.Clear(); + _count = 0; + _hasLast = false; + _lastScript = null; + _lastLanguage = null; + _lastTable = null; + } + + private Dictionary GetTable(string script, string language, bool create) + { + if (_hasLast + && string.Equals(script, _lastScript, StringComparison.Ordinal) + && string.Equals(language, _lastLanguage, StringComparison.Ordinal) + && (_lastTable != null || !create)) + { + return _lastTable; + } + + // A null script or language is the same as an empty one, as it was in the string key. + string tableKey = (script ?? string.Empty) + "\0" + (language ?? string.Empty); + Dictionary table; + if (!_tables.TryGetValue(tableKey, out table) && create) + { + table = new Dictionary(); + _tables.Add(tableKey, table); + } + + _hasLast = true; + _lastScript = script; + _lastLanguage = language; + _lastTable = table; + return table; } - private static string MakeKey(ushort leftGlyph, ushort rightGlyph, string script, string language) + private static uint PairKey(ushort leftGlyph, ushort rightGlyph) { - // A string key trades a little speed for simplicity over the previous packed-ulong - // key, which had no room left for script/language without a second dictionary layer. - return leftGlyph.ToString() + "_" + rightGlyph.ToString() + "_" - + (script ?? string.Empty) + "_" + (language ?? string.Empty); + return ((uint)leftGlyph << 16) | 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 b9ad77e2f..93aa9cbd7 100644 --- a/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs @@ -27,7 +27,7 @@ namespace EPPlus.Fonts.OpenType.TextShaping.Ligatures { internal class LigatureProcessor { - private readonly struct IndexedLookup + internal readonly struct IndexedLookup { public readonly int FeatureIndex; public readonly LookupTable Lookup; @@ -240,7 +240,7 @@ private bool TryApplyLigatureInPlace( /// FeatureRecords can legitimately share a tag (one per script); both are kept so the /// script filter in ApplyLigaturesInPlace has something to choose between. /// - private static Dictionary> BuildLookupsByFeatureTag(GsubTable gsub) + internal static Dictionary> BuildLookupsByFeatureTag(GsubTable gsub) { var map = new Dictionary>();