diff --git a/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj b/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj index 95caaa366d..c4e5e83ea4 100644 --- a/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj +++ b/src/EPPlus.DrawingRenderer.Tests/EPPlus.DrawingRenderer.Tests.csproj @@ -22,6 +22,13 @@ + + + + PreserveNewest + + + diff --git a/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs b/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs new file mode 100644 index 0000000000..9983e9e724 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/FontTestBase.cs @@ -0,0 +1,115 @@ +using EPPlus.Fonts.OpenType; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests +{ + /// + /// Base class for renderer tests that lay out or measure text. + /// + /// Mirrors FontTestBase in EPPlus.Fonts.OpenType.Tests: tests use one of the exposed engines, + /// TestFolderEngine (test fonts only) or SystemFontsEngine (test fonts and system fonts), and + /// the render context built on it. The test fonts are linked from + /// EPPlus.Fonts.OpenType.Tests/Fonts and copied to the TestFonts folder in the output + /// directory (see the csproj). + /// + /// The engines and contexts are shared by all tests. Do not dispose them. + /// + public abstract class FontTestBase : TestBase + { + /// + /// Folder holding the test fonts in the output directory. + /// + protected static string FontFolder + { + get { return Path.Combine(AppContext.BaseDirectory, "TestFonts"); } + } + + // ----------------------------------------------------------------------------------------- + // Engines + // ----------------------------------------------------------------------------------------- + + private static readonly Lazy _testFolderEngine = + new Lazy(() => new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(GetExistingFontFolder()); + cfg.SearchSystemDirectories = false; + })); + + private static readonly Lazy _systemFontsEngine = + new Lazy(() => new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(GetExistingFontFolder()); + cfg.SearchSystemDirectories = true; + })); + + private static readonly Lazy _testFolderContext = + new Lazy(() => new RenderContext(() => TestFolderEngine)); + + private static readonly Lazy _systemFontsContext = + new Lazy(() => new RenderContext(() => SystemFontsEngine)); + + /// + /// Engine that searches only the test font folder. Use this for tests that can rely on + /// the fonts bundled with the font test project (BIZUDGothic, CrimsonText, EBGaramond, + /// Mulish, NotoEmoji, NotoSansMath, Oi, OpenSans, PinyonScript, Roboto, SourceSans3, + /// UnicaOne, Archivo Narrow). + /// + protected static OpenTypeFontEngine TestFolderEngine + { + get { return _testFolderEngine.Value; } + } + + /// + /// Engine that searches both the test font folder and the system font directories. Use + /// this only in tests that need fonts not bundled with the tests (e.g. Aptos Narrow, + /// Calibri), together with so the test is Inconclusive on + /// machines that lack the font. + /// + protected static OpenTypeFontEngine SystemFontsEngine + { + get { return _systemFontsEngine.Value; } + } + + /// + /// Render context over . + /// + protected static RenderContext TestFolderContext + { + get { return _testFolderContext.Value; } + } + + /// + /// Render context over . + /// + protected static RenderContext SystemFontsContext + { + get { return _systemFontsContext.Value; } + } + + /// + /// Marks the test Inconclusive unless the font is available in the engine with the + /// requested subfamily. + /// + protected static void RequireFont( + OpenTypeFontEngine engine, + string fontName, + FontSubFamily subFamily = FontSubFamily.Regular) + { + var avail = engine.GetFontAvailability(fontName, subFamily); + if (avail != FontAvailability.Exact) + { + Assert.Inconclusive( + "Test requires " + fontName + " " + subFamily + + " which is not available (availability: " + avail + ")."); + } + } + + private static string GetExistingFontFolder() + { + var folder = FontFolder; + if (!Directory.Exists(folder)) + throw new DirectoryNotFoundException("Test font folder not found: " + folder); + return folder; + } + } +} diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs new file mode 100644 index 0000000000..11d5ef5164 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/EmbedFontsMeasurementTests.cs @@ -0,0 +1,216 @@ +using System.Text.RegularExpressions; +using EPPlus.DrawingRenderer.Svg; +using EPPlus.Fonts.OpenType; +using EPPlusImageRenderer; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// Step 4: decides whether text is measured with the + /// requested font or with its web substitute. + /// carries the decision down to measurement. + /// + [TestClass] + public class EmbedFontsMeasurementTests : FontTestBase + { + [TestInitialize] + public void Initialize() + { + ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project"); + } + + private static ExcelPackage CreatePackage(Action? configure = null) + { + var p = new ExcelPackage(); + p.Workbook.UseFontEngine(new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(FontFolder); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + })); + return p; + } + + private static string FirstTspanFamily(string svg) + { + var m = Regex.Match(svg, "]*?style=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*)"); + Assert.IsTrue(m.Success, "No text run with a font-family was rendered."); + return System.Net.WebUtility.HtmlDecode(m.Groups[1].Value).Split(',')[0].Trim(); + } + + private static string ShapeSvg(ExcelPackage p, string fontName, Action options) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect); + shape.SetSize(300, 200); + shape.TextBody.Paragraphs.Add("Some text").TextRuns[0].SetFromFont(fontName, 11); + return shape.ToSvg(options); + } + + // ----------------------------------------------------------------------------------------- + // RenderContext + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [DataRow(FontRenderTarget.Web, true, "Calibri")] + [DataRow(FontRenderTarget.Web, false, "Aptos Narrow")] + [DataRow(FontRenderTarget.Document, true, "Aptos Narrow")] + [DataRow(FontRenderTarget.Document, false, "Aptos Narrow")] + public void RenderContext_SubstitutesOnlyForWebWithFlag(FontRenderTarget target, bool substitute, string expected) + { + using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false)) + { + var rc = new RenderContext(() => engine).ForTarget(target, substitute); + + Assert.AreEqual(target, rc.Target); + Assert.AreEqual(substitute, rc.SubstituteWebFonts); + Assert.AreEqual(expected, rc.GetFamilyForTarget("Aptos Narrow")); + } + } + + [TestMethod] + public void RenderContext_ForTargetWithoutFlag_SubstitutesForWebOnly() + { + using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false)) + { + var root = new RenderContext(() => engine); + + Assert.IsTrue(root.ForTarget(FontRenderTarget.Web).SubstituteWebFonts); + Assert.IsFalse(root.ForTarget(FontRenderTarget.Document).SubstituteWebFonts); + Assert.AreEqual("Calibri", root.ForTarget(FontRenderTarget.Web).GetFamilyForTarget("Aptos Narrow")); + } + } + + [TestMethod] + public void RenderContext_Views_ShareTheRootEngineAndReturnRootWhenEqual() + { + using (var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = false)) + { + var root = new RenderContext(() => engine); + var web = root.ForTarget(FontRenderTarget.Web, true); + var webNoSubstitution = web.ForTarget(FontRenderTarget.Web, false); + + Assert.AreSame(root, web.ForTarget(FontRenderTarget.Document, false)); + Assert.AreSame(web, web.ForTarget(FontRenderTarget.Web, true)); + Assert.AreSame(root.FontEngine, webNoSubstitution.FontEngine); + } + } + + // ----------------------------------------------------------------------------------------- + // SvgRenderOptions.EmbedFonts + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void SvgRenderOptions_EmbedFonts_DefaultsToTrue() + { + Assert.IsTrue(new SvgRenderOptions().EmbedFonts); + } + + [TestMethod] + public void Shape_EmbedFonts_MeasuresAndWritesRequestedFont() + { + using (var p = CreatePackage()) + { + var svg = ShapeSvg(p, "Aptos Narrow", o => o.EmbedFonts = true); + Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(svg)); + } + } + + [TestMethod] + public void Shape_NoEmbedFonts_WebTarget_UsesSubstitute() + { + using (var p = CreatePackage()) + { + var svg = ShapeSvg(p, "Aptos Narrow", o => o.EmbedFonts = false); + Assert.AreEqual("'Calibri'", FirstTspanFamily(svg)); + } + } + + [TestMethod] + public void Shape_NoEmbedFonts_DocumentTarget_KeepsRequestedFont() + { + using (var p = CreatePackage()) + { + var svg = ShapeSvg(p, "Aptos Narrow", o => + { + o.EmbedFonts = false; + o.FontTarget = FontRenderTarget.Document; + }); + Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(svg)); + } + } + + [TestMethod] + public void Chart_EmbedFonts_MeasuresAndWritesRequestedFont() + { + using (var p = CreatePackage()) + { + var chart = AddColumnChart(p, "Aptos Narrow"); + Assert.AreEqual("'Aptos Narrow'", FirstTspanFamily(chart.ToSvg(o => o.EmbedFonts = true))); + Assert.AreEqual("'Calibri'", FirstTspanFamily(chart.ToSvg(o => o.EmbedFonts = false))); + } + } + + // ----------------------------------------------------------------------------------------- + // Axis width is measured with the same font as the axis labels + // ----------------------------------------------------------------------------------------- + + private static ExcelChart AddColumnChart(ExcelPackage p, string axisFont) + { + var ws = p.Workbook.Worksheets.Add("Sheet" + (p.Workbook.Worksheets.Count + 1)); + ws.Cells["A1:A4"].FillNumber(1, 1); + ws.Cells["B1"].Value = 1000000; + ws.Cells["B2"].Value = 2500000; + ws.Cells["B3"].Value = 4000000; + ws.Cells["B4"].Value = 5500000; + var chart = ws.Drawings.AddChart("Chart1", eChartType.ColumnClustered); + chart.Series.Add(ws.Cells["B1:B4"], ws.Cells["A1:A4"]); + chart.SetSize(500, 300); + chart.XAxis.Font.LatinFont = axisFont; + chart.YAxis.Font.LatinFont = axisFont; + return chart; + } + + private static double VerticalAxisWidth(string substitute) + { + using (var p = CreatePackage(cfg => + { + cfg.WebFontSubstitutions["Aptos Narrow"] = substitute; + // Measure from serialized metrics, so the result does not depend on installed fonts. + cfg.MetricsFallback = MetricsFallbackMode.Always; + })) + { + var chart = AddColumnChart(p, "Aptos Narrow"); + var renderer = new ChartRenderer(chart, new SvgRenderOptions { EmbedFonts = false }); + Assert.IsNotNull(renderer.VerticalAxis, "Test setup: the chart has no vertical axis."); + return renderer.VerticalAxis.Rectangle.Width; + } + } + + [TestMethod] + public void Chart_VerticalAxisWidth_FollowsTheSubstitutedFont() + { + // Verdana is much wider than Calibri. Before the fix the axis width was measured with the + // unsubstituted font, so it was the same in both cases. + using (var engine = new OpenTypeFontEngine(cfg => + { + cfg.SearchSystemDirectories = false; + cfg.MetricsFallback = MetricsFallbackMode.Always; + })) + { + if (engine.GetMeasurementShaper("Verdana").HasGlyphIds || engine.GetMeasurementShaper("Calibri").HasGlyphIds) + Assert.Inconclusive("Test setup: Verdana and Calibri are expected to have serialized metrics."); + } + + var verdana = VerticalAxisWidth("Verdana"); + var calibri = VerticalAxisWidth("Calibri"); + + Assert.IsTrue(verdana > calibri, + $"Expected the axis to be wider with Verdana than with Calibri (Verdana {verdana}, Calibri {calibri})."); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs new file mode 100644 index 0000000000..a834fe8398 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgBrowserCheckTests.cs @@ -0,0 +1,205 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using OfficeOpenXml.Interfaces.Fonts; +using OfficeOpenXml.Style; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Net; +using System.Text; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// Step 7: generates a page for checking the svg export in browsers. Not a regression test. + /// + [TestClass] + public class SvgBrowserCheckTests : SvgExportTestBase + { + // The folder under the test output folder (TestBase), written the way TestBase builds paths. + private const string OutputFolder = "svg\\SvgBrowserCheck\\"; + + /// + /// Writes svg files and a page for checking the svg export in browsers to svg\SvgBrowserCheck + /// under the test output folder (TestBase). Open index.html in Chrome, Firefox, Edge and Safari + /// and go through the checks on the page. A screenshot from Excel named <case>.excel.png + /// placed in the folder is shown next to its case the next time the page is written. + /// Where files cannot be written, as in some build environments, the test is inconclusive. + /// + [TestMethod] + [TestCategory("Manual")] + public void WriteBrowserCheckPage() + { + RequireFont(TestFolderEngine, "Roboto"); + + var html = new StringBuilder(); + AppendPageStart(html); + + foreach (var c in GetCases()) + { + var svg = c.Render(); + // TestBase writes to the configured output folder and turns a failed write into Inconclusive. + SaveTextFileToWorkbook(OutputFolder + c.File + ".svg", svg); + AppendCaseRow(html, c, svg); + } + + html.AppendLine(""); + SaveTextFileToWorkbook(OutputFolder + "index.html", html.ToString()); + Console.WriteLine("Browser check page: " + GetOutputFile(OutputFolder, "index.html").FullName); + } + + private List GetCases() + { + var robotoBold = TestFolderEngine.LoadFont("Roboto", FontSubFamily.Bold); + var boldNote = robotoBold != null && robotoBold.NameTable.GetSubfamilyEnum() == FontSubFamily.Bold + ? + "Roboto has a bold file in the test folder, so this case checks that the bold face is used rather than synthesis." + : "Roboto has no bold file in the test folder, so the browser synthesizes bold and italic."; + + const string longText = "The quick brown fox jumps over the lazy dog. Sphinx of black quartz, judge my vow. Office, affluent, waffle."; + + return new List + { + new BrowserCase("roboto-embedded", "Roboto, embedded", + "Drawn with the subset ABCDEF+Roboto. Ligatures in 'Office, affluent, waffle' if the font has them.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Hello world 1 - Office, affluent, waffle", "Roboto").ToSvg(); } }), + + new BrowserCase("calibri-by-name", "Calibri, by name with safety net", + "Calibri may not be embedded. With Calibri installed (Windows) it is drawn with Calibri; without it (Mac, Linux) with the embedded safety net, normally Carlito or Archivo Narrow. The width is the same either way.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Hello world 1 - Calibri", "Calibri").ToSvg(); } }), + + new BrowserCase("aptos-narrow-embedded", "Aptos Narrow, EmbedFonts = true", + "Measured as Aptos Narrow (from .fmtr metrics if it is not installed on the server). Written by name, followed by an embedded safety net. Browsers without Aptos Narrow use the safety net.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Hello world 1 - Aptos Narrow", "Aptos Narrow").ToSvg(); } }), + + new BrowserCase("aptos-narrow-no-embed", "Aptos Narrow, EmbedFonts = false", + "Measured as Calibri (web substitution). No @font-face; the stack starts with 'Calibri'.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Hello world 1 - Aptos Narrow", "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); } }), + + new BrowserCase("roboto-no-embed", "Roboto, EmbedFonts = false", + "No @font-face. Drawn with Roboto only where it is installed, otherwise with a font from the stack; the width stays the same.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Hello world 1", "Roboto").ToSvg(o => o.EmbedFonts = false); } }), + + new BrowserCase("japanese-fallback-by-name", "Japanese, glyph fallback by name", + "The run is split: 'Sales ' with the Roboto subset, the kana with BIZ UDGothic or the next font in the Japanese chain (Yu Gothic, Meiryo), never a Chinese font. Check the positions of both parts in Firefox and Safari.", + () => { using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: false))) { return AddShape(p, JapaneseText, "Roboto").ToSvg(); } }), + + new BrowserCase("japanese-fallback-embedded", "Japanese, glyph fallback embedded", + "One run, two subsets in the stack. The kana are drawn with the BIZ UDGothic subset.", + () => { using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: true))) { return AddShape(p, JapaneseText, "Roboto").ToSvg(); } }), + + new BrowserCase("bold-italic", "Bold and italic", + boldNote + " In the hostile column the page sets font-synthesis:none on every element; note whether synthesized bold or italic disappears there.", + () => { using (var p = CreatePackage()) { return RenderFormattedShape(p, 360, 80, s => + { + AddRun(s, "Regular ", "Roboto"); + AddRun(s, "Bold ", "Roboto").Bold = true; + AddRun(s, "Italic ", "Roboto").Italic = true; + var both = AddRun(s, "Bold italic", "Roboto"); + both.Bold = true; + both.Italic = true; + }); } }), + + new BrowserCase("decoration", "Underline and strike-through", + "'Both' has both an underline and a strike-through. 'Red line' has a red underline under black text. Both must remain in the hostile column, which sets text-decoration:none.", + () => { using (var p = CreatePackage()) { return RenderFormattedShape(p, 360, 80, s => + { + var both = AddRun(s, "Both", "Roboto"); + both.UnderLine = eUnderLineType.Single; + both.Strike = eStrikeType.Single; + AddRun(s, " and ", "Roboto"); + var red = AddRun(s, "Red line", "Roboto"); + red.UnderLine = eUnderLineType.Single; + red.UnderLineColor = Color.Red; + }); } }), + + new BrowserCase("superscript", "Superscript and subscript", + "The 2 is raised and the 2 in H2O is lowered. Known: both move about 4/3 too far (dy converted twice; on the residue list).", + () => { using (var p = CreatePackage()) { return RenderFormattedShape(p, 360, 80, s => + { + AddRun(s, "E = mc", "Roboto"); + AddRun(s, "2", "Roboto").Baseline = 30; + AddRun(s, " H", "Roboto"); + AddRun(s, "2", "Roboto").Baseline = -25; + AddRun(s, "O", "Roboto"); + }); } }), + + new BrowserCase("emoji", "Emoji and symbols", + "The emoji and the check mark are drawn with the embedded Noto Emoji subset (monochrome), not with a color emoji font of the system.", + () => { using (var p = CreatePackage()) { return AddShape(p, "Smile \U0001F642 done \u2713", "Roboto").ToSvg(); } }), + + new BrowserCase("wrapping", "Line breaks", + "The lines break after the same words as in Excel, and no line is wider than the shape.", + () => { using (var p = CreatePackage()) { return RenderFormattedShape(p, 180, 140, s => AddRun(s, longText, "Roboto")); } }), + + new BrowserCase("chart", "Chart", + "Title, axis labels and values are placed and sized as in Excel. With several svgs on the page, gradients or patterns of one svg must not show up in another (ids are not unique across svgs).", + () => { using (var p = CreatePackage()) { return RenderColumnChart(p); } }), + }; + } + + private static void AppendPageStart(StringBuilder html) + { + html.AppendLine(""); + html.AppendLine("EPPlus SVG browser check"); + html.AppendLine(""); + html.AppendLine("

EPPlus SVG browser check

"); + html.Append("

Generated ").Append(WebUtility.HtmlEncode(DateTime.Now.ToString("yyyy-MM-dd HH:mm"))) + .AppendLine(". Open in Chrome, Firefox, Edge and Safari.

"); + html.AppendLine("

General checks

    "); + html.AppendLine("
  • The img, inline and hostile columns show the same text in the same places, and the text fits the shape as in Excel.
  • "); + html.AppendLine("
  • Hostile column: font, size, weight and style must not change (inline style). Letter and word spacing must not change the width of a run (textLength).
  • "); + html.AppendLine("
  • Which font a run is drawn with: Chrome/Edge DevTools, Elements, Computed, Rendered Fonts. Firefox: Inspector, Fonts.
  • "); + html.AppendLine("
  • Zoom to 90, 110 and 125 percent: text scales smoothly and keeps its width relative to the shape (text-rendering:geometricPrecision, Chrome and Firefox).
  • "); + html.AppendLine("
  • The open link shows the standalone svg; it looks the same as the img column.
  • "); + html.AppendLine("
"); + html.AppendLine(""); + } + + private static void AppendCaseRow(StringBuilder html, BrowserCase c, string svg) + { + var excel = c.File + ".excel.png"; + html.AppendLine(""); + html.Append(""); + html.Append(""); + html.Append(""); + html.Append(""); + html.Append(""); + html.Append(""); + html.AppendLine(""); + } + + private sealed class BrowserCase + { + internal BrowserCase(string file, string title, string check, Func render) + { + File = file; + Title = title; + Check = check; + Render = render; + } + + /// The file name of the svg, without extension. + internal string File { get; } + internal string Title { get; } + + /// What to look for in the browser. + internal string Check { get; } + internal Func Render { get; } + } + } +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgExportTestBase.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgExportTestBase.cs new file mode 100644 index 0000000000..e2397b1551 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgExportTestBase.cs @@ -0,0 +1,147 @@ +using EPPlus.Fonts.OpenType; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Interfaces.Fonts; +using OfficeOpenXml.Style; +using System; +using System.Drawing; +using System.Text.RegularExpressions; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// Base class for tests that export shapes and charts to svg: creates packages and drawings, and + /// reads fonts, stacks and text runs from the svg. + /// + public abstract class SvgExportTestBase : FontTestBase + { + protected const string JapaneseText = "Sales あいう"; + + protected OpenTypeFontEngine? _engine; + + protected ExcelPackage CreatePackage(Action? configure = null) + { + _engine = new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(FontFolder); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + }); + var p = new ExcelPackage(); + p.Workbook.UseFontEngine(_engine); + return p; + } + + protected static ExcelShape AddShape(ExcelPackage p, string text, string fontName, bool bold = false) + { + var ws = p.Workbook.Worksheets.Add("Sheet" + (p.Workbook.Worksheets.Count + 1)); + var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect); + shape.SetSize(300, 200); + shape.TextBody.Paragraphs.Add(text).TextRuns[0].SetFromFont(fontName, 11, bold); + return shape; + } + + /// Hiragana is drawn with BIZ UDGothic, which an OnFontEmbedding callback may forbid. + protected static void JapaneseFallback(IEpplusFontConfiguration cfg, bool embedFallback) + { + RequireFont(TestFolderEngine, "BIZ UDGothic"); + cfg.SetScriptFallback(UnicodeScript.Hiragana, "BIZ UDGothic", "Yu Gothic", "Meiryo"); + if (!embedFallback) + { + cfg.OnFontEmbedding(info => info.FontName.StartsWith("BIZ UDGothic", StringComparison.OrdinalIgnoreCase) + ? FontEmbeddingDecision.Skip + : FontEmbeddingDecision.Default); + } + } + + protected static List FontFaceFamilies(string svg) + { + return Regex.Matches(svg, "@font-face\\{font-family:'([^']*)'") + .Cast().Select(m => m.Groups[1].Value).ToList(); + } + + protected static string[] Families(string fontFamilyAttribute) + { + return System.Net.WebUtility.HtmlDecode(fontFamilyAttribute) + .Split(',').Select(f => f.Trim().Trim('\'')).ToArray(); + } + + /// The innermost tspans, the ones that hold text. + protected static MatchCollection TextTspans(string svg) + { + return Regex.Matches(svg, "]*)>([^<]+)"); + } + + protected static string? Attribute(string attributes, string name) + { + var m = Regex.Match(attributes, "\\s" + Regex.Escape(name) + "=\"([^\"]*)\""); + return m.Success ? m.Groups[1].Value : null; + } + + /// The width in pixels, measured with the engine of the package the test created. + protected double MeasurePixels(string text, string family, FontSubFamily subFamily, float size) + { + var points = _engine!.GetMeasurementShaper(family, subFamily).ShapeLight(text).GetWidthInPoints(size); + return points / 72d * 96d; + } + + // ----------------------------------------------------------------------------------------- + // Drawings with formatted text + // ----------------------------------------------------------------------------------------- + + /// + /// Adds a white rectangle with a gray border to a new worksheet, lets the caller add the text, + /// and returns the svg. + /// + protected static string RenderFormattedShape(ExcelPackage p, int widthPixels, int heightPixels, Action addText) + { + var ws = p.Workbook.Worksheets.Add("FormattedShape"); + var shape = ws.Drawings.AddShape("FormattedShape", eShapeStyle.Rect); + shape.SetPosition(1, 0, 1, 0); + shape.SetSize(widthPixels, heightPixels); + shape.Fill.Style = eFillStyle.SolidFill; + shape.Fill.Color = Color.White; + shape.Border.Fill.Color = Color.Gray; + addText(shape); + return shape.ToSvg(); + } + + /// + /// Adds a black 11 pt run in the given font to the shape. + /// + protected static ExcelParagraph AddRun(ExcelShape shape, string text, string font) + { + var run = shape.RichText.Add(text); + run.LatinFont = font; + run.Size = 11; + run.Color = Color.Black; + return run; + } + + /// + /// Renders a clustered column chart with a title and four categories. + /// + protected static string RenderColumnChart(ExcelPackage p) + { + var ws = p.Workbook.Worksheets.Add("ColumnChart"); + ws.Cells["A1"].Value = "Quarter"; + ws.Cells["B1"].Value = "Sales"; + var quarters = new[] { "Q1", "Q2", "Q3", "Q4" }; + var values = new[] { 120d, 180d, 150d, 210d }; + for (int i = 0; i < quarters.Length; i++) + { + ws.Cells[i + 2, 1].Value = quarters[i]; + ws.Cells[i + 2, 2].Value = values[i]; + } + + var chart = ws.Drawings.AddChart("ColumnChart", eChartType.ColumnClustered); + var serie = chart.Series.Add(ws.Cells["B2:B5"], ws.Cells["A2:A5"]); + serie.Header = "Sales"; + chart.Title.Text = "Sales per quarter"; + chart.SetPosition(1, 0, 4, 0); + chart.SetSize(480, 300); + return chart.ToSvg(); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs new file mode 100644 index 0000000000..8363131d9e --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontEmbeddingTests.cs @@ -0,0 +1,366 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using EPPlus.DrawingRenderer.Svg; +using EPPlus.Fonts.OpenType; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// Step 5: fonts embedded in the svg as subsets (@font-face), font-family stacks that start with + /// the subsets, textLength on every text run, xml:space on text elements, the root text style, + /// and text runs split where measurement used a glyph fallback that is written by name. + /// The font engine only sees the test fonts, so the output does not depend on installed fonts. + /// + [TestClass] + public class SvgFontEmbeddingTests : SvgExportTestBase + { + + [TestInitialize] + public void Initialize() + { + ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project"); + } + + + + [TestCleanup] + public void Cleanup() + { + _engine?.Dispose(); + _engine = null; + } + + + + // ----------------------------------------------------------------------------------------- + // @font-face + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void EmbedFonts_WritesFontFaceWithDataUriInDefs() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Hello", "Roboto").ToSvg(); + + var m = Regex.Match(svg, + "").Groups[1].Value; + StringAssert.StartsWith(style, ".epplus-svg text,.epplus-svg tspan{", + "Without embedding the style element holds only the text rule."); + } + } + + [TestMethod] + public void Chart_EmbedFonts_EveryStackHasADeclaredSubset() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + ws.Cells["A1:A4"].FillNumber(1, 1); + ws.Cells["B1:B4"].FillNumber(10, 10); + var chart = ws.Drawings.AddChart("Chart1", eChartType.ColumnClustered); + chart.Series.Add(ws.Cells["B1:B4"], ws.Cells["A1:A4"]); + chart.Title.Text = "Title"; + chart.Title.Font.LatinFont = "Roboto"; + chart.XAxis.Font.LatinFont = "Roboto"; + chart.YAxis.Font.LatinFont = "Roboto"; + + var svg = chart.ToSvg(); + var faces = FontFaceFamilies(svg); + Assert.IsTrue(faces.Any(f => f.EndsWith("+Roboto")), "Roboto is not embedded."); + + var runs = TextTspans(svg); + Assert.IsTrue(runs.Count > 0); + // A font that is not installed (here the title's Aptos Narrow) is measured from metrics and + // written by name, followed by an embedded safety net. Every stack therefore has a subset, + // and every subset a stack names is declared. + foreach (Match run in runs) + { + var fontFamily = Attribute(run.Groups[1].Value, "font-family"); + if (fontFamily == null) + continue; + var subsets = Families(fontFamily).Where(f => Regex.IsMatch(f, @"^[A-Z]{6}\+")).ToList(); + Assert.IsTrue(subsets.Count > 0, "Text run '" + run.Groups[2].Value + "' has no subset in its stack."); + foreach (var subset in subsets) + CollectionAssert.Contains(faces, subset, "Undeclared subset in the stack of '" + run.Groups[2].Value + "'."); + } + } + } + + // ----------------------------------------------------------------------------------------- + // textLength, xml:space, root + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void EveryTextRun_HasTextLengthEqualToTheMeasuredWidth() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var svg = AddShape(p, "This text is long enough to wrap over more than one line in the shape.", "Roboto").ToSvg(); + + var runs = TextTspans(svg); + Assert.IsTrue(runs.Count > 1, "Expected the text to wrap."); + foreach (Match run in runs) + { + var text = System.Net.WebUtility.HtmlDecode(run.Groups[2].Value); + var textLength = Attribute(run.Groups[1].Value, "textLength"); + Assert.IsNotNull(textLength, "No textLength on '" + text + "'."); + Assert.AreEqual("spacing", Attribute(run.Groups[1].Value, "lengthAdjust")); + Assert.AreEqual(MeasurePixels(text, "Roboto", FontSubFamily.Regular, 11), + double.Parse(textLength!, CultureInfo.InvariantCulture), 0.01, "textLength of '" + text + "'."); + } + } + } + + [TestMethod] + public void TextElements_PreserveSpaceAndHaveNothingBetweenRuns() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var svg = AddShape(p, "This text is long enough to wrap over more than one line in the shape.", "Roboto").ToSvg(); + + var texts = Regex.Matches(svg, "]*)>(.*?)", RegexOptions.Singleline); + Assert.IsTrue(texts.Count > 0); + foreach (Match text in texts) + { + StringAssert.Contains(text.Groups[1].Value, "xml:space=\"preserve\""); + // Outside the tspans there may be no text, not even white space. + var outside = Regex.Replace(text.Groups[2].Value, "]*>[^<]*|]*>|", ""); + Assert.AreEqual(string.Empty, outside, "Text outside the runs of a text element."); + } + } + } + + [TestMethod] + public void Root_HasViewBoxAndScopedTextStyle() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Hello", "Roboto").ToSvg(); + var root = Regex.Match(svg, "]*>").Value; + + StringAssert.Contains(root, " viewBox=\""); + Assert.IsFalse(root.Contains(" viewbox=")); + Assert.AreEqual("epplus-svg", Attribute(root, "class")); + Assert.IsNull(Attribute(root, "style"), "The text style is a scoped rule, not a style on the root."); + + var style = Regex.Match(svg, "").Groups[1].Value; + StringAssert.Contains(style, ".epplus-svg text,.epplus-svg tspan{"); + foreach (var rule in new[] { "font-kerning:normal", "font-variant-ligatures:common-ligatures contextual", + "letter-spacing:0", "word-spacing:0", "font-synthesis:weight style", "text-rendering:geometricPrecision" }) + { + StringAssert.Contains(style, rule + "!important"); + } + Assert.IsFalse(style.Contains("font-synthesis:none"), "Bold and italic synthesis must be allowed."); + } + } + + // ----------------------------------------------------------------------------------------- + // Glyph fallback + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void EmbeddedGlyphFallback_IsOneRunWithBothSubsetsInTheStack() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: true))) + { + var svg = AddShape(p, JapaneseText, "Roboto").ToSvg(); + + var faces = FontFaceFamilies(svg); + Assert.AreEqual(2, faces.Count, string.Join(", ", faces)); + var runs = TextTspans(svg); + Assert.AreEqual(1, runs.Count, "An embedded fallback needs no split."); + + var families = Families(SvgStyle.Property(runs[0].Groups[1].Value, "font-family")!); + Assert.IsTrue(families[0].EndsWith("+Roboto")); + Assert.IsTrue(families[1].EndsWith("+BIZ UDGothic")); + Assert.AreEqual(MeasurePixels(JapaneseText, "Roboto", FontSubFamily.Regular, 11), + double.Parse(Attribute(runs[0].Groups[1].Value, "textLength")!, CultureInfo.InvariantCulture), 0.01); + } + } + + [TestMethod] + public void GlyphFallbackByName_IsSplitIntoItsOwnTspan() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: false))) + { + var svg = AddShape(p, JapaneseText, "Roboto").ToSvg(); + + // Only Roboto is embedded; BIZ UDGothic is written by name. + var faces = FontFaceFamilies(svg); + Assert.AreEqual(1, faces.Count, string.Join(", ", faces)); + + // The run is an outer tspan without textLength, holding one tspan per font. + var outer = Regex.Match(svg, "]*)>((?:]*>[^<]*)+)"); + Assert.IsTrue(outer.Success, "The run was not split."); + Assert.IsNull(Attribute(outer.Groups[1].Value, "textLength")); + Assert.AreEqual(faces[0], Families(SvgStyle.Property(outer.Groups[1].Value, "font-family")!)[0]); + + var segments = TextTspans(outer.Groups[2].Value); + Assert.AreEqual(2, segments.Count); + + Assert.AreEqual("Sales ", segments[0].Groups[2].Value); + Assert.IsNull(SvgStyle.Property(segments[0].Groups[1].Value, "font-family"), "The Latin part inherits the run's stack."); + + Assert.AreEqual("あいう", segments[1].Groups[2].Value); + var families = Families(SvgStyle.Property(segments[1].Groups[1].Value, "font-family")!); + CollectionAssert.AreEqual(new[] { "BIZ UDGothic", "Yu Gothic", "Meiryo" }, families.Take(3).ToArray(), + "The fallback, then the rest of the script's chain."); + Assert.AreEqual("sans-serif", families.Last()); + + foreach (Match segment in segments) + { + Assert.AreEqual(MeasurePixels(segment.Groups[2].Value, "Roboto", FontSubFamily.Regular, 11), + double.Parse(Attribute(segment.Groups[1].Value, "textLength")!, CultureInfo.InvariantCulture), 0.01, + "textLength of '" + segment.Groups[2].Value + "'."); + } + } + } + + [TestMethod] + public void GlyphFallbackByName_RunStackListsTheScriptChain() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: false))) + { + var svg = AddShape(p, JapaneseText, "Roboto").ToSvg(); + + var outer = Regex.Match(svg, "]*)> 0, string.Join(", ", families)); + Assert.AreEqual("Yu Gothic", families[fallback + 1]); + Assert.AreEqual("Meiryo", families[fallback + 2]); + } + } + + // ----------------------------------------------------------------------------------------- + // Without embedding (step 6) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void NoEmbedFonts_GlyphFallback_IsSplitIntoItsOwnTspan() + { + RequireFont(TestFolderEngine, "Roboto"); + using (var p = CreatePackage(cfg => JapaneseFallback(cfg, embedFallback: true))) + { + var svg = AddShape(p, JapaneseText, "Roboto").ToSvg(o => o.EmbedFonts = false); + Assert.IsFalse(svg.Contains("@font-face")); + + var outer = Regex.Match(svg, "]*)>((?:]*>[^<]*)+)"); + Assert.IsTrue(outer.Success, "The run was not split."); + CollectionAssert.AreEqual(new[] { "Roboto", "BIZ UDGothic", "Yu Gothic", "Meiryo", "sans-serif" }, + Families(SvgStyle.Property(outer.Groups[1].Value, "font-family")!), + "The run's stack: the font, the glyph fallback and its script chain, a generic family."); + + var segments = TextTspans(outer.Groups[2].Value); + Assert.AreEqual(2, segments.Count); + Assert.IsNull(SvgStyle.Property(segments[0].Groups[1].Value, "font-family")); + CollectionAssert.AreEqual(new[] { "BIZ UDGothic", "Yu Gothic", "Meiryo", "Roboto", "sans-serif" }, + Families(SvgStyle.Property(segments[1].Groups[1].Value, "font-family")!)); + + foreach (Match segment in segments) + { + Assert.AreEqual(MeasurePixels(segment.Groups[2].Value, "Roboto", FontSubFamily.Regular, 11), + double.Parse(Attribute(segment.Groups[1].Value, "textLength")!, CultureInfo.InvariantCulture), 0.01, + "textLength of '" + segment.Groups[2].Value + "'."); + } + } + } + + [TestMethod] + public void NoEmbedFonts_FontNotInstalled_HasNoSafetyNet() + { + using (var p = CreatePackage()) + { + // Calibri is not in the test folder. Without embedding there is no Archivo Narrow subset. + var svg = AddShape(p, "Hello", "Calibri").ToSvg(o => { o.EmbedFonts = false; o.FontTarget = FontRenderTarget.Document; }); + + Assert.IsFalse(svg.Contains("@font-face")); + Assert.IsFalse(svg.Contains("Archivo Narrow"), "Archivo Narrow is only ever used embedded."); + var families = Families(SvgStyle.Property(TextTspans(svg)[0].Groups[1].Value, "font-family")!); + Assert.AreEqual("Calibri", families[0]); + Assert.AreEqual("sans-serif", families.Last()); + } + } + + [TestMethod] + public void NoEmbedFonts_DoesNotConsultTheEmbeddingCallback() + { + RequireFont(TestFolderEngine, "Roboto"); + int calls = 0; + using (var p = CreatePackage(cfg => cfg.OnFontEmbedding(info => { calls++; return FontEmbeddingDecision.Default; }))) + { + AddShape(p, "Hello", "Roboto").ToSvg(o => o.EmbedFonts = false); + Assert.AreEqual(0, calls); + + AddShape(p, "Hello", "Roboto").ToSvg(); + Assert.IsTrue(calls > 0, "Test setup: the callback runs when fonts are embedded."); + } + } + } +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontFamilyStackTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontFamilyStackTests.cs new file mode 100644 index 0000000000..7ffd591b45 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/SvgFontFamilyStackTests.cs @@ -0,0 +1,230 @@ +using System.Text.RegularExpressions; +using EPPlus.DrawingRenderer.Svg; +using EPPlus.Fonts.OpenType; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Drawing.Chart; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests.Fonts +{ + /// + /// The font-family written to svg is a CSS stack: the measured family, its fallback chain + /// (user-configured, then built-in) and a generic family from the measured font. + /// + /// The engines here search only the test font folder, so the expected stacks do not depend + /// on the fonts installed on the machine. + /// + [TestClass] + public class SvgFontFamilyStackTests : FontTestBase + { + private const string CalibriChain = "'Carlito', 'Liberation Sans', 'Arial', 'Helvetica'"; + + [TestInitialize] + public void Initialize() + { + ExcelPackage.License.SetNonCommercialOrganization("EPPlus Project"); + } + + private Action GetRenderOptions(FontRenderTarget target = FontRenderTarget.Document) + { + return o => + { + o.FontTarget = target; + o.EmbedFonts = false; + }; + } + + private static ExcelPackage CreatePackage(Action? configure = null) + { + var p = new ExcelPackage(); + p.Workbook.UseFontEngine(new OpenTypeFontEngine(cfg => + { + cfg.FontDirectories.Add(FontFolder); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + })); + return p; + } + + private static ExcelShape AddShape(ExcelPackage p, string fontName) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect); + shape.SetSize(300, 200); + var paragraph = shape.TextBody.Paragraphs.Add("Text in " + fontName); + paragraph.TextRuns[0].SetFromFont(fontName, 11); + return shape; + } + + /// + /// The font-family attribute of every tspan, decoded from xml. + /// + private static List GetTspanFontFamilies(string svg) + { + return Regex.Matches(svg, "]*?style=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*)") + .Cast() + .Select(m => System.Net.WebUtility.HtmlDecode(m.Groups[1].Value)) + .ToList(); + } + + private static string GetSingleTspanFontFamily(string svg) + { + var families = GetTspanFontFamilies(svg); + Assert.AreEqual(1, families.Count, "Expected one text run."); + return families[0]; + } + + // ----------------------------------------------------------------------------------------- + // Shapes + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Shape_FontWithoutChain_IsFamilyAndGeneric() + { + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Roboto").ToSvg(GetRenderOptions()); + Assert.AreEqual("'Roboto', sans-serif", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_FontWithBuiltinChain_ListsChain() + { + using (var p = CreatePackage()) + { + // Calibri is not in the test folder; measurement falls through to the embedded + // last-resort font, which is sans-serif. + var svg = AddShape(p, "Calibri").ToSvg(GetRenderOptions()); + Assert.AreEqual("'Calibri', " + CalibriChain + ", sans-serif", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_UserChain_ComesFirst() + { + using (var p = CreatePackage(cfg => cfg.FontFallbacks["Calibri"] = new[] { "Open Sans" })) + { + var svg = AddShape(p, "Calibri").ToSvg(GetRenderOptions()); + Assert.AreEqual("'Calibri', 'Open Sans', " + CalibriChain + ", sans-serif", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_MonospaceFont_EndsWithMonospace() + { + using (var p = CreatePackage()) + { + RequireFont(TestFolderEngine, "BIZ UDGothic"); + var svg = AddShape(p, "BIZ UDGothic").ToSvg(GetRenderOptions()); + Assert.AreEqual("'BIZ UDGothic', monospace", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_WebTarget_StackStartsWithSubstitute() + { + using (var p = CreatePackage()) + { + // Aptos Narrow is substituted with Calibri for the web before measurement, so the + // stack is Calibri's. + var svg = AddShape(p, "Aptos Narrow").ToSvg(GetRenderOptions(FontRenderTarget.Web)); + Assert.AreEqual("'Calibri', " + CalibriChain + ", sans-serif", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_DocumentTarget_StackStartsWithRequestedFont() + { + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Aptos Narrow").ToSvg(GetRenderOptions()); + Assert.AreEqual( + "'Aptos Narrow', 'Liberation Sans Narrow', 'Arial Narrow', 'Carlito', 'Liberation Sans', 'Arial', sans-serif", + GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_NameWithQuote_IsEscaped() + { + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Bob's \"Font\"").ToSvg(GetRenderOptions()); + + // xml: the double quote is an entity so the attribute stays well-formed. + StringAssert.Contains(svg, "font-family:'Bob\\'s "Font"', sans-serif;"); + // css after xml decoding: the single quote is escaped inside the quoted name. + Assert.AreEqual("'Bob\\'s \"Font\"', sans-serif", GetSingleTspanFontFamily(svg)); + } + } + + [TestMethod] + public void Shape_NoMsFontService() + { + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Calibri").ToSvg(GetRenderOptions(FontRenderTarget.Web)); + Assert.IsFalse(svg.Contains("_MSFontService"), "The svg still contains _MSFontService."); + } + } + + [TestMethod] + public void Shape_ParagraphAndGroupFonts_AreStacks() + { + using (var p = CreatePackage()) + { + var svg = AddShape(p, "Calibri").ToSvg(GetRenderOptions()); + + // Every font-family in the svg, on text, tspan and g, ends with a generic family. The group writes + // it as an attribute, text and tspan in the style attribute. A font-family in a style attribute is + // only matched inside style="...", so the @font-face rules in the style element are not counted; + // xml entities such as " are skipped, since they contain a semicolon. + var all = Regex.Matches(svg, "(?:\\bfont-family=\"([^\"]*)\"|\\bstyle=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*))") + .Cast() + .Select(m => m.Groups[1].Success ? m.Groups[1].Value : m.Groups[2].Value) + .ToList(); + Assert.IsTrue(all.Count >= 2, "Expected font-family on more than the text runs."); + foreach (var family in all) + { + Assert.IsTrue(family.EndsWith(", sans-serif") || family.EndsWith(", serif") || family.EndsWith(", monospace"), + "Not a stack: " + family); + } + } + } + + // ----------------------------------------------------------------------------------------- + // Charts + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Chart_AllTextRuns_AreStacks() + { + using (var p = CreatePackage()) + { + var ws = p.Workbook.Worksheets.Add("Sheet1"); + ws.Cells["A1:A4"].FillNumber(1, 1); + ws.Cells["B1:B4"].FillNumber(10, 5); + var chart = ws.Drawings.AddChart("Chart1", eChartType.ColumnClustered); + chart.Series.Add(ws.Cells["B1:B4"], ws.Cells["A1:A4"]); + chart.SetSize(400, 300); + chart.Title.Text = "Chart title"; + chart.Title.Font.LatinFont = "Calibri"; + chart.XAxis.Font.LatinFont = "Calibri"; + chart.YAxis.Font.LatinFont = "Calibri"; + + var svg = chart.ToSvg(GetRenderOptions()); + + Assert.IsFalse(svg.Contains("_MSFontService"), "The svg still contains _MSFontService."); + var families = GetTspanFontFamilies(svg); + Assert.IsTrue(families.Count > 0, "No text run was rendered."); + foreach (var family in families.Where(f => f.StartsWith("'Calibri'"))) + { + Assert.AreEqual("'Calibri', " + CalibriChain + ", sans-serif", family); + } + Assert.IsTrue(families.Any(f => f.StartsWith("'Calibri'")), "No text run in Calibri."); + } + } + } +} diff --git a/src/EPPlus.DrawingRenderer.Tests/Fonts/WebFontSubstitutionSvgTests.cs b/src/EPPlus.DrawingRenderer.Tests/Fonts/WebFontSubstitutionSvgTests.cs index 07fc67c598..e96d333eff 100644 --- a/src/EPPlus.DrawingRenderer.Tests/Fonts/WebFontSubstitutionSvgTests.cs +++ b/src/EPPlus.DrawingRenderer.Tests/Fonts/WebFontSubstitutionSvgTests.cs @@ -54,7 +54,7 @@ private static ExcelShape AddShapeWithText(ExcelPackage p, string fontName) private static List GetRunFontFamilies(string svg) { var result = new List(); - foreach (Match m in Regex.Matches(svg, "]*?font-family=\"([^\"]*)\"")) + foreach (Match m in Regex.Matches(svg, "]*?style=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*)")) { var first = m.Groups[1].Value.Split(',')[0].Trim().Trim('\'', '"'); result.Add(first); @@ -64,7 +64,7 @@ private static List GetRunFontFamilies(string svg) private static void AssertAllFamilies(string svg, string expectedFamily) { - var matches = Regex.Matches(svg, "]*?font-family=\"([^\"]*)\"[^>]*>([^<]*)"); + var matches = Regex.Matches(svg, "]*?style=\"[^\"]*?font-family:((?:&[#\\w]+;|[^;\"])*)[^>]*>([^<]*)"); Assert.IsTrue(matches.Count > 0, "No text run with a font-family was rendered."); foreach (Match m in matches) { @@ -82,7 +82,7 @@ public void Shape_OfficeCloudFont_IsSubstituted() { using (var p = CreatePackage()) { - var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(); + var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); AssertAllFamilies(svg, "Calibri"); Assert.IsFalse(svg.Contains("Aptos Narrow"), "The original font name leaked into the svg."); @@ -94,7 +94,7 @@ public void Shape_FontNotInTable_IsUnchanged() { using (var p = CreatePackage()) { - var svg = AddShapeWithText(p, "Arial").ToSvg(); + var svg = AddShapeWithText(p, "Arial").ToSvg(o => o.EmbedFonts = false); AssertAllFamilies(svg, "Arial"); } @@ -105,7 +105,7 @@ public void Shape_DocumentTarget_KeepsOriginalFont() { using (var p = CreatePackage()) { - var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => o.FontTarget = FontRenderTarget.Document); + var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => { o.FontTarget = FontRenderTarget.Document; o.EmbedFonts = false; }); AssertAllFamilies(svg, "Aptos Narrow"); } @@ -116,7 +116,7 @@ public void Shape_UserSubstitution_IsUsed() { using (var p = CreatePackage(cfg => cfg.WebFontSubstitutions["Aptos Narrow"] = "Verdana")) { - var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(); + var svg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); AssertAllFamilies(svg, "Verdana"); } @@ -143,7 +143,7 @@ public void Chart_OfficeCloudFont_IsSubstitutedInAllText() chart.YAxis.Font.LatinFont = "Aptos Narrow"; chart.Legend.Font.LatinFont = "Aptos Narrow"; - var svg = chart.ToSvg(); + var svg = chart.ToSvg(o => o.EmbedFonts = false); //Covers title, axis labels and legend. A failure here points to a text path //that bypasses the render context's target. @@ -199,11 +199,11 @@ public void Shape_WebSubstitution_WrapsAsSubstituteFont() string webSvg, documentSvg; using (var p = CreatePackage(Deterministic)) { - webSvg = AddShapeWithText(p, "Aptos Narrow").ToSvg(); + webSvg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); } using (var p = CreatePackage(Deterministic)) { - documentSvg = AddShapeWithText(p, "Calibri").ToSvg(o => o.FontTarget = FontRenderTarget.Document); + documentSvg = AddShapeWithText(p, "Calibri").ToSvg(o => { o.FontTarget = FontRenderTarget.Document; o.EmbedFonts = false; }); } var webLines = GetRunTexts(webSvg); @@ -219,11 +219,11 @@ public void Shape_WrapComparison_DetectsDifferentFont() string webSvg, documentSvg; using (var p = CreatePackage(Deterministic)) { - webSvg = AddShapeWithText(p, "Aptos Narrow").ToSvg(); + webSvg = AddShapeWithText(p, "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); } using (var p = CreatePackage(Deterministic)) { - documentSvg = AddShapeWithText(p, "Verdana").ToSvg(o => o.FontTarget = FontRenderTarget.Document); + documentSvg = AddShapeWithText(p, "Verdana").ToSvg(o => { o.FontTarget = FontRenderTarget.Document; o.EmbedFonts = false; }); } CollectionAssert.AreNotEqual(GetRunTexts(documentSvg), GetRunTexts(webSvg)); @@ -235,11 +235,11 @@ public void Chart_WebSubstitution_LaysOutAsSubstituteFont() string webSvg, documentSvg; using (var p = CreatePackage(Deterministic)) { - webSvg = AddChartWithFont(p, "Aptos Narrow").ToSvg(); + webSvg = AddChartWithFont(p, "Aptos Narrow").ToSvg(o => o.EmbedFonts = false); } using (var p = CreatePackage(Deterministic)) { - documentSvg = AddChartWithFont(p, "Calibri").ToSvg(o => o.FontTarget = FontRenderTarget.Document); + documentSvg = AddChartWithFont(p, "Calibri").ToSvg(o => { o.FontTarget = FontRenderTarget.Document; o.EmbedFonts = false; }); } //Covers title wrapping, axis label selection and legend. Any text path that measures diff --git a/src/EPPlus.DrawingRenderer.Tests/SvgStyle.cs b/src/EPPlus.DrawingRenderer.Tests/SvgStyle.cs new file mode 100644 index 0000000000..e242943020 --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/SvgStyle.cs @@ -0,0 +1,32 @@ +using System.Net; +using System.Text.RegularExpressions; + +namespace EPPlus.DrawingRenderer.Tests +{ + /// + /// Reads properties from the style attribute of svg elements in tests. Font properties are written + /// in the style attribute rather than as presentation attributes, so that an inline style wins over + /// the css of a host page. + /// + internal static class SvgStyle + { + private static readonly Regex StyleAttribute = new Regex("\\bstyle=\"([^\"]*)\""); + + /// + /// The value of a property in the style attribute of an element, decoded from xml, or null when + /// the element has no style attribute or the style has no such property. + /// + /// The start tag of the element, or its attributes. + /// The css property, e.g. "font-family". + internal static string? Property(string element, string property) + { + var style = StyleAttribute.Match(element); + if (!style.Success) + return null; + + var declarations = WebUtility.HtmlDecode(style.Groups[1].Value); + var match = Regex.Match(declarations, "(?:^|;)\\s*" + Regex.Escape(property) + "\\s*:\\s*([^;]*)"); + return match.Success ? match.Groups[1].Value.Trim() : null; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer.Tests/Text/TextRunWidthInvariantTests.cs b/src/EPPlus.DrawingRenderer.Tests/Text/TextRunWidthInvariantTests.cs new file mode 100644 index 0000000000..c8f530c5cd --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Text/TextRunWidthInvariantTests.cs @@ -0,0 +1,292 @@ +using System.Globalization; +using System.Text; +using EPPlus.DrawingRenderer.RenderItems; +using EPPlus.DrawingRenderer.RenderItems.SvgItem; +using EPPlus.Export.ImageRenderer.RenderItems.Shared; +using EPPlus.Fonts.OpenType; +using EPPlus.Fonts.OpenType.Integration.DataHolders; +using EPPlus.Graphics; +using OfficeOpenXml.Interfaces.Fonts; +using OfficeOpenXml.Interfaces.RichText; + +namespace EPPlus.DrawingRenderer.Tests.Text +{ + /// + /// Step 0 of the SVG font subsetting plan. + /// + /// SVG output will set textLength on every tspan, which assumes that run.Width is the width + /// of exactly run.CurrentText in the run's font. These tests check that invariant for the runs + /// produced by ParagraphRenderItem.WrapTextFragmentsAndGenerateTextRuns, and that glyph + /// fallback (emoji) is part of the measured width. + /// + [TestClass] + public class TextRunWidthInvariantTests : FontTestBase + { + private const string Roboto = "Roboto"; + private const string OpenSans = "Open Sans"; + + // Known issue, handed over: when a line ends, trailing spaces are trimmed from the line's + // text but their width stays in the last run. Not visible today (nothing is placed after the + // last run on a line), but textLength in SVG step 5 needs it fixed. Remove the Ignore + // attributes when it is. + private const string TrailingSpaceIssue = + "Known issue: trailing spaces at line ends are included in the last run's width but not in its text. " + + "Handed over (see 'Fynd i textradbrytningen'). Remove when fixed; required before textLength in SVG step 5."; + + // Widths are summed per character in doubles and compared with a single shaping pass in + // floats; anything above this is a real difference, not rounding. + private const double Tolerance = 0.01; + + // Kerning is attributed to the left glyph of a pair. When a line breaks inside a word, the + // kern value of the pair at the break stays with the run on the first line. Allow for one + // kern value at 11pt. + private const double MidWordBreakTolerance = 0.6; + + private const float FontSize = 11f; + + // Test fonts only, so the measurements are the same on every machine. + private static RenderContext Rc + { + get { return TestFolderContext; } + } + + [ClassInitialize] + public static void ClassInitialize(TestContext context) + { + // The test fonts are part of the test setup, so a missing font is a failure, not + // an inconclusive result. + AssertTestFont(Roboto, FontSubFamily.Regular); + AssertTestFont(Roboto, FontSubFamily.Bold); + AssertTestFont(OpenSans, FontSubFamily.Regular); + } + + // ----------------------------------------------------------------------------------------- + // Width invariant + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_WrapInsideFragment() + { + var fragments = new[] { Rt("The quick brown fox jumps over the lazy dog") }; + var p = CreateParagraph(80, fragments); + + Assert.IsTrue(p.Lines.Count > 1, "Expected the text to wrap."); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_WrapExactlyAtFragmentBoundary() + { + var first = Rt("Hello "); + var second = Rt("World again"); + + // Wide enough for "Hello " but not for "Hello W", so the break falls on the boundary. + var widthHelloSpace = Measure("Hello ", first); + var widthHelloW = Measure("Hello W", first); + var maxWidth = Math.Ceiling(widthHelloSpace) + 1; + Assert.IsTrue(maxWidth < widthHelloW, "Test setup: max width must not fit 'Hello W'."); + + var fragments = new[] { first, second }; + var p = CreateParagraph(maxWidth, fragments); + + Assert.IsTrue(p.Lines.Count > 1, "Expected the text to wrap."); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_TrailingSpace_NoWrap() + { + var fragments = new[] { Rt("Hello world ") }; + var p = CreateParagraph(1000, fragments); + + Assert.AreEqual(1, p.Lines.Count); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + public void Invariant_DoubleSpaces_NoWrap() + { + var fragments = new[] { Rt("Hello world again") }; + var p = CreateParagraph(1000, fragments); + + Assert.AreEqual(1, p.Lines.Count); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_DoubleSpaces_Wrapped() + { + var fragments = new[] { Rt("alpha beta gamma delta epsilon") }; + var p = CreateParagraph(60, fragments); + + Assert.IsTrue(p.Lines.Count > 1, "Expected the text to wrap."); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_ExplicitLineBreak() + { + var fragments = new[] { Rt("First line \r\nSecond line") }; + var p = CreateParagraph(1000, fragments); + + Assert.AreEqual(2, p.Lines.Count); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_TwoFontsInParagraph() + { + var fragments = new[] + { + Rt("Alpha beta gamma "), + Rt("delta epsilon zeta ", Roboto, bold: true), + Rt("eta theta iota kappa", OpenSans), + }; + var p = CreateParagraph(90, fragments); + + Assert.IsTrue(p.Lines.Count > 1, "Expected the text to wrap."); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + [Ignore(TrailingSpaceIssue)] + public void Invariant_HyphenAsAdditionalBreakChar() + { + const string text = "well-known long-term state-of-the-art"; + var fragments = new[] { Rt(text) }; + var p = CreateParagraph(50, fragments); + + p.AddAdditionalWrappingChars(new[] { '-' }); + p.SetNewText(text); // re-wraps with the additional break char + + Assert.IsTrue(p.Lines.Count > 1, "Expected the text to wrap."); + AssertRunWidthsMatchShaping(p, fragments); + } + + [TestMethod] + public void Invariant_BreakInsideWordWithoutSpace() + { + var fragments = new[] { Rt("Supercalifragilisticexpialidocious") }; + var p = CreateParagraph(40, fragments); + + Assert.IsTrue(p.Lines.Count > 1, "Expected the word to be broken."); + AssertRunWidthsMatchShaping(p, fragments, MidWordBreakTolerance); + } + + // ----------------------------------------------------------------------------------------- + // Glyph fallback in measurement + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void GlyphFallback_EmojiIsMeasuredWithNotoEmojiAdvance() + { + const uint chartIncreasing = 0x1F4C8; // 📈 + var emoji = char.ConvertFromUtf32((int)chartIncreasing); + + var roboto = TestFolderEngine.LoadFont(Roboto); + Assert.IsFalse(roboto.CmapTable.TryGetGlyphId(chartIncreasing, out _), "Test setup: Roboto must not have the emoji."); + + // Where the provider routes the emoji, and that glyph's advance in points. + var provider = new DefaultFontProvider(TestFolderEngine, roboto); + Assert.IsTrue(provider.TryGetGlyphFont(chartIncreasing, out var fallbackFont, out var glyphId), "No fallback font has the emoji."); + Assert.AreNotSame(roboto, fallbackFont); + StringAssert.Contains(fallbackFont.GetEnglishFontFamilyName(), "Emoji"); + var emojiAdvance = fallbackFont.HmtxTable.GetAdvanceWidth(glyphId) * (double)FontSize / fallbackFont.HeadTable.UnitsPerEm; + var notdefAdvance = roboto.HmtxTable.GetAdvanceWidth(0) * (double)FontSize / roboto.HeadTable.UnitsPerEm; + Assert.AreNotEqual(notdefAdvance, emojiAdvance, 0.001, "Test setup: emoji and .notdef advances must differ."); + + // The width the layout path measured for the run. + var fragments = new[] { Rt("Sales " + emoji) }; + var p = CreateParagraph(1000, fragments); + Assert.AreEqual(1, p.Runs.Count); + + var expected = Measure("Sales ", fragments[0]) + emojiAdvance; + Assert.AreEqual(expected, p.Runs[0].Width, Tolerance, + "The emoji should be measured with the fallback font's advance, not Roboto's .notdef."); + + AssertRunWidthsMatchShaping(p, fragments); + } + + // ----------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------- + + private static void AssertTestFont(string family, FontSubFamily subFamily) + { + Assert.AreEqual(FontAvailability.Exact, TestFolderEngine.GetFontAvailability(family, subFamily), + $"Test font '{family} {subFamily}' is not available in {FontFolder}."); + } + + private static RichTextFormatSimple Rt(string text, string family = Roboto, bool bold = false) + { + return new RichTextFormatSimple(text, family, FontSize, bold); + } + + /// + /// Creates an auto-sized paragraph that wraps at points. + /// Auto-size is used because a fixed-size paragraph shrinks its own width to the widest + /// line after the first wrap, and later fragments would then wrap at that width. + /// + private static ParagraphRenderItem CreateParagraph(double maxWidth, params RichTextFormatSimple[] fragments) + { + var group = new GroupRenderItem(new BoundingBox(0, 0, 1000, 1000)); + var body = new SvgTextBodyRenderItem(Rc, group, 0, 0, maxWidth, 1000, false, autoSize: true); + + var p = body.AddParagraph(fragments[0]); + for (int i = 1; i < fragments.Length; i++) + { + p.AddRichText(fragments[i]); + } + return p; + } + + private static double Measure(string text, IFontFormatBase font) + { + return Rc.GetMeasurementShaper(font).ShapeLight(text).GetWidthInPoints(font.Size); + } + + /// + /// Asserts that every run's width equals the width of its own text shaped in its own font. + /// The font is taken from the input fragment the run came from (OriginalRtIdx), since + /// ParagraphRenderItem.AddRichText(IRichTextFormatSimple) does not re-import styles to the + /// runs it recreates. All mismatches are reported together. + /// + private static void AssertRunWidthsMatchShaping(ParagraphRenderItem p, RichTextFormatSimple[] fragments, double tolerance = Tolerance) + { + Assert.IsTrue(p.Runs.Count > 0, "The paragraph has no runs."); + + var report = new StringBuilder(); + var failures = 0; + + foreach (var run in p.Runs) + { + if (string.IsNullOrEmpty(run.CurrentText)) + continue; + + Assert.IsTrue(run.OriginalRtIdx >= 0 && run.OriginalRtIdx < fragments.Length, + $"Run '{run.CurrentText}' has no valid source fragment (OriginalRtIdx {run.OriginalRtIdx})."); + var font = fragments[run.OriginalRtIdx]; + + var expected = Measure(run.CurrentText, font); + var diff = run.Width - expected; + var ok = Math.Abs(diff) <= tolerance; + if (!ok) failures++; + + report.AppendLine(string.Format(CultureInfo.InvariantCulture, + "{0} '{1}' [{2} {3}]: run.Width={4:F3} shaped={5:F3} diff={6:+0.000;-0.000;0.000}", + ok ? " " : "!!", run.CurrentText, font.Family, font.SubFamily, run.Width, expected, diff)); + } + + if (failures > 0) + { + Assert.Fail($"{failures} run(s) differ from their shaped width by more than {tolerance}pt:{Environment.NewLine}{report}"); + } + } + } +} diff --git a/src/EPPlus.DrawingRenderer.Tests/Text/WrapExcelComparisonTests.cs b/src/EPPlus.DrawingRenderer.Tests/Text/WrapExcelComparisonTests.cs new file mode 100644 index 0000000000..e83410b8fb --- /dev/null +++ b/src/EPPlus.DrawingRenderer.Tests/Text/WrapExcelComparisonTests.cs @@ -0,0 +1,205 @@ +using System.Drawing; +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using EPPlus.Fonts.OpenType; +using OfficeOpenXml; +using OfficeOpenXml.Drawing; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.DrawingRenderer.Tests.Text +{ + /// + /// Manual verification of text wrapping against Excel, before changing the wrap code. + /// + /// Writes WrapExcelComparison.xlsx with one shape per case, an svg per shape and an html page + /// with all svgs, plus a text dump of every tspan (x and text). Open the workbook in Excel and + /// compare each shape with its svg. + /// + /// The font is Calibri, read from the system font directories, so the test is Inconclusive + /// where Calibri is not installed. The svgs are exported for the document target so Calibri is + /// not substituted. + /// + /// Expected, from reading the wrap code: + /// A, B, E - line breaks and positions match Excel; the trailing space on wrapped lines + /// only affects run.Width internally, never a visible position. + /// C, D - when a word is broken inside (no space to break at), the first run on the new + /// line is measured one character too narrow (the character moved to the new + /// line is not counted), so the next run on that line starts too far left and + /// overlaps it. + /// + [TestClass] + public class WrapExcelComparisonTests : TestBase + { + private const string FontName = "Calibri"; + private const float FontSize = 11f; + private const string OutputFolder = "svg\\WrapExcelComparison\\"; + + private static readonly Color[] RunColors = + { + Color.Black, Color.Red, Color.Blue, Color.DarkGreen, Color.DarkOrange, Color.Purple + }; + + [TestMethod] + public void WrapComparison_Calibri() + { + var engine = new OpenTypeFontEngine(cfg => cfg.SearchSystemDirectories = true); + if (engine.GetFontAvailability(FontName) != FontAvailability.Exact + || engine.GetFontAvailability(FontName, FontSubFamily.Bold) != FontAvailability.Exact) + { + Assert.Inconclusive(FontName + " (Regular and Bold) must be installed for this comparison."); + } + + var cases = new List(); + var dump = new StringBuilder(); + + using (var p = OpenPackage("WrapExcelComparison.xlsx", true)) + { + p.Workbook.UseFontEngine(engine); + var ws = p.Workbook.Worksheets.Add("Wrap"); + + // A: right aligned, several lines broken at spaces. + cases.Add(AddCase(ws, "A_RightAligned", 0, 150, eTextAlignment.Right, + R("The quick brown fox jumps over the lazy dog and keeps on running"))); + + // B: the same text centered. + cases.Add(AddCase(ws, "B_Centered", 1, 150, eTextAlignment.Center, + R("The quick brown fox jumps over the lazy dog and keeps on running"))); + + // C: one long word broken inside, followed directly (no space) by a second run in + // another colour. The second run lands on a line that starts with the word's tail. + cases.Add(AddCase(ws, "C_MidWordBreak_TwoColours", 2, 60, eTextAlignment.Left, + R("Supercalifragilistic"), R("XYZ"), R("abc"))); + + // D: as C, but the second run is bold and larger. + cases.Add(AddCase(ws, "D_MidWordBreak_TwoFonts", 3, 60, eTextAlignment.Left, + R("Supercalifragilistic"), R("XYZ", bold: true, size: 14f), R("abc"))); + + // E: break at a space on a fragment boundary, with more runs on the next line. + cases.Add(AddCase(ws, "E_FragmentBoundary", 4, 70, eTextAlignment.Left, + R("Hello "), R("World "), R("again "), R("and again"))); + + var html = new StringBuilder(); + html.AppendLine("Wrap comparison"); + html.AppendLine(""); + + foreach (var shape in cases) + { + var svg = shape.ToSvg(o => o.FontTarget = FontRenderTarget.Document); + var svgFile = GetOutputFile(OutputFolder, shape.Name + ".svg"); + File.WriteAllText(svgFile.FullName, svg); + + html.AppendLine($"
{WebUtility.HtmlEncode(shape.Name)}
"); + + dump.AppendLine(shape.Name); + foreach (var tspan in GetTspans(engine, svg)) + { + dump.AppendLine(" " + tspan); + } + dump.AppendLine(); + } + + html.AppendLine(""); + File.WriteAllText(GetOutputFile(OutputFolder, "index.html").FullName, html.ToString()); + File.WriteAllText(GetOutputFile(OutputFolder, "tspans.txt").FullName, dump.ToString()); + + SaveAndCleanup(p); + } + + Console.WriteLine(dump.ToString()); + } + + private sealed class RunSpec + { + public string Text = ""; + public bool Bold; + public float Size = FontSize; + } + + private static RunSpec R(string text, bool bold = false, float size = FontSize) + { + return new RunSpec { Text = text, Bold = bold, Size = size }; + } + + /// + /// Adds a rectangle with black text on white, no insets, at row 2 + index * 8. + /// Each run gets its own colour so run boundaries are visible. + /// + private static ExcelShape AddCase(ExcelWorksheet ws, string name, int index, int widthPx, eTextAlignment alignment, params RunSpec[] runs) + { + var shape = ws.Drawings.AddShape(name, eShapeStyle.Rect); + shape.SetPosition(1 + index * 8, 0, 1, 0); + shape.SetSize(widthPx, 120); + + shape.Fill.Style = eFillStyle.SolidFill; + shape.Fill.Color = Color.White; + shape.Border.Fill.Style = eFillStyle.SolidFill; + shape.Border.Fill.Color = Color.Gray; + + shape.TextBody.LeftInsert = 0; + shape.TextBody.RightInsert = 0; + shape.TextBody.TopInsert = 0; + shape.TextBody.BottomInsert = 0; + shape.TextBody.Anchor = eTextAnchoringType.Top; + + for (int i = 0; i < runs.Length; i++) + { + var rt = shape.RichText.Add(runs[i].Text, i == 0); + rt.SetFromFont(FontName, runs[i].Size, runs[i].Bold); + rt.Color = RunColors[i % RunColors.Length]; + rt.HorizontalAlignment = alignment; + } + + return shape; + } + + /// + /// Returns one line per tspan in document order: x, y, the text's own width shaped in the + /// tspan's font (px), where that text ends (x + width), and the text. When the next tspan + /// on the same line starts before "end", the runs overlap. + /// + private static IEnumerable GetTspans(OpenTypeFontEngine engine, string svg) + { + foreach (Match m in Regex.Matches(svg, "]*)>([^<]*)")) + { + var attributes = m.Groups[1].Value; + var text = WebUtility.HtmlDecode(m.Groups[2].Value); + var x = ParseNumber(GetAttribute(attributes, "x")); + var y = ParseNumber(GetAttribute(attributes, "y")); + var family = (SvgStyle.Property(attributes, "font-family") ?? FontName).Split(',')[0].Trim().Trim('\'', '"'); + var sizePx = ParseNumber(SvgStyle.Property(attributes, "font-size")); + var bold = SvgStyle.Property(attributes, "font-weight") == "bold"; + + double widthPx = double.NaN; + if (!double.IsNaN(sizePx)) + { + var shaper = engine.GetMeasurementShaper(family, bold ? FontSubFamily.Bold : FontSubFamily.Regular); + // Shaping at the pixel size gives the width in pixels. + widthPx = shaper.ShapeLight(text).GetWidthInPoints((float)sizePx); + } + + yield return string.Format(CultureInfo.InvariantCulture, + "x={0,8:F2} y={1,7:F2} width={2,7:F2} end={3,8:F2} {4}{5} '{6}'", + x, y, widthPx, x + widthPx, family, bold ? " Bold" : "", text); + } + } + + private static string? GetAttribute(string attributes, string name) + { + // EPPlus writes some attributes with a space before '=' (x ="0"). + var m = Regex.Match(attributes, "(?:^|\\s)" + Regex.Escape(name) + "\\s*=\\s*\"([^\"]*)\""); + return m.Success ? m.Groups[1].Value : null; + } + + private static double ParseNumber(string? value) + { + if (string.IsNullOrEmpty(value)) + return double.NaN; + double result; + return double.TryParse(value.Replace("px", ""), NumberStyles.Float, CultureInfo.InvariantCulture, out result) + ? result + : double.NaN; + } + } +} diff --git a/src/EPPlus.DrawingRenderer/RenderContext.cs b/src/EPPlus.DrawingRenderer/RenderContext.cs index 666ad65b82..2b66a15cfb 100644 --- a/src/EPPlus.DrawingRenderer/RenderContext.cs +++ b/src/EPPlus.DrawingRenderer/RenderContext.cs @@ -13,46 +13,79 @@ namespace EPPlus.DrawingRenderer /// public class RenderContext : IDisposable { - private readonly object _lock; - private readonly Func _engineFactory; - private readonly RenderContext _root; - private volatile OpenTypeFontEngine _fontEngine; + // A context is either a root, which owns the engine factory and creates the engine, or a + // view, which has a root and delegates every engine access to it. Exactly one of + // _engineFactory and _root is set. + private readonly object _lock = new object(); + private readonly Func? _engineFactory; + private readonly RenderContext? _root; + private volatile OpenTypeFontEngine? _fontEngine; public RenderContext(Func engineFactory) { if (engineFactory == null) throw new ArgumentNullException("engineFactory"); _engineFactory = engineFactory; - _lock = new object(); Target = FontRenderTarget.Document; } /// /// Creates a view of the root context for another render target. Shares the root's font engine. /// - private RenderContext(RenderContext root, FontRenderTarget target) + private RenderContext(RenderContext root, FontRenderTarget target, bool substituteWebFonts) { + if (root == null) + throw new ArgumentNullException("root"); _root = root; Target = target; + SubstituteWebFonts = substituteWebFonts; } /// - /// The output kind text is laid out for. Decides whether web font substitution applies. + /// The output kind text is laid out for. /// public FontRenderTarget Target { get; private set; } + /// + /// True when fonts are substituted for the web before text is measured, so text is laid out + /// with a font a browser is likely to have (e.g. Aptos Narrow is measured as Calibri). + /// False when the requested font is measured as is, for instance because the fonts are + /// embedded in the output. Substitution only ever applies to . + /// + public bool SubstituteWebFonts { get; private set; } + /// /// Returns a context for the given target that shares this context's font engine and cache. + /// Web font substitution applies when the target is . /// public RenderContext ForTarget(FontRenderTarget target) { - if (target == Target) + return ForTarget(target, target == FontRenderTarget.Web); + } + + /// + /// Returns a context for the given target that shares this context's font engine and cache. + /// + /// The output kind text is laid out for. + /// + /// Whether fonts are substituted for the web before measuring. Has no effect unless + /// is . + /// + public RenderContext ForTarget(FontRenderTarget target, bool substituteWebFonts) + { + if (target == Target && substituteWebFonts == SubstituteWebFonts) return this; var root = _root ?? this; - return target == root.Target ? root : new RenderContext(root, target); + if (target == root.Target && substituteWebFonts == root.SubstituteWebFonts) + return root; + + return new RenderContext(root, target, substituteWebFonts); } + /// + /// The font engine, created on first use by the root context. A view returns its root's engine. + /// public OpenTypeFontEngine FontEngine { get @@ -60,23 +93,36 @@ public OpenTypeFontEngine FontEngine if (_root != null) return _root.FontEngine; - if (_fontEngine == null) + var engine = _fontEngine; + if (engine != null) + return engine; + + lock (_lock) { - lock (_lock) + if (_fontEngine == null) { - if (_fontEngine == null) - _fontEngine = _engineFactory(); + if (_engineFactory == null) + throw new InvalidOperationException("The render context has neither a root context nor an engine factory."); + + var created = _engineFactory(); + if (created == null) + throw new InvalidOperationException("The engine factory returned null."); + _fontEngine = created; } + return _fontEngine; } - return _fontEngine; } } /// - /// Returns the font family to lay out and output text with for this context's target. + /// Returns the font family to lay out and output text with for this context. The family is + /// substituted only when is true and the target is + /// ; otherwise it is returned unchanged. /// public string GetFamilyForTarget(string fontName) { + if (!SubstituteWebFonts) + return fontName; return FontEngine.GetFamilyForTarget(fontName, Target); } diff --git a/src/EPPlus.DrawingRenderer/RenderItems/Textbox/ParagraphRenderItem.cs b/src/EPPlus.DrawingRenderer/RenderItems/Textbox/ParagraphRenderItem.cs index 32f38def66..5820e6c029 100644 --- a/src/EPPlus.DrawingRenderer/RenderItems/Textbox/ParagraphRenderItem.cs +++ b/src/EPPlus.DrawingRenderer/RenderItems/Textbox/ParagraphRenderItem.cs @@ -73,6 +73,15 @@ public enum TextLineSpacing public abstract class ParagraphRenderItem : RenderItem { + /// + /// The family of the default font of a paragraph that has no font of its own: the default + /// font of a new workbook. + /// + public const string FallbackFontFamily = "Aptos Narrow"; + /// + /// The size in points of the default font of a paragraph that has no font of its own. + /// + public const float FallbackFontSize = 11; protected double LeftMargin { get; set; } protected double RightMargin { get; set; } protected double LineSpacingAscendantOnly { get; set; } @@ -158,7 +167,7 @@ protected ParagraphRenderItem(RenderContext renderContext, BoundingBox parent, b Name = "Paragraph"; if (setFallbackDefaultFont) { - var defaultFont = new MeasurementFont { FontFamily = "Aptos Narrow", Size = 11, Style = MeasurementFontStyles.Regular }; + var defaultFont = new MeasurementFont { FontFamily = FallbackFontFamily, Size = FallbackFontSize, Style = MeasurementFontStyles.Regular }; DefaultParagraphFont = new FontFormatBase(defaultFont); } } diff --git a/src/EPPlus.DrawingRenderer/Svg/Core/BaseRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/Core/BaseRenderer.cs index f09bc947bc..de2df82a51 100644 --- a/src/EPPlus.DrawingRenderer/Svg/Core/BaseRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/Core/BaseRenderer.cs @@ -1,8 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ namespace EPPlus.DrawingRenderer { public abstract class BaseRenderer diff --git a/src/EPPlus.DrawingRenderer/Svg/Core/SvgBaseRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/Core/SvgBaseRenderer.cs index b8aaf2edf7..e622c8527f 100644 --- a/src/EPPlus.DrawingRenderer/Svg/Core/SvgBaseRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/Core/SvgBaseRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.DrawingRenderer.Utils; using System.Globalization; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/Core/SvgBasicShapesRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/Core/SvgBasicShapesRenderer.cs index e444b638d3..f449e7a6ff 100644 --- a/src/EPPlus.DrawingRenderer/Svg/Core/SvgBasicShapesRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/Core/SvgBasicShapesRenderer.cs @@ -1,25 +1,38 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.DrawingRenderer.Svg; using EPPlus.Export.ImageRenderer.RenderItems.Shared; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace EPPlus.DrawingRenderer { public class SvgBasicShapesRenderer : IBasicIShapesRenderer { public SvgBasicShapesRenderer(StringBuilder outputStream) + : this(outputStream, SvgFontPlan.WithoutContext) + { + } + + internal SvgBasicShapesRenderer(StringBuilder outputStream, SvgFontPlan fontPlan) { LineRenderer = new SvgLineRenderer(outputStream); RectangleRenderer = new SvgRectRenderer(outputStream); EllipseRenderer = new SvgEllipseRenderer(outputStream); PathRenderer = new SvgPathRenderer(outputStream); - ParagraphRenderer = new SvgParagraphRenderer(this, outputStream); - GroupRenderer = new SvgGroupRenderer(this, outputStream); - TextRunRenderer = new SvgTextRunRenderer(outputStream); + ParagraphRenderer = new SvgParagraphRenderer(this, outputStream) { FontPlan = fontPlan }; + GroupRenderer = new SvgGroupRenderer(this, outputStream) { FontPlan = fontPlan }; + TextRunRenderer = new SvgTextRunRenderer(outputStream) { FontPlan = fontPlan }; TitleRenderer = new SvgTitleRenderer(outputStream); UseReferenceRenderer = new SvgUseReferenceRenderer(outputStream); diff --git a/src/EPPlus.DrawingRenderer/Svg/Core/SvgShapeRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/Core/SvgShapeRenderer.cs index 165cdd76d7..75337d591d 100644 --- a/src/EPPlus.DrawingRenderer/Svg/Core/SvgShapeRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/Core/SvgShapeRenderer.cs @@ -1,4 +1,16 @@ -using DrawingRenderer.Constants; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using DrawingRenderer.Constants; using EPPlus.DrawingRenderer.RenderItems; using EPPlus.DrawingRenderer.Svg; using EPPlus.DrawingRenderer.Utils; @@ -15,10 +27,49 @@ namespace EPPlus.DrawingRenderer { public class SvgShapeRenderer : IShapeRenderer { + /// + /// The class on the root svg element, which scopes to this svg. + /// + internal const string RootClass = "epplus-svg"; + + /// + /// Protects the text from css of a host page, so the browser lays out text the way it was + /// measured. The rule is written in the svg's style element, scoped by so + /// it applies to nothing else on a page the svg is inlined in, and marked important so it also + /// wins over host rules that match text and tspan directly (e.g. "* { letter-spacing: 2px }"), + /// which inherited values do not. + /// Bold and italic synthesis is allowed: measurement uses the regular font file when a family + /// has no bold or italic file, and the face is declared with the weight and style of that file, + /// so the browser synthesizes exactly where no matching face exists, as Excel does. The widths + /// are kept by textLength either way. + /// + internal const string TextStyleRule = + "." + RootClass + " text,." + RootClass + " tspan{" + + "font-kerning:normal!important;" + + "font-variant-ligatures:common-ligatures contextual!important;" + + "letter-spacing:0!important;" + + "word-spacing:0!important;" + + "font-synthesis:weight style!important;" + + "text-rendering:geometricPrecision!important}"; + SvgRenderOptions _options; + readonly SvgFontPlan _fontPlan; public SvgShapeRenderer(BoundingBox bounds, StringBuilder outputStream, SvgRenderOptions options) + : this(bounds, outputStream, options, null) { - BasicShapesRenderer = new SvgBasicShapesRenderer(outputStream); + } + + /// + /// Creates a renderer that writes font-family stacks with fallback chains and a generic + /// family, resolved through the render context's font engine, and that embeds the fonts as + /// subsets when is set. Pass the render context the + /// render items were measured with. Without a context only the family and sans-serif are + /// written and no font is embedded. + /// + public SvgShapeRenderer(BoundingBox bounds, StringBuilder outputStream, SvgRenderOptions options, RenderContext? renderContext) + { + _fontPlan = new SvgFontPlan(renderContext, options.EmbedFonts); + BasicShapesRenderer = new SvgBasicShapesRenderer(outputStream, _fontPlan); _options = options; //Override size. if (options.Width.HasValue) @@ -42,35 +93,35 @@ public SvgShapeRenderer(BoundingBox bounds, StringBuilder outputStream, SvgRende public bool Render(List items) { OutputStream.Clear(); - OutputStream.Append($""); + OutputStream.Append($""); PreRender(items); foreach (var item in items) { - if(item is RenderItem renderItem) - switch (renderItem.Type) - { - case RenderItemType.Group: - BasicShapesRenderer.GroupRenderer.Render((GroupRenderItem)item); - break; - case RenderItemType.Line: - BasicShapesRenderer.LineRenderer.Render((LineRenderItem)item); - break; - case RenderItemType.Rect: - BasicShapesRenderer.RectangleRenderer.Render((RectRenderItem)item); - break; - case RenderItemType.Ellipse: - BasicShapesRenderer.EllipseRenderer.Render((EllipseRenderItem)item); - break; - case RenderItemType.Path: - BasicShapesRenderer.PathRenderer.Render((PathRenderItem)item); - break; - case RenderItemType.Paragraph: - BasicShapesRenderer.ParagraphRenderer.Render((ParagraphRenderItem)item); - break; - case RenderItemType.UseReference: - BasicShapesRenderer.UseReferenceRenderer.Render((UseReferenceRenderItem)item); - break; - } + if (item is RenderItem renderItem) + switch (renderItem.Type) + { + case RenderItemType.Group: + BasicShapesRenderer.GroupRenderer.Render((GroupRenderItem)item); + break; + case RenderItemType.Line: + BasicShapesRenderer.LineRenderer.Render((LineRenderItem)item); + break; + case RenderItemType.Rect: + BasicShapesRenderer.RectangleRenderer.Render((RectRenderItem)item); + break; + case RenderItemType.Ellipse: + BasicShapesRenderer.EllipseRenderer.Render((EllipseRenderItem)item); + break; + case RenderItemType.Path: + BasicShapesRenderer.PathRenderer.Render((PathRenderItem)item); + break; + case RenderItemType.Paragraph: + BasicShapesRenderer.ParagraphRenderer.Render((ParagraphRenderItem)item); + break; + case RenderItemType.UseReference: + BasicShapesRenderer.UseReferenceRenderer.Render((UseReferenceRenderItem)item); + break; + } } OutputStream.AppendLine(""); return true; @@ -78,8 +129,8 @@ public bool Render(List items) private string GetViewBoxAttr() { - if (string.IsNullOrEmpty(ViewBox)) return $" viewbox=\"0 0 {Math.Round(Bounds.Width + 1,0).PointToPixelString()} {Math.Round(Bounds.Height + 1).PointToPixelString()}\""; // +1 here is to make sure outer borders are not clipped. This should be fixed for when the full calculation for the viewbox is implemented. For now, we just add 1 pixel to the width and height to make sure the outer border is not clipped. - return $" viewbox=\"{ViewBox}\""; + if (string.IsNullOrEmpty(ViewBox)) return $" viewBox=\"0 0 {Math.Round(Bounds.Width + 1,0).PointToPixelString()} {Math.Round(Bounds.Height + 1).PointToPixelString()}\""; // +1 here is to make sure outer borders are not clipped. This should be fixed for when the full calculation for the viewbox is implemented. For now, we just add 1 pixel to the width and height to make sure the outer border is not clipped. + return $" viewBox=\"{ViewBox}\""; } public void PreRenderGroup(List items, StringBuilder defSb, HashSet hs, ref int ix) @@ -111,13 +162,17 @@ public bool PreRender(List items) var hs = new HashSet(); var ix = 1; - //foreach (var item in items) - //{ - // if (item is RenderItem) - // { - PreRenderGroup(items, defSb, hs, ref ix); - // } - //} + // The fonts are planned from all text of the svg before anything is written. The style + // element declares the embedded subsets, then the rule that protects the text from host css. + _fontPlan.BeginCollect(); + CollectText(items); + _fontPlan.Build(); + defSb.Append(""); + + PreRenderGroup(items, defSb, hs, ref ix); if (defSb.Length > 0) { @@ -126,10 +181,40 @@ public bool PreRender(List items) OutputStream.Append("
"); } - ////Remove all items that have already been rendered - //renderItems.RemoveAll(x => x is SvgRenderItem svgX && string.IsNullOrEmpty(svgX.DefId) == false); return true; } + + /// + /// Adds the text of the render items to the font plan, and registers the default fonts of + /// groups and paragraphs, which have no text of their own but get a font-family stack. + /// + void CollectText(List items) + { + foreach (var t in items) + { + if (t is GroupRenderItem group) + { + _fontPlan.AddText(group.GroupDefaultFont, null); + CollectText(group.ChildObjects); + } + else if (t is ParagraphRenderItem paragraph) + { + _fontPlan.AddText(paragraph.DefaultParagraphFont, null); + if (paragraph.Runs != null) + { + foreach (var run in paragraph.Runs) + { + _fontPlan.AddText(run._measurementFont, run.CurrentText); + } + } + } + else if (t is TextRunRenderItem run) + { + _fontPlan.AddText(run._measurementFont, run.CurrentText); + } + } + } + Dictionary _defsCache = new Dictionary(); private void WriteDefsForRenderItem(StringBuilder defSb, HashSet hs, ref int ix, RenderItem item) { diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgEllipseRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgEllipseRenderer.cs index ca9697120b..19c4ae1db5 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgEllipseRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgEllipseRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.Utils; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgGroupRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgGroupRenderer.cs index ea0322c64f..3c3ac29859 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgGroupRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgGroupRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.GenericFontWidths; using EPPlus.Fonts.OpenType.Utils; using System.Globalization; @@ -16,6 +28,7 @@ public SvgGroupRenderer(IBasicIShapesRenderer shapeRenderer, Stri { _shapeRenderer = shapeRenderer; } + internal SvgFontPlan FontPlan { get; set; } = SvgFontPlan.WithoutContext; internal string Suffix = "px"; public override void Render(GroupRenderItem item) { @@ -125,7 +138,7 @@ string GetDefaultFontAttribute(GroupRenderItem item) if (font != null && string.IsNullOrEmpty(font.Family) == false) { - defFontAttributes = $" font-family=\"{font.Family},{font.Family}_MSFontService,sans-serif\" " + + defFontAttributes = $" font-family=\"{FontPlan.GetFontFamilyAttributeValue(font)}\" " + $"font-size=\"{font.Size.ToString(CultureInfo.InvariantCulture)}px\" "; } diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgLineRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgLineRenderer.cs index c4acda910c..ffbda546e2 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgLineRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgLineRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.Utils; using System.Globalization; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgParagraphRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgParagraphRenderer.cs index a0ef177910..333978efd3 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgParagraphRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgParagraphRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Export.ImageRenderer.RenderItems; using EPPlus.Export.ImageRenderer.RenderItems.Shared; using EPPlus.Fonts.OpenType.Utils; @@ -15,6 +27,7 @@ public SvgParagraphRenderer(IBasicIShapesRenderer shapeRenderer, { _shapeRenderer = shapeRenderer; } + internal SvgFontPlan FontPlan { get; set; } = SvgFontPlan.WithoutContext; internal string Suffix = "px"; public override void Render(ParagraphRenderItem item) { @@ -96,12 +109,13 @@ public override void Render(ParagraphRenderItem item) // } //} - sb.Append(""); + // The default font in the style attribute, as on the runs: an inline style wins over css of a host page. + sb.Append($"style=\"font-family:{FontPlan.GetFontFamilyAttributeValue(item.DefaultParagraphFont)};font-size:{fontSize}px;\" >"); if (item.Runs != null && item.Runs.Count > 0) { diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgPathRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgPathRenderer.cs index 7b50155b05..70c8b53bd8 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgPathRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgPathRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.Utils; using EPPlusImageRenderer; using EPPlusImageRenderer.RenderItems; diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgRectRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgRectRenderer.cs index 8d76903534..c00521a110 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgRectRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgRectRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.Utils; using System.Globalization; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRenderer.cs index 2d85760517..ae3e8059d1 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Export.ImageRenderer.RenderItems.Shared; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRunRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRunRenderer.cs index 53d1e0c12b..56dbe255e8 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRunRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTextRunRenderer.cs @@ -6,6 +6,8 @@ using EPPlus.Fonts.OpenType.Utils; using EPPlusImageRenderer.RenderItems; using OfficeOpenXml.Interfaces.Drawing.Text; +using OfficeOpenXml.Interfaces.Fonts; +using OfficeOpenXml.Interfaces.RichText; using OfficeOpenXml.Utils; using System.Globalization; using System.Text; @@ -21,170 +23,170 @@ public SvgTextRunRenderer(StringBuilder outputStream) : base(outputStream) } - string GetFontStyleAttributes(TextRunRenderItem textRun) + internal SvgFontPlan FontPlan { get; set; } = SvgFontPlan.WithoutContext; + + /// + /// Appends the font-style, font-weight and text-decoration declarations of the run. Weight and + /// style follow the subfamily the text was measured with, which is also the subfamily of the + /// embedded face, so output cannot diverge from measurement; the run's own flags are used only + /// when it has no measurement font. When the underline has a color of its own, text-decoration + /// goes on a wrapping tspan instead (see ), whose fill is the + /// color the line is drawn with. + /// + void AppendFontStyleDeclarations(TextRunRenderItem textRun, StringBuilder style) { - string fontStyleAttributes = " "; - - if (textRun._isItalic) + bool bold, italic; + if (textRun._measurementFont != null) { - fontStyleAttributes += "font-style=\"italic\" "; + var subFamily = textRun._measurementFont.SubFamily; + bold = subFamily == FontSubFamily.Bold || subFamily == FontSubFamily.BoldItalic; + italic = subFamily == FontSubFamily.Italic || subFamily == FontSubFamily.BoldItalic; } - if (textRun._isBold) + else { - fontStyleAttributes += "font-weight=\"bold\" "; + bold = textRun._isBold; + italic = textRun._isItalic; } - string content = ""; + if (italic) + { + style.Append("font-style:italic;"); + } + if (bold) + { + style.Append("font-weight:bold;"); + } - if (textRun._underLineType != eDrawingUnderLineType.None | textRun._strikeType != eDrawingStrikeType.No) + string decoration = string.Empty; + if (textRun._underLineType != eDrawingUnderLineType.None) { - string underlineContent = ""; - if (textRun._underLineType != eDrawingUnderLineType.None) + // Double, dotted, dashed and wavy underlines need text-decoration-style, which svg + // renderers do not support consistently, so every type is drawn as a single underline. + decoration = "underline"; + if (textRun._underlineColor != System.Drawing.Color.Empty) { - switch (textRun._underLineType) - { - case eDrawingUnderLineType.Single: - underlineContent += "underline"; - break; - //These are all css only apparently - //case eUnderLineType.Double: - // fontStyleAttributes += "double"; - // break; - //case eUnderLineType.Dotted: - // fontStyleAttributes += "dotted"; - // break; - //case eUnderLineType.Dash: - // fontStyleAttributes += "dashed"; - // break; - //case eUnderLineType.Wavy: - // fontStyleAttributes += "wavy"; - // break; - default: - underlineContent += "underline"; - break; - //throw new NotImplementedException("Not implemented yet"); - } - if(textRun._underlineColor != System.Drawing.Color.Empty) - { - UnderlineColorString = $"{{1}}"; - } - content += underlineContent; - //Underline color - //We can change the underline color using double tspans - // SVG with a colored underlinesection. + UnderlineColorString = $"{{1}}"; } + } + if (textRun._strikeType == eDrawingStrikeType.Single) + { + // Line values are separated by spaces; a comma makes the whole declaration invalid. + decoration += decoration.Length > 0 ? " line-through" : "line-through"; + } - if (textRun._strikeType == eDrawingStrikeType.Single) - { - //Has to check if Both underline and strike - if (textRun._underLineType != eDrawingUnderLineType.None) - { - content += ","; - } - content += "line-through"; - } + if (decoration.Length == 0) + { + return; + } + if (string.IsNullOrEmpty(UnderlineColorString)) + { + style.Append("text-decoration:").Append(decoration).Append(';'); + } + else + { + UnderlineColorString = string.Format(UnderlineColorString, $"text-decoration:{decoration};", "{0}"); + } + } - if(string.IsNullOrEmpty(content) == false) - { - if (string.IsNullOrEmpty(UnderlineColorString)) - { - fontStyleAttributes += $" text-decoration=\"{content}\" "; - } - else - { - UnderlineColorString = string.Format(UnderlineColorString, $"text-decoration: {content};", "{0}"); - } - } + /// + /// The textLength and lengthAdjust attributes that make the browser draw the text with the + /// width it was measured with, whatever font it ends up using. Empty when the text has no + /// measured width. + /// + string GetTextLengthAttributes(IFontFormatBase font, string text) + { + var width = FontPlan.MeasureWidthInPoints(font, text); + if (width.HasValue == false || width.Value <= 0) + { + return string.Empty; } - return fontStyleAttributes; + return $"textLength=\"{width.Value.PointToPixelString()}\" lengthAdjust=\"spacing\" "; } public override void Render(TextRunRenderItem textRun) { - var sbStartidx = OutputStream.Length -1; - - string finalString = ""; - var xString = $"x =\"{(textRun.Left.PointToPixelString())}\" "; + double fontSize = textRun.FontSizeInPixels; - var currentYEndPos = textRun.Position.Y; // Global position Y - finalString += $"= textRun.ClippingHeight) + if (textRun._measurementFont != null && segments == null) { - //visibility = " display=\"none\""; + sb.Append(GetTextLengthAttributes(textRun._measurementFont, textRun.CurrentText)); } - finalString += visibility; - finalString += $"{GetFontStyleAttributes(textRun)}"; - + // Font and fill go in the style attribute rather than in presentation attributes: an inline + // style wins over the css rules of a host page (e.g. "* { font-family: ... }"), which beat + // presentation attributes and would draw the text with another font than it was measured with. + var style = new StringBuilder(); if (textRun._measurementFont != null) { - finalString += $"font-family=\"{textRun._measurementFont.Family}," - + $"{textRun._measurementFont.Family}_MSFontService,sans-serif\" " - + $"font-size=\"{fontSize.ToString(CultureInfo.InvariantCulture)}px\" "; + style.Append("font-family:").Append(FontPlan.GetFontFamilyAttributeValue(textRun._measurementFont)).Append(';'); + style.Append("font-size:").Append(fontSize.ToString(CultureInfo.InvariantCulture)).Append("px;"); } - - if(string.IsNullOrEmpty(textRun.Style.FillColor) == false) + AppendFontStyleDeclarations(textRun, style); + if (string.IsNullOrEmpty(textRun.Style.FillColor) == false) { - finalString += $" style=\"fill: {textRun.Style.FillColor};\" "; + style.Append("fill:").Append(textRun.Style.FillColor).Append(';'); + } + if (style.Length > 0) + { + sb.Append("style=\"").Append(style).Append("\" "); } - //Avoid rendering fill color as we do so via style - var temp = textRun.Style.FillColor; + // The fill is in the style attribute, so the base must not write it as an attribute as well. + var fillColor = textRun.Style.FillColor; textRun.Style.FillColor = null; - - var sb = new StringBuilder(); - sb.Append(finalString); - - //Get color etc. - //Renders up until this point (must be done to end the attribute addings so that text content can then be added) RenderBaseToSpecified(textRun, sb); + textRun.Style.FillColor = fillColor; - textRun.Style.FillColor = temp; - - //Since final string has been written in base.render erase it. - finalString = ""; - - finalString += ">"; - //Add actual text content - finalString += ConvertUtil.HtmlEscapeString(textRun.CurrentText); - finalString += ""; - sb.Append(finalString); + sb.Append('>'); + if (segments == null) + { + sb.Append(ConvertUtil.HtmlEscapeString(textRun.CurrentText)); + } + else + { + foreach (var segment in segments) + { + sb.Append("').Append(ConvertUtil.HtmlEscapeString(segment.Text)).Append(""); + } + } + sb.Append(""); var textRunString = sb.ToString(); - //Wrap in another tspan to apply underline color if neccesary + // Wrap in another tspan to draw the underline in its own color. if (string.IsNullOrEmpty(UnderlineColorString) == false) { textRunString = string.Format(UnderlineColorString, textRunString); } - if (textRun is SvgTextRunRenderItem) + if (textRun is SvgTextRunRenderItem tr && tr.RenderTextNode) { - var tr = (SvgTextRunRenderItem)textRun; - if (tr.RenderTextNode) - { - textRunString = $"{textRunString}"; - } + textRunString = $"{textRunString}"; } OutputStream.Append(textRunString); UnderlineColorString = string.Empty; } } -} +} \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTitleRenderer.cs b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTitleRenderer.cs index cb05caebef..4f4224f9c6 100644 --- a/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTitleRenderer.cs +++ b/src/EPPlus.DrawingRenderer/Svg/ItemRenderers/SvgTitleRenderer.cs @@ -1,4 +1,16 @@ -using EPPlus.DrawingRenderer.RenderItems; +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.DrawingRenderer.RenderItems; using EPPlus.Fonts.OpenType.Utils; using System.Globalization; using System.Text; diff --git a/src/EPPlus.DrawingRenderer/Svg/Options/SvgRenderOptions.cs b/src/EPPlus.DrawingRenderer/Svg/Options/SvgRenderOptions.cs index e0dc2457fe..ebd3a15794 100644 --- a/src/EPPlus.DrawingRenderer/Svg/Options/SvgRenderOptions.cs +++ b/src/EPPlus.DrawingRenderer/Svg/Options/SvgRenderOptions.cs @@ -8,7 +8,7 @@ This software is licensed under PolyForm Noncommercial License 1.0.0 ************************************************************************************************* Date Author Change ************************************************************************************************* - 01/27/2020 EPPlus Software AB Initial release EPPlus 5 + 23/11/2026 EPPlus Software AB EPPlus 9 *************************************************************************************************/ using OfficeOpenXml.Interfaces.Fonts; @@ -35,12 +35,23 @@ public class SvgRenderOptions public SvgSize SvgSize { get; } = new SvgSize(); /// - /// The render target used for text layout. Defaults to , which - /// substitutes fonts unlikely to be available to a browser, both when measuring and in the output. - /// Use when the fonts are made available to the consumer - /// by other means, e.g. embedded. + /// The render target used for text layout. Only has an effect when is + /// false. (the default) then substitutes fonts unlikely to be + /// available to a browser, both when measuring and in the output, e.g. Aptos Narrow with Calibri. + /// keeps the requested fonts, for when they are made + /// available to the consumer by other means. /// public FontRenderTarget FontTarget { get; set; } = FontRenderTarget.Web; + + /// + /// When true (the default), text is measured with the requested fonts (no web font + /// substitution) and the fonts are embedded in the svg as subsets that only hold the glyphs + /// used, so the output does not depend on the fonts the browser has. A font is only embedded + /// when its licence allows it, see IEpplusFontConfiguration.OnFontEmbedding; other fonts + /// are referenced by name. When false, no font is embedded and + /// decides whether fonts are substituted. + /// + public bool EmbedFonts { get; set; } = true; } } \ No newline at end of file diff --git a/src/EPPlus.DrawingRenderer/Svg/SvgFontPlan.cs b/src/EPPlus.DrawingRenderer/Svg/SvgFontPlan.cs new file mode 100644 index 0000000000..3b1c41df73 --- /dev/null +++ b/src/EPPlus.DrawingRenderer/Svg/SvgFontPlan.cs @@ -0,0 +1,349 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 23/11/2026 EPPlus Software AB EPPlus 9 + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Subsetting; +using OfficeOpenXml.Interfaces.Fonts; +using OfficeOpenXml.Interfaces.RichText; +using System.Globalization; +using System.Text; + +namespace EPPlus.DrawingRenderer.Svg +{ + /// + /// Decides the fonts of one svg: the CSS font-family stacks, and, when fonts are embedded, the + /// subsets declared with @font-face. + /// + /// The text of the svg is collected first (, , + /// ) and a decides the stacks, and the subsets + /// when fonts are embedded. A stack then starts with the subsets, e.g. + /// 'ABCDEF+Aptos Narrow', 'Aptos Narrow', 'Calibri', ..., sans-serif. + /// + /// When fonts are not embedded, a stack is the font measurement used, the glyph fallbacks it used + /// (each followed by its script's fallback chain), the measured family and its fallback chain + /// (user-configured, then built-in), and a generic family, e.g. + /// 'Calibri', 'Carlito', 'Liberation Sans', 'Arial', 'Helvetica', sans-serif. + /// The measured family is the family after web font substitution, so it is the family the + /// text was laid out for. Text measured with a glyph fallback that is written by name is split off + /// with a stack of its own (), whether fonts are embedded or not. + /// + /// A font that was not collected gets the measured family, its fallback chain and a generic family. + /// Without a render context only the family and sans-serif are written and nothing is embedded. + /// + /// One instance serves one svg and is not thread-safe. + /// + internal class SvgFontPlan + { + private readonly RenderContext? _renderContext; + private readonly bool _embedFonts; + private readonly Dictionary _stacks = new Dictionary(StringComparer.OrdinalIgnoreCase); + private WebFontSubsetPlanner? _planner; + private WebFontPlan? _webFontPlan; + + internal SvgFontPlan(RenderContext? renderContext) + : this(renderContext, false) + { + } + + /// The context the render items were measured with, or null. + /// Whether fonts are embedded as subsets. Has no effect without a render context. + internal SvgFontPlan(RenderContext? renderContext, bool embedFonts) + { + _renderContext = renderContext; + _embedFonts = embedFonts; + } + + /// + /// A plan without a render context: family and sans-serif only. + /// + internal static SvgFontPlan WithoutContext + { + get { return new SvgFontPlan(null); } + } + + // ----------------------------------------------------------------------------------------- + // Collecting the text of the svg + // ----------------------------------------------------------------------------------------- + + /// + /// Starts collecting the text of a new svg and discards the plan of a previous one. + /// + internal void BeginCollect() + { + _stacks.Clear(); + _webFontPlan = null; + _planner = _renderContext != null ? new WebFontSubsetPlanner(_renderContext.FontEngine, _embedFonts) : null; + } + + /// + /// Adds text measured with the font. A null or empty text only registers the font, so it + /// gets a stack (for instance a paragraph's default font). Ignored without a render context. + /// + internal void AddText(IFontFormatBase? font, string? text) + { + if (_planner == null || font == null || string.IsNullOrEmpty(font.Family)) + return; + _planner.AddText(font.Family, font.SubFamily, text); + } + + /// + /// Plans the stacks, and the subsets when fonts are embedded, for the collected text. Does + /// nothing without a render context. + /// + internal void Build() + { + if (_planner == null) + return; + _webFontPlan = _planner.Build(); + _planner = null; + _stacks.Clear(); + } + + // ----------------------------------------------------------------------------------------- + // Output + // ----------------------------------------------------------------------------------------- + + /// + /// Appends an @font-face rule for each embedded subset. Appends nothing when no font is embedded. + /// The caller writes the style element around the rules. + /// + internal void AppendFontFaceRules(StringBuilder sb) + { + if (_webFontPlan == null || _webFontPlan.Faces.Count == 0) + return; + + foreach (var face in _webFontPlan.Faces) + { + sb.Append("@font-face{font-family:"); + sb.Append(EscapeXml(QuoteFamilyName(face.FamilyName))); + sb.Append(";src:url(data:font/ttf;base64,"); + sb.Append(Convert.ToBase64String(face.FontData)); + sb.Append(") format('truetype');font-weight:"); + sb.Append(face.FontWeight.ToString(CultureInfo.InvariantCulture)); + sb.Append(";font-style:"); + sb.Append(face.IsItalic ? "italic" : "normal"); + sb.Append(";}"); + } + } + + /// + /// Returns the value of the font-family attribute for the font, escaped for use inside + /// a double-quoted xml attribute. + /// + internal string GetFontFamilyAttributeValue(IFontFormatBase? font) + { + if (font == null || string.IsNullOrEmpty(font.Family)) + return ToCss(GenericFontFamily.SansSerif); + + return GetFontFamilyAttributeValue(font.Family, font.SubFamily); + } + + /// + /// Returns the value of the font-family attribute for the family, escaped for use inside + /// a double-quoted xml attribute. + /// + internal string GetFontFamilyAttributeValue(string family, FontSubFamily subFamily) + { + if (string.IsNullOrEmpty(family)) + return ToCss(GenericFontFamily.SansSerif); + + var key = family + "|" + subFamily; + string stack; + if (_stacks.TryGetValue(key, out stack)) + return stack; + + IReadOnlyList? names = _webFontPlan != null ? _webFontPlan.GetFamilyNames(family, subFamily) : null; + stack = names != null + ? FormatStack(names, _webFontPlan!.GetGenericFamily(family, subFamily)) + : EscapeXml(BuildStack(family, subFamily)); + _stacks.Add(key, stack); + return stack; + } + + /// + /// Splits the text where the font-family stack changes, which happens when measurement routed + /// code points to a glyph fallback that is written by name (see + /// ). Returns null when the + /// whole text is drawn with the font's own stack, which is the normal case. + /// + internal List? GetFallbackSegments(IFontFormatBase? font, string? text) + { + if (_webFontPlan == null || font == null || string.IsNullOrEmpty(font.Family) || string.IsNullOrEmpty(text)) + return null; + + var fontStack = _webFontPlan.GetFamilyNames(font.Family, font.SubFamily); + if (fontStack == null) + return null; + + var segments = new List(); + IReadOnlyList? current = null; + int start = 0; + bool split = false; + + for (int i = 0; i < text!.Length;) + { + int length = char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]) ? 2 : 1; + int codePoint = length == 2 ? char.ConvertToUtf32(text[i], text[i + 1]) : text[i]; + + // Marks, variation selectors and joiners stay with the character before them. + IReadOnlyList stack = i > 0 && IsAttachedToPrevious(text, i, codePoint) + ? current! + : _webFontPlan.GetFamilyNames(font.Family, font.SubFamily, codePoint); + + if (i == 0) + { + current = stack; + } + else if (!ReferenceEquals(stack, current)) + { + segments.Add(CreateSegment(text.Substring(start, i - start), current!, fontStack, font)); + start = i; + current = stack; + split = true; + } + if (!ReferenceEquals(stack, fontStack)) + split = true; + + i += length; + } + + if (!split) + return null; + + segments.Add(CreateSegment(text.Substring(start), current!, fontStack, font)); + return segments; + } + + /// + /// The width of the text in points, measured as layout measured it. Null without a render + /// context or when the font cannot be measured. + /// + internal double? MeasureWidthInPoints(IFontFormatBase? font, string? text) + { + if (_renderContext == null || font == null || string.IsNullOrEmpty(font.Family) || string.IsNullOrEmpty(text)) + return null; + + // The family is already substituted for the target, so the engine is asked directly. + var shaper = _renderContext.FontEngine.GetMeasurementShaper(font.Family, font.SubFamily); + if (shaper == null) + return null; + return shaper.ShapeLight(text).GetWidthInPoints(font.Size); + } + + private SvgTextSegment CreateSegment(string text, IReadOnlyList stack, IReadOnlyList fontStack, IFontFormatBase font) + { + var fontFamily = ReferenceEquals(stack, fontStack) + ? null + : FormatStack(stack, _webFontPlan!.GetGenericFamily(font.Family, font.SubFamily)); + return new SvgTextSegment(text, fontFamily); + } + + private static bool IsAttachedToPrevious(string text, int index, int codePoint) + { + switch (CharUnicodeInfo.GetUnicodeCategory(text, index)) + { + case UnicodeCategory.NonSpacingMark: + case UnicodeCategory.SpacingCombiningMark: + case UnicodeCategory.EnclosingMark: + case UnicodeCategory.Format: + return true; + default: + // Emoji modifiers (skin tones) are symbols but belong to the emoji before them. + return codePoint >= 0x1F3FB && codePoint <= 0x1F3FF; + } + } + + private string BuildStack(string family, FontSubFamily subFamily) + { + var sb = new StringBuilder(); + sb.Append(QuoteFamilyName(family)); + + var generic = GenericFontFamily.SansSerif; + if (_renderContext != null) + { + var engine = _renderContext.FontEngine; + foreach (var fallback in engine.GetFallbackChain(family)) + { + sb.Append(", "); + sb.Append(QuoteFamilyName(fallback)); + } + generic = engine.GetGenericFamily(family, subFamily); + } + + sb.Append(", "); + sb.Append(ToCss(generic)); + return sb.ToString(); + } + + private static string FormatStack(IReadOnlyList names, GenericFontFamily generic) + { + var sb = new StringBuilder(); + foreach (var name in names) + { + sb.Append(QuoteFamilyName(name)); + sb.Append(", "); + } + sb.Append(ToCss(generic)); + return EscapeXml(sb.ToString()); + } + + /// + /// Quotes a family name as a CSS string. Quoting every name avoids the rules for unquoted + /// names, which reject names such as "Noto Sans 3" or names that are generic keywords. + /// + internal static string QuoteFamilyName(string name) + { + return "'" + name.Replace("\\", "\\\\").Replace("'", "\\'") + "'"; + } + + internal static string ToCss(GenericFontFamily generic) + { + switch (generic) + { + case GenericFontFamily.Serif: + return "serif"; + case GenericFontFamily.Monospace: + return "monospace"; + default: + return "sans-serif"; + } + } + + /// + /// Escapes a value for use in xml text or inside a double-quoted xml attribute. + /// + private static string EscapeXml(string value) + { + return value.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """); + } + } + + /// + /// A part of a text run that is drawn with its own font-family stack. + /// + internal sealed class SvgTextSegment + { + internal SvgTextSegment(string text, string? fontFamily) + { + Text = text; + FontFamily = fontFamily; + } + + /// The text of the segment. + internal string Text { get; private set; } + + /// + /// The font-family attribute value, escaped for a double-quoted xml attribute, or null when the + /// segment is drawn with the run's own stack. + /// + internal string? FontFamily { get; private set; } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/EPPlus.Fonts.OpenType.Tests.csproj b/src/EPPlus.Fonts.OpenType.Tests/EPPlus.Fonts.OpenType.Tests.csproj index 04f9c1a982..1ee3b0c49b 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/EPPlus.Fonts.OpenType.Tests.csproj +++ b/src/EPPlus.Fonts.OpenType.Tests/EPPlus.Fonts.OpenType.Tests.csproj @@ -32,6 +32,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest @@ -68,6 +71,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontResolver/FallbackChainTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontResolver/FallbackChainTests.cs new file mode 100644 index 0000000000..fc695de2ac --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/FontResolver/FallbackChainTests.cs @@ -0,0 +1,119 @@ +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Tests.FontResolver +{ + /// + /// Tests for : the user-configured chain + /// followed by the built-in chain, without duplicates, in resolution order. + /// + [TestClass] + public class FallbackChainTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private static OpenTypeFontEngine CreateEngine(Action? configure = null) + { + return new OpenTypeFontEngine(cfg => + { + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + }); + } + + [TestMethod] + public void BuiltinChain_AptosNarrow() + { + using (var engine = CreateEngine()) + { + CollectionAssert.AreEqual( + new[] { "Liberation Sans Narrow", "Arial Narrow", "Carlito", "Liberation Sans", "Arial" }, + engine.GetFallbackChain("Aptos Narrow")); + } + } + + [TestMethod] + public void BuiltinChain_LookupIsCaseInsensitive() + { + using (var engine = CreateEngine()) + { + CollectionAssert.AreEqual( + engine.GetFallbackChain("Calibri"), + engine.GetFallbackChain("cALIBRI")); + Assert.IsTrue(engine.GetFallbackChain("cALIBRI").Length > 0); + } + } + + [TestMethod] + public void UserChain_ComesBeforeBuiltinChain() + { + using (var engine = CreateEngine(cfg => cfg.FontFallbacks["Calibri"] = new[] { "Roboto", "Open Sans" })) + { + CollectionAssert.AreEqual( + new[] { "Roboto", "Open Sans", "Carlito", "Liberation Sans", "Arial", "Helvetica" }, + engine.GetFallbackChain("Calibri")); + } + } + + [TestMethod] + public void Duplicates_AreRemoved_FirstOccurrenceWins() + { + // "carlito" from the user chain wins over "Carlito" from the built-in chain, + // and the repeated "Roboto" in the user chain is dropped. + using (var engine = CreateEngine(cfg => cfg.FontFallbacks["Calibri"] = new[] { "Roboto", "carlito", "ROBOTO" })) + { + CollectionAssert.AreEqual( + new[] { "Roboto", "carlito", "Liberation Sans", "Arial", "Helvetica" }, + engine.GetFallbackChain("Calibri")); + } + } + + [TestMethod] + public void FontItself_IsNotInChain() + { + using (var engine = CreateEngine(cfg => cfg.FontFallbacks["Calibri"] = new[] { "calibri", "Roboto" })) + { + var chain = engine.GetFallbackChain("Calibri"); + Assert.IsFalse(chain.Any(n => string.Equals(n, "Calibri", StringComparison.OrdinalIgnoreCase))); + Assert.AreEqual("Roboto", chain[0]); + } + } + + [TestMethod] + public void EmptyNamesInUserChain_AreSkipped() + { + using (var engine = CreateEngine(cfg => cfg.FontFallbacks["My Font"] = new[] { "", null!, "Roboto" })) + { + CollectionAssert.AreEqual(new[] { "Roboto" }, engine.GetFallbackChain("My Font")); + } + } + + [TestMethod] + public void UnknownFont_GivesEmptyChain() + { + using (var engine = CreateEngine()) + { + Assert.AreEqual(0, engine.GetFallbackChain("No Such Font 123").Length); + } + } + + [TestMethod] + public void NullOrEmptyName_GivesEmptyChain() + { + using (var engine = CreateEngine()) + { + Assert.AreEqual(0, engine.GetFallbackChain(null!).Length); + Assert.AreEqual(0, engine.GetFallbackChain(string.Empty).Length); + } + } + + [TestMethod] + public void LastResortFont_IsNotInChain() + { + using (var engine = CreateEngine()) + { + Assert.IsFalse(engine.GetFallbackChain("Aptos Narrow") + .Any(n => string.Equals(n, "Archivo Narrow", StringComparison.OrdinalIgnoreCase))); + } + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontResolver/GenericFontFamilyTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontResolver/GenericFontFamilyTests.cs new file mode 100644 index 0000000000..ef9ca5d1cb --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/FontResolver/GenericFontFamilyTests.cs @@ -0,0 +1,182 @@ +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Tests.FontResolver +{ + /// + /// Tests for and the rules in + /// . + /// + [TestClass] + public class GenericFontFamilyTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + // ----------------------------------------------------------------------------------------- + // Test fonts + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Roboto_IsSansSerif() + { + RequireFont(TestFolderEngine, "Roboto"); + Assert.AreEqual(GenericFontFamily.SansSerif, TestFolderEngine.GetGenericFamily("Roboto")); + } + + [TestMethod] + public void BizUdGothic_FixedPitch_IsMonospace() + { + RequireFont(TestFolderEngine, "BIZ UDGothic"); + Assert.AreEqual(GenericFontFamily.Monospace, TestFolderEngine.GetGenericFamily("BIZ UDGothic")); + } + + /// + /// EB Garamond has serifs, but sets neither sFamilyClass nor PANOSE. Nothing in the font + /// says it is a serif font, so it is reported as sans-serif. Documents the limitation. + /// + [TestMethod] + public void EbGaramond_WithoutClassification_IsSansSerif() + { + RequireFont(TestFolderEngine, "EB Garamond"); + Assert.AreEqual(GenericFontFamily.SansSerif, TestFolderEngine.GetGenericFamily("EB Garamond")); + } + + [TestMethod] + public void NullOrEmptyName_IsSansSerif() + { + Assert.AreEqual(GenericFontFamily.SansSerif, TestFolderEngine.GetGenericFamily(null!)); + Assert.AreEqual(GenericFontFamily.SansSerif, TestFolderEngine.GetGenericFamily(string.Empty)); + } + + // ----------------------------------------------------------------------------------------- + // System fonts (Inconclusive where not installed) + // ----------------------------------------------------------------------------------------- + + [TestMethod] + [DataRow("Calibri", GenericFontFamily.SansSerif)] + [DataRow("Arial", GenericFontFamily.SansSerif)] + [DataRow("Cambria", GenericFontFamily.Serif)] + [DataRow("Times New Roman", GenericFontFamily.Serif)] + [DataRow("Georgia", GenericFontFamily.Serif)] + [DataRow("Consolas", GenericFontFamily.Monospace)] + [DataRow("Courier New", GenericFontFamily.Monospace)] + public void SystemFont(string family, GenericFontFamily expected) + { + RequireFont(SystemFontsEngine, family); + Assert.AreEqual(expected, SystemFontsEngine.GetGenericFamily(family)); + } + + // ----------------------------------------------------------------------------------------- + // Classifier rules, on a private copy of Roboto with the relevant fields changed + // ----------------------------------------------------------------------------------------- + + private static OpenTypeFont LoadPrivateRoboto() + { + RequireFont(TestFolderEngine, "Roboto"); + // ignoreCache: the fields are changed below and must not leak into the shared engine. + var font = TestFolderEngine.LoadFont("Roboto", FontSubFamily.Regular, ignoreCache: true); + font.PostTable.isFixedPitch = 0; + font.Os2Table.sFamilyClass = 0; + font.Os2Table.panose = new byte[10]; + return font; + } + + [TestMethod] + public void Classifier_NothingSet_IsSansSerif() + { + Assert.AreEqual(GenericFontFamily.SansSerif, GenericFontFamilyClassifier.Classify(LoadPrivateRoboto())); + } + + [TestMethod] + public void Classifier_IsFixedPitch_IsMonospace_EvenWithSerifClass() + { + var font = LoadPrivateRoboto(); + font.PostTable.isFixedPitch = 1; + font.Os2Table.sFamilyClass = 0x0105; + Assert.AreEqual(GenericFontFamily.Monospace, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + [DataRow(1)] + [DataRow(2)] + [DataRow(3)] + [DataRow(4)] + [DataRow(5)] + [DataRow(7)] + public void Classifier_SerifFamilyClass_IsSerif(int familyClass) + { + var font = LoadPrivateRoboto(); + font.Os2Table.sFamilyClass = (short)((familyClass << 8) | 0x03); + Assert.AreEqual(GenericFontFamily.Serif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + [DataRow(8)] // sans serif + [DataRow(9)] // ornamentals + [DataRow(10)] // scripts + [DataRow(12)] // symbolic + public void Classifier_OtherFamilyClass_IsSansSerif(int familyClass) + { + var font = LoadPrivateRoboto(); + font.Os2Table.sFamilyClass = (short)(familyClass << 8); + Assert.AreEqual(GenericFontFamily.SansSerif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + public void Classifier_SerifFamilyClass_WinsOverSansPanose() + { + var font = LoadPrivateRoboto(); + font.Os2Table.sFamilyClass = 1 << 8; // oldstyle serifs + font.Os2Table.panose = new byte[] { 2, 11, 0, 0, 0, 0, 0, 0, 0, 0 }; // panose says sans + Assert.AreEqual(GenericFontFamily.Serif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + public void Classifier_NonSerifFamilyClass_FallsThroughToPanose() + { + // Only classes 1-7 decide. Any other class leaves the decision to PANOSE. + var font = LoadPrivateRoboto(); + font.Os2Table.sFamilyClass = 8 << 8; // sans serif class + font.Os2Table.panose = new byte[] { 2, 2, 0, 0, 0, 0, 0, 0, 0, 0 }; // panose says serif + Assert.AreEqual(GenericFontFamily.Serif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + [DataRow((byte)2)] + [DataRow((byte)6)] + [DataRow((byte)10)] + public void Classifier_PanoseSerifStyle_IsSerif(byte serifStyle) + { + var font = LoadPrivateRoboto(); + font.Os2Table.panose = new byte[] { 2, serifStyle, 0, 0, 0, 0, 0, 0, 0, 0 }; + Assert.AreEqual(GenericFontFamily.Serif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + [DataRow((byte)0)] // any + [DataRow((byte)1)] // no fit + [DataRow((byte)11)] // normal sans + [DataRow((byte)15)] // rounded + public void Classifier_PanoseOtherSerifStyle_IsSansSerif(byte serifStyle) + { + var font = LoadPrivateRoboto(); + font.Os2Table.panose = new byte[] { 2, serifStyle, 0, 0, 0, 0, 0, 0, 0, 0 }; + Assert.AreEqual(GenericFontFamily.SansSerif, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + public void Classifier_PanoseMonospacedProportion_IsMonospace() + { + var font = LoadPrivateRoboto(); + font.Os2Table.panose = new byte[] { 2, 11, 0, 9, 0, 0, 0, 0, 0, 0 }; + Assert.AreEqual(GenericFontFamily.Monospace, GenericFontFamilyClassifier.Classify(font)); + } + + [TestMethod] + public void Classifier_PanoseNotLatinText_IsIgnored() + { + var font = LoadPrivateRoboto(); + font.Os2Table.panose = new byte[] { 3, 2, 0, 9, 0, 0, 0, 0, 0, 0 }; // family type 3 = script + Assert.AreEqual(GenericFontFamily.SansSerif, GenericFontFamilyClassifier.Classify(font)); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Fonts/Mulish-Regular-GsubExtension.ttf b/src/EPPlus.Fonts.OpenType.Tests/Fonts/Mulish-Regular-GsubExtension.ttf new file mode 100644 index 0000000000..61fd48de16 Binary files /dev/null and b/src/EPPlus.Fonts.OpenType.Tests/Fonts/Mulish-Regular-GsubExtension.ttf differ diff --git a/src/EPPlus.Fonts.OpenType.Tests/Helpers/FontTestHelper.cs b/src/EPPlus.Fonts.OpenType.Tests/Helpers/FontTestHelper.cs index 2346762a69..e45d307be9 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Helpers/FontTestHelper.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Helpers/FontTestHelper.cs @@ -1,4 +1,7 @@ using EPPlus.Fonts.OpenType.FontValidation; +using EPPlus.Fonts.OpenType.Tables; +using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; +using EPPlus.Fonts.OpenType.Tables.Gsub; using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups; using OfficeOpenXml.Interfaces.Fonts; using System; @@ -210,5 +213,93 @@ public static void SaveFontForInspection( File.WriteAllBytes(tempPath, bytes); Console.WriteLine($"Font saved to: {tempPath}"); } + + /// + /// Asserts that every lookup index referenced by the GSUB table is within the bounds of + /// its LookupList: indices from features, and from SubstLookupRecords in contextual + /// subtables, including subtables wrapped in Extension lookups. + /// + internal static void AssertGsubLookupIndicesValid(OpenTypeFont font) + { + GsubTable gsub = font.GsubTable; + if (gsub == null || gsub.LookupList == null) return; + + int lookupCount = gsub.LookupList.Lookups.Count; + List errors = new List(); + + if (gsub.FeatureList != null) + { + for (int f = 0; f < gsub.FeatureList.FeatureRecords.Count; f++) + { + // ASSUMPTION: property names on FeatureRecord/FeatureTable - adjust if they differ + var featureRecord = gsub.FeatureList.FeatureRecords[f]; + foreach (ushort lookupIndex in featureRecord.FeatureTable.LookupListIndices) + { + if (lookupIndex >= lookupCount) + { + errors.Add(string.Format("Feature {0} ('{1}') references lookup {2}, lookup count is {3}", + f, featureRecord.FeatureTag, lookupIndex, lookupCount)); + } + } + } + } + + for (int l = 0; l < lookupCount; l++) + { + LookupTable lookup = gsub.LookupList.Lookups[l]; + for (int s = 0; s < lookup.SubTables.Count; s++) + { + FontTableElement subTable = lookup.SubTables[s]; + ExtensionSubTableBase extension = subTable as ExtensionSubTableBase; + if (extension != null) + { + subTable = extension.ExtendedSubTable; + } + + ChainingContextualSubstFormat3 chainContext = subTable as ChainingContextualSubstFormat3; + if (chainContext == null) continue; + + foreach (SubstLookupRecord record in chainContext.SubstLookupRecords) + { + if (record.LookupListIndex >= lookupCount) + { + errors.Add(string.Format("Lookup {0} (type {1}), subtable {2}: SubstLookupRecord references lookup {3}, lookup count is {4}", + l, lookup.LookupType, s, record.LookupListIndex, lookupCount)); + } + } + } + } + + foreach (string error in errors) + { + Console.WriteLine(error); + } + Assert.AreEqual(0, errors.Count, "Invalid GSUB lookup indices:" + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray())); + } + + /// + /// Finds a table in a serialized font's table directory and returns its offset and length. + /// Reads the bytes directly so tests do not depend on the font model. + /// + public static void FindTableInDirectory(byte[] fontBytes, string tag, out int offset, out int length) + { + int numTables = (fontBytes[4] << 8) | fontBytes[5]; + for (int i = 0; i < numTables; i++) + { + int recordStart = 12 + i * 16; + if (System.Text.Encoding.ASCII.GetString(fontBytes, recordStart, 4) == tag) + { + offset = ReadInt32BigEndian(fontBytes, recordStart + 8); + length = ReadInt32BigEndian(fontBytes, recordStart + 12); + return; + } + } + throw new AssertFailedException("Table " + tag + " not found"); + } + + private static int ReadInt32BigEndian(byte[] bytes, int index) + { + return (bytes[index] << 24) | (bytes[index + 1] << 16) | (bytes[index + 2] << 8) | bytes[index + 3]; + } } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Serialization/CoreTableSerializationTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Serialization/CoreTableSerializationTests.cs index ac401899b8..de858d44ce 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Serialization/CoreTableSerializationTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Serialization/CoreTableSerializationTests.cs @@ -81,8 +81,8 @@ public void SerializeNameTable() [TestMethod] [DataRow("Roboto", FontSubFamily.Regular, 96)] [DataRow("Roboto", FontSubFamily.Italic, 96)] - [DataRow("EB Garamond", FontSubFamily.Regular, 100)] - [DataRow("Mulish", FontSubFamily.Regular, 100)] + [DataRow("EB Garamond", FontSubFamily.Regular, 96)] + [DataRow("Mulish", FontSubFamily.Regular, 96)] public void SerializeOs2Table(string fontName, FontSubFamily subFamily, int expectedLength) { var ffi = FontScannerV2.FindBestMatch(FontFolder, fontName, subFamily); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/BasicSubsettingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/BasicSubsettingTests.cs index 3b487aae8e..7c189ab722 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/BasicSubsettingTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/BasicSubsettingTests.cs @@ -37,7 +37,7 @@ public void Subset_Abc_RoundtripValidation() SaveFontForCurrentTest(parsedFont); - Assert.AreEqual(12, parsedFont.TableRecords.Count); + Assert.AreEqual(16, parsedFont.TableRecords.Count); Assert.IsTrue(parsedFont.TableRecords.ContainsKey("head")); Assert.IsTrue(parsedFont.TableRecords.ContainsKey("name")); Assert.IsTrue(parsedFont.TableRecords.ContainsKey("maxp")); @@ -50,6 +50,10 @@ public void Subset_Abc_RoundtripValidation() Assert.IsTrue(parsedFont.TableRecords.ContainsKey("OS/2")); Assert.IsTrue(parsedFont.TableRecords.ContainsKey("GSUB")); Assert.IsTrue(parsedFont.TableRecords.ContainsKey("GPOS")); + Assert.IsTrue(parsedFont.TableRecords.ContainsKey("cvt ")); + Assert.IsTrue(parsedFont.TableRecords.ContainsKey("fpgm")); + Assert.IsTrue(parsedFont.TableRecords.ContainsKey("prep")); + Assert.IsTrue(parsedFont.TableRecords.ContainsKey("gasp")); FontTestHelper.AssertFontValid(parsedFont); diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/FontEmbeddingPolicyTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/FontEmbeddingPolicyTests.cs index f9447ba6f3..8d4b0c61f5 100644 --- a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/FontEmbeddingPolicyTests.cs +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/FontEmbeddingPolicyTests.cs @@ -226,5 +226,7 @@ public void Build_SkippedFont_FallsBackToTaggedLastResortSubset() Assert.IsTrue(embedded.Font.FullName.Contains("Archivo"), embedded.Font.FullName); Assert.IsNotNull(builder.GetShapingProvider("Roboto", FontSubFamily.Regular)); } + + } } diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutLookupIndexTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutLookupIndexTests.cs new file mode 100644 index 0000000000..8a8106df4a --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/LayoutLookupIndexTests.cs @@ -0,0 +1,96 @@ +using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups; +using EPPlus.Fonts.OpenType.Tests.Helpers; +using System.IO; +using System.Text; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + [TestClass] + public class LayoutLookupIndexTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + [TestMethod] + [DataRow("Mulish-Regular.ttf")] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("CrimsonText-Regular.ttf")] + public void Subset_GsubLookupIndices_AreWithinLookupList(string fileName) + { + var font = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName))); + + // Control: the original font must pass, otherwise the loader is at fault, not the subsetter + FontTestHelper.AssertGsubLookupIndicesValid(font); + + var subsetFont = font.CreateSubset("Hello World 123"); + + // Serialize and reload so the assertion checks what OTS and browsers will read + var bytes = new OpenTypeFontSerializer(subsetFont).Serialize(); + var parsedFont = new OpenTypeFont(bytes); + + SaveFontForCurrentTest(parsedFont, Path.GetFileNameWithoutExtension(fileName)); + + FontTestHelper.AssertGsubLookupIndicesValid(parsedFont); + } + + [TestMethod] + public void Subset_GsubExtensionFont_MatchesPlainFont() + { + var plainFont = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, "Mulish-Regular.ttf"))); + var extensionFont = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, "Mulish-Regular-GsubExtension.ttf"))); + + // Precondition: the test font must actually use Extension lookups + Assert.IsTrue(FontTestHelper.HasGsubLookupType(extensionFont, 7), "Test font should contain GSUB Extension lookups"); + + const string text = "Hello World 123"; + var plainSubset = new OpenTypeFont(new OpenTypeFontSerializer(plainFont.CreateSubset(text)).Serialize()); + var extensionSubset = new OpenTypeFont(new OpenTypeFontSerializer(extensionFont.CreateSubset(text)).Serialize()); + + SaveFontForCurrentTest(extensionSubset); + + Assert.IsNotNull(extensionSubset.GsubTable, "GSUB should survive subsetting of a font with Extension lookups"); + + // Discovery through Extension must find the same glyphs + Assert.AreEqual(plainSubset.MaxpTable.numGlyphs, extensionSubset.MaxpTable.numGlyphs, "Glyph count differs"); + + // Extension lookups are written with their inner type, so the result must be identical + var expected = DescribeGsubLookups(plainSubset); + var actual = DescribeGsubLookups(extensionSubset); + + Console.WriteLine("Plain subset:"); + expected.ForEach(Console.WriteLine); + Console.WriteLine("Extension subset:"); + actual.ForEach(Console.WriteLine); + + CollectionAssert.AreEqual(expected, actual, "GSUB of the Extension subset differs from the plain subset"); + + FontTestHelper.AssertGsubLookupIndicesValid(extensionSubset); + } + + /// + /// Describes each GSUB lookup by type, subtable count and, for chaining contextual + /// subtables, their lookup records, so two fonts' lookup lists can be compared. + /// + private static List DescribeGsubLookups(OpenTypeFont font) + { + var result = new List(); + foreach (var lookup in font.GsubTable.LookupList.Lookups) + { + var sb = new StringBuilder(); + sb.Append("type ").Append(lookup.LookupType).Append(", subtables ").Append(lookup.SubTables.Count); + foreach (var subTable in lookup.SubTables) + { + if (subTable is ChainingContextualSubstFormat3 chain) + { + sb.Append(" -> [") + .Append(string.Join(", ", chain.SubstLookupRecords.Select(r => r.SequenceIndex + ":" + r.LookupListIndex).ToArray())) + .Append("]"); + } + } + result.Add(sb.ToString()); + } + return result; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/OtsSubsetMatrixTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/OtsSubsetMatrixTests.cs new file mode 100644 index 0000000000..77d920a7a7 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/OtsSubsetMatrixTests.cs @@ -0,0 +1,75 @@ +using EPPlus.Fonts.OpenType.Tests.Helpers; +using System.IO; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Generates subsets with demanding typography, for validation with OpenType Sanitizer (OTS). + /// The saved fonts are checked externally with "python -m ots in.ttf out.ttf". + /// + [TestClass] + public class OtsSubsetMatrixTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + // Each line targets a specific part of the subsetter + private const string ChallengingText = + "office affluent final ffi ffl fj " + // GSUB ligatures + "AVATAR Wave To Yo LT P. F. W. " + // GPOS kerning (PairPos format 1 and 2) + "Åsa Öberg äter smörgåsar på Café Résumé, naïve façade ñ " + // precomposed diacritics, composite glyphs + "e\u0301 a\u0308 o\u0302\u0301 n\u0303 " + // combining marks (MarkToBase, MarkToMark) + "Tiếng Việt: Phở, đường, ổn định " + // stacked diacritics + "½ ¼ € 1 234,56 −12 % ‰ № “citat” ‘enkel’ – — … • " + // figures and punctuation + "Ελληνικά Кириллица " + // Greek and Cyrillic + "\u2764\uFE0F \U0001F600 \U0001D400"; // variation selector, emoji, math bold A (cmap 12/14) + + [TestMethod] + [DataRow("Mulish-Regular.ttf")] + [DataRow("Mulish-Regular-GsubExtension.ttf")] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("CrimsonText-Regular.ttf")] + public void OtsMatrix_TestFolderFonts(string fileName) + { + CreateAndSaveSubset(Path.Combine(FontFolder, fileName)); + } + + [TestMethod] + [DataRow("calibri.ttf")] + [DataRow("arial.ttf")] + [DataRow("times.ttf")] + [DataRow("segoeui.ttf")] + [DataRow("georgia.ttf")] + [DataRow("seguisym.ttf")] + public void OtsMatrix_SystemFonts(string fileName) + { + string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), fileName); + if (!File.Exists(path)) + { + Assert.Inconclusive(fileName + " is not installed on this machine"); + } + CreateAndSaveSubset(path); + } + + private void CreateAndSaveSubset(string fontPath) + { + var font = new OpenTypeFont(File.ReadAllBytes(fontPath)); + var subsetFont = font.CreateSubset(ChallengingText); + + var bytes = new OpenTypeFontSerializer(subsetFont).Serialize(); + var parsedFont = new OpenTypeFont(bytes); + + // Save before asserting, so the file is available for OTS even if an assert fails + SaveFontForCurrentTest(parsedFont, Path.GetFileNameWithoutExtension(fontPath)); + + Console.WriteLine("Glyphs: " + parsedFont.MaxpTable.numGlyphs); + Console.WriteLine("Tables: " + string.Join(", ", parsedFont.TableRecords.Keys.ToArray())); + Console.WriteLine("GSUB lookup types: " + string.Join(", ", + FontTestHelper.GetGsubLookupTypes(parsedFont).Select(t => t.ToString()).ToArray())); + + FontTestHelper.AssertGsubLookupIndicesValid(parsedFont); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PassThroughTableSubsetProcessorTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PassThroughTableSubsetProcessorTests.cs new file mode 100644 index 0000000000..80ad45b87a --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PassThroughTableSubsetProcessorTests.cs @@ -0,0 +1,296 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/17/2026 EPPlus Software AB Pass-through hinting table subsetting tests + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.FontValidation; +using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Tables; +using EPPlus.Fonts.OpenType.Tables.Glyph; +using EPPlus.Fonts.OpenType.Tests.Helpers; +using EPPlus.Fonts.OpenType.Utils; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + [TestClass] + public class PassThroughTableSubsetProcessorTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private static readonly string[] PassThroughTags = { "cvt ", "fpgm", "prep", "gasp" }; + + private const string SubsetText = "Hello World 123"; + + /// + /// Loads a fresh, uncached font instance directly from the test font folder. + /// + private static OpenTypeFont LoadFontFile(string fileName) + { + var path = Path.Combine(FontFolder, fileName); + if (!File.Exists(path)) + Assert.Inconclusive("Test font not found: " + path); + return new OpenTypeFont(File.ReadAllBytes(path)); + } + + private static byte[] PadTo4(byte[] data) + { + var padded = (byte[])data.Clone(); + int paddedLen = (padded.Length + 3) & ~3; + if (paddedLen > padded.Length) + Array.Resize(ref padded, paddedLen); + return padded; + } + + [TestMethod] + public void PassThroughTags_AreFourCharactersLong() + { + Assert.AreEqual("cvt ", EPPlus.Fonts.OpenType.Tables.TableNames.Cvt); + Assert.AreEqual(4, EPPlus.Fonts.OpenType.Tables.TableNames.Fpgm.Length); + Assert.AreEqual(4, EPPlus.Fonts.OpenType.Tables.TableNames.Prep.Length); + Assert.AreEqual(4, EPPlus.Fonts.OpenType.Tables.TableNames.Gasp.Length); + } + + /// + /// Exploratory test: lists which hinting-related tables each bundled test font contains. + /// + [TestMethod] + public void Probe_ListHintingTablesInTestFonts() + { + foreach (var folder in FontFolders) + { + if (!Directory.Exists(folder)) + continue; + + foreach (var file in Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories)) + { + var ext = Path.GetExtension(file).ToLowerInvariant(); + if (ext != ".ttf" && ext != ".otf") + continue; + + try + { + var font = new OpenTypeFont(File.ReadAllBytes(file)); + var present = PassThroughTags + .Select(t => font.TableRecords.ContainsKey(t) ? t.Trim() : "-"); + Console.WriteLine($"{Path.GetFileName(file),-50} {font.Format,-4} {string.Join(" ", present)}"); + } + catch (Exception ex) + { + Console.WriteLine($"{Path.GetFileName(file),-50} ERROR: {ex.Message}"); + } + } + } + } + + // Test case 1: all four tables are present in the original and copied byte-identical. + [TestMethod] + [DataRow("Roboto-Regular.ttf")] // Verify with the probe output + [DataRow("OpenSans-Regular.ttf")] + public void Subset_FontWithHintingTables_CopiesTablesByteIdentical(string fileName) + { + var font = LoadFontFile(fileName); + foreach (var tag in PassThroughTags) + { + Assert.IsTrue(font.TableRecords.ContainsKey(tag), + $"Precondition: {fileName} should contain '{tag}'."); + } + + var subset = font.CreateSubset(SubsetText); + + foreach (var tag in PassThroughTags) + { + Assert.IsTrue(subset.TableRecords.ContainsKey(tag), + $"Subset should contain '{tag}'. Subset tables: [{string.Join(", ", subset.TableRecords.Keys.Select(k => "'" + k + "'").ToArray())}]"); + CollectionAssert.AreEqual(font.GetTableData(tag), subset.GetTableData(tag), + $"'{tag}' should be byte-identical to the original."); + } + } + + // Test case 2: tables missing in the original are missing in the subset too. + [TestMethod] + [DataRow("Mulish-Regular.ttf")] // prep + gasp only + [DataRow("NotoEmoji-Regular.ttf")] // gasp only + public void Subset_FontMissingHintingTables_DoesNotAddThem(string fileName) + { + var font = LoadFontFile(fileName); + Assert.IsTrue(PassThroughTags.Any(t => !font.TableRecords.ContainsKey(t)), + $"Precondition: {fileName} should lack at least one of the pass-through tables."); + + var subset = font.CreateSubset(SubsetText); + + foreach (var tag in PassThroughTags) + { + Assert.AreEqual(font.TableRecords.ContainsKey(tag), subset.TableRecords.ContainsKey(tag), + $"Presence of '{tag}' in subset should match the original."); + } + } + + [TestMethod] + public void Subset_TableDirectory_IsSortedOrdinal() + { + var bytes = LoadFontFile("Roboto-Regular.ttf").CreateSubset(SubsetText).Serialize(); + int numTables = (bytes[4] << 8) | bytes[5]; + var tags = new List(); + for (int i = 0; i < numTables; i++) + tags.Add(System.Text.Encoding.ASCII.GetString(bytes, 12 + i * 16, 4)); + + var expected = tags.OrderBy(t => t, StringComparer.Ordinal).ToList(); + CollectionAssert.AreEqual(expected, tags, "Table directory must be sorted by tag in ordinal (binary) order."); + } + + + // Test case 3: serialize, re-parse, verify bytes and checksums. + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("Mulish-Regular.ttf")] + public void Subset_WithHintingTables_RoundtripPreservesTablesAndChecksums(string fileName) + { + var font = LoadFontFile(fileName); + var subset = font.CreateSubset(SubsetText); + + var parsed = new OpenTypeFont(subset.Serialize()); + SaveFontForCurrentTest(parsed, Path.GetFileNameWithoutExtension(fileName)); + + foreach (var tag in PassThroughTags) + { + if (!font.TableRecords.ContainsKey(tag)) + continue; + + Assert.IsTrue(parsed.TableRecords.ContainsKey(tag), $"Parsed subset should contain '{tag}'."); + + var originalData = font.GetTableData(tag); + CollectionAssert.AreEqual(originalData, parsed.GetTableData(tag), + $"'{tag}' should survive the roundtrip byte-identical."); + + var expectedChecksum = ChecksumCalculator.CalculateTableChecksum(PadTo4(originalData), tag); + Assert.AreEqual(expectedChecksum, parsed.TableRecords[tag].Checksum, + $"Checksum for '{tag}' is incorrect."); + } + + FontTestHelper.AssertFontValid(parsed, FontValidationSeverity.Warning); + } + + // Test case 4: maxp hinting limits must match the copied fpgm/prep/cvt. + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + public void Subset_WithHintingTables_PreservesMaxpHintingLimits(string fileName) + { + var font = LoadFontFile(fileName); + var parsed = new OpenTypeFont(font.CreateSubset(SubsetText).Serialize()); + + var o = font.MaxpTable; + var s = parsed.MaxpTable; + Assert.AreEqual(o.maxZones, s.maxZones, "maxZones"); + Assert.AreEqual(o.maxTwilightPoints, s.maxTwilightPoints, "maxTwilightPoints"); + Assert.AreEqual(o.maxStorage, s.maxStorage, "maxStorage"); + Assert.AreEqual(o.maxFunctionDefs, s.maxFunctionDefs, "maxFunctionDefs"); + Assert.AreEqual(o.maxInstructionDefs, s.maxInstructionDefs, "maxInstructionDefs"); + Assert.AreEqual(o.maxStackElements, s.maxStackElements, "maxStackElements"); + // maxSizeOfInstructions may legitimately shrink if computed over the subset glyphs, + // but must never be smaller than the largest instruction block actually kept. + Assert.IsTrue(s.maxSizeOfInstructions > 0 || o.maxSizeOfInstructions == 0, "maxSizeOfInstructions"); + } + + private static readonly string[] HintingProgramTags = { TableNames.Cvt, TableNames.Fpgm, TableNames.Prep }; + + // Accented letters are composite glyphs in many fonts, so composites are covered too. + private const string UnhintedSubsetText = "Hello Héllo Åäö ñ 123"; + + private static OpenTypeFont CreateUnhintedSubset(OpenTypeFont font) + { + var subset = font.CreateSubset(UnhintedSubsetText, new SubsetOptions { RemoveHinting = true }); + return new OpenTypeFont(subset.Serialize()); + } + + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + public void Subset_RemoveHinting_LeavesOutHintingTablesAndKeepsGasp(string fileName) + { + var font = LoadFontFile(fileName); + var parsed = CreateUnhintedSubset(font); + + foreach (var tag in HintingProgramTags) + { + Assert.IsFalse(parsed.TableRecords.ContainsKey(tag), $"'{tag}' should be left out of an unhinted subset."); + } + Assert.AreEqual(font.TableRecords.ContainsKey(TableNames.Gasp), parsed.TableRecords.ContainsKey(TableNames.Gasp), + "gasp is kept when the original has it."); + } + + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + public void Subset_RemoveHinting_GlyphsHaveNoInstructions(string fileName) + { + var font = LoadFontFile(fileName); + var parsed = CreateUnhintedSubset(font); + + int simpleCount = 0, compositeCount = 0; + for (ushort gid = 0; gid < parsed.MaxpTable.numGlyphs; gid++) + { + var glyph = parsed.GlyfTable.GetGlyph(gid); + if (glyph == null) + continue; + + if (glyph.SimpleData != null) + { + simpleCount++; + Assert.AreEqual(0, glyph.SimpleData.Instructions.Length, $"Simple glyph {gid} has instructions."); + } + if (glyph.CompositeData != null) + { + compositeCount++; + Assert.AreEqual(0, glyph.CompositeData.Instructions.Length, $"Composite glyph {gid} has instructions."); + foreach (var component in glyph.CompositeData.Components) + { + Assert.AreEqual((CompositeGlyphFlags)0, component.Flags & CompositeGlyphFlags.WE_HAVE_INSTRUCTIONS, + $"Composite glyph {gid} has a component with WE_HAVE_INSTRUCTIONS."); + } + } + } + + Assert.IsTrue(simpleCount > 0, "The subset has no simple glyphs."); + Console.WriteLine($"{fileName}: {simpleCount} simple and {compositeCount} composite glyphs checked."); + } + + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + public void Subset_RemoveHinting_MaxpReservesNothingForInstructions(string fileName) + { + var maxp = CreateUnhintedSubset(LoadFontFile(fileName)).MaxpTable; + + Assert.AreEqual(1, maxp.maxZones, "maxZones"); + Assert.AreEqual(0, maxp.maxTwilightPoints, "maxTwilightPoints"); + Assert.AreEqual(0, maxp.maxStorage, "maxStorage"); + Assert.AreEqual(0, maxp.maxFunctionDefs, "maxFunctionDefs"); + Assert.AreEqual(0, maxp.maxInstructionDefs, "maxInstructionDefs"); + Assert.AreEqual(0, maxp.maxStackElements, "maxStackElements"); + Assert.AreEqual(0, maxp.maxSizeOfInstructions, "maxSizeOfInstructions"); + } + + [TestMethod] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + [DataRow("Mulish-Regular.ttf")] + public void Subset_RemoveHinting_IsValidAndSmallerThanHinted(string fileName) + { + var font = LoadFontFile(fileName); + var hinted = font.CreateSubset(UnhintedSubsetText, new SubsetOptions()).Serialize(); + var unhinted = font.CreateSubset(UnhintedSubsetText, new SubsetOptions { RemoveHinting = true }).Serialize(); + + FontTestHelper.AssertFontValid(new OpenTypeFont(unhinted), FontValidationSeverity.Warning); + Assert.IsTrue(unhinted.Length < hinted.Length, + $"Unhinted {unhinted.Length} bytes, hinted {hinted.Length} bytes."); + Console.WriteLine($"{fileName}: hinted {hinted.Length} bytes, unhinted {unhinted.Length} bytes."); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebEmbeddingPolicyTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebEmbeddingPolicyTests.cs new file mode 100644 index 0000000000..dfa0615c97 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebEmbeddingPolicyTests.cs @@ -0,0 +1,369 @@ +using EPPlus.Fonts.OpenType.Tables.Os2; +using EPPlus.Fonts.OpenType.Tests.Tables; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + [TestClass] + public class WebEmbeddingPolicyTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + private static OpenTypeFontEngine CreateEngineWithCallback( + Func callback) + { + return new OpenTypeFontEngine(cfg => + { + foreach (var folder in FontFolders) + cfg.FontDirectories.Add(folder); + cfg.SearchSystemDirectories = false; + cfg.OnFontEmbedding(callback); + }); + } + + // ---- Level 1b: GetEmbeddingPermission / IsBitmapEmbeddingOnly (pure fsType interpretation) ---- + + [TestMethod] + [DataRow(FsTypeFlags.Installable, FontEmbeddingPermission.Installable)] + [DataRow(FsTypeFlags.RestrictedLicense, FontEmbeddingPermission.RestrictedLicense)] + [DataRow(FsTypeFlags.PreviewPrint, FontEmbeddingPermission.PreviewAndPrint)] + [DataRow(FsTypeFlags.Editable, FontEmbeddingPermission.Editable)] + public void GetEmbeddingPermission_SingleUsageBit_ReturnsMatchingPermission( + FsTypeFlags fsType, FontEmbeddingPermission expected) + { + var os2 = new Os2Table { fsType = fsType }; + Assert.AreEqual(expected, os2.GetEmbeddingPermission()); + } + + [TestMethod] + [DataRow(FsTypeFlags.RestrictedLicense | FsTypeFlags.PreviewPrint, FontEmbeddingPermission.PreviewAndPrint)] + [DataRow(FsTypeFlags.RestrictedLicense | FsTypeFlags.Editable, FontEmbeddingPermission.Editable)] + [DataRow(FsTypeFlags.PreviewPrint | FsTypeFlags.Editable, FontEmbeddingPermission.Editable)] + [DataRow(FsTypeFlags.RestrictedLicense | FsTypeFlags.PreviewPrint | FsTypeFlags.Editable, FontEmbeddingPermission.Editable)] + public void GetEmbeddingPermission_SeveralUsageBits_LeastRestrictiveWins( + FsTypeFlags fsType, FontEmbeddingPermission expected) + { + var os2 = new Os2Table { fsType = fsType }; + Assert.AreEqual(expected, os2.GetEmbeddingPermission()); + } + + [TestMethod] + [DataRow(FsTypeFlags.NoSubsetting | FsTypeFlags.BitmapEmbeddingOnly, FontEmbeddingPermission.Installable)] + [DataRow(FsTypeFlags.PreviewPrint | FsTypeFlags.NoSubsetting | FsTypeFlags.BitmapEmbeddingOnly, FontEmbeddingPermission.PreviewAndPrint)] + public void GetEmbeddingPermission_HighBits_DoNotAffectUsageLevel( + FsTypeFlags fsType, FontEmbeddingPermission expected) + { + var os2 = new Os2Table { fsType = fsType }; + Assert.AreEqual(expected, os2.GetEmbeddingPermission()); + } + + [TestMethod] + [DataRow(FsTypeFlags.BitmapEmbeddingOnly, true)] + [DataRow(FsTypeFlags.BitmapEmbeddingOnly | FsTypeFlags.Editable, true)] + [DataRow(FsTypeFlags.NoSubsetting, false)] + [DataRow(FsTypeFlags.Installable, false)] + public void IsBitmapEmbeddingOnly_ReflectsBit9(FsTypeFlags fsType, bool expected) + { + var os2 = new Os2Table { fsType = fsType }; + Assert.AreEqual(expected, os2.IsBitmapEmbeddingOnly()); + } + + // ---- Level 2b: web default policy (no callback) ---- + + [TestMethod] + [DataRow(FsTypeFlags.Installable)] + [DataRow(FsTypeFlags.Editable)] + public void ResolveEmbeddingDecision_Web_PermissiveFsType_ReturnsSubset(FsTypeFlags fsType) + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = fsType; + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + [DataRow(FsTypeFlags.RestrictedLicense)] + [DataRow(FsTypeFlags.PreviewPrint)] + [DataRow(FsTypeFlags.NoSubsetting)] + [DataRow(FsTypeFlags.BitmapEmbeddingOnly)] + [DataRow(FsTypeFlags.Editable | FsTypeFlags.NoSubsetting)] + [DataRow(FsTypeFlags.Editable | FsTypeFlags.BitmapEmbeddingOnly)] + public void ResolveEmbeddingDecision_Web_RestrictiveFsType_ReturnsSkipWithoutThrowing(FsTypeFlags fsType) + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = fsType; + Assert.AreEqual(FontEmbeddingDecision.Skip, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_BundledFont_ReturnsSubsetRegardlessOfFsType() + { + // Bundled fonts are OFL-licensed; the bundled check runs before fsType is consulted. + var font = TestFolderEngine.LoadFont("Archivo Narrow", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.RestrictedLicense; + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + // ---- Level 2c: document (PDF) path is unchanged ---- + + [TestMethod] + [DataRow(FsTypeFlags.Installable)] + [DataRow(FsTypeFlags.PreviewPrint)] + [DataRow(FsTypeFlags.Editable)] + [DataRow(FsTypeFlags.NoSubsetting)] + [DataRow(FsTypeFlags.BitmapEmbeddingOnly)] + public void ResolveEmbeddingDecision_OverloadWithoutTarget_EqualsDocument(FsTypeFlags fsType) + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = fsType; + Assert.AreEqual( + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Document), + TestFolderEngine.ResolveEmbeddingDecision(font)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Document_PreviewPrint_ReturnsSubset() + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.PreviewPrint; + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Document)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Document_BitmapEmbeddingOnly_IsIgnored() + { + // Documents current behaviour: the PDF path does not act on bitmap-only. Changing that is + // a separate decision; if it is made, this test is expected to change with it. + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.BitmapEmbeddingOnly; + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Document)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Document_RestrictedLicense_StillThrows() + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.RestrictedLicense; + Assert.ThrowsExactly( + () => TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Document)); + } + + // ---- Level 2d: web default policy requires an open licence ---- + + [TestMethod] + public void ResolveEmbeddingDecision_Web_NoLicenseRecords_ReturnsSkip() + { + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.Installable; + LicenseDetectionTests.SetLicenseRecords(font, null, null); + + Assert.AreEqual(FontEmbeddingDecision.Skip, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + [DataRow(FsTypeFlags.Installable)] + [DataRow(FsTypeFlags.Editable)] + public void ResolveEmbeddingDecision_Web_CommercialLicense_ReturnsSkipWhateverFsType(FsTypeFlags fsType) + { + // fsType Editable permits embedding in documents, not use as a web font. + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = fsType; + LicenseDetectionTests.SetLicenseRecords(font, "Commercial font. All rights reserved.", "https://example.com/eula"); + + Assert.AreEqual(FontEmbeddingDecision.Skip, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_OpenLicenseButRestrictiveFsType_ReturnsSkip() + { + // An open licence is not enough on its own; fsType must also permit embedding. + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.PreviewPrint; + Assert.IsTrue(font.NameTable.HasOpenLicense(), "Test setup: Roboto is Apache licensed."); + + Assert.AreEqual(FontEmbeddingDecision.Skip, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_NoLicense_CallbackSubset_Wins() + { + var engine = CreateEngineWithCallback(info => FontEmbeddingDecision.Subset); + var font = engine.LoadFont("Roboto", ignoreCache: true); + LicenseDetectionTests.SetLicenseRecords(font, null, null); + + Assert.AreEqual(FontEmbeddingDecision.Subset, + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_BundledFont_WithoutLicenseRecords_ReturnsSubset() + { + var font = TestFolderEngine.LoadFont("Archivo Narrow", ignoreCache: true); + LicenseDetectionTests.SetLicenseRecords(font, null, null); + + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Document_NoLicense_IsUnchanged() + { + // The licence rule applies to web output only. + var font = TestFolderEngine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.Installable; + LicenseDetectionTests.SetLicenseRecords(font, null, null); + + Assert.AreEqual(FontEmbeddingDecision.Subset, + TestFolderEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Document)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_CallbackReceivesLicense_OpenFont() + { + FontEmbeddingInfo captured = null; + var engine = CreateEngineWithCallback(info => + { + captured = info; + return FontEmbeddingDecision.Default; + }); + + var font = engine.LoadFont("Roboto", ignoreCache: true); + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web); + + Assert.IsNotNull(captured); + Assert.IsTrue(captured.HasOpenLicense); + StringAssert.Contains(captured.LicenseDescription, "Apache License"); + } + + [TestMethod] + public void ResolveEmbeddingDecision_CallbackReceivesLicense_NoLicense() + { + FontEmbeddingInfo captured = null; + var engine = CreateEngineWithCallback(info => + { + captured = info; + return FontEmbeddingDecision.Default; + }); + + var font = engine.LoadFont("Roboto", ignoreCache: true); + LicenseDetectionTests.SetLicenseRecords(font, null, null); + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web); + + Assert.IsNotNull(captured); + Assert.IsFalse(captured.HasOpenLicense); + Assert.IsNull(captured.LicenseDescription); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_SystemCommercialFont_ReturnsSkip() + { + // Calibri is a Microsoft font with fsType Editable; it must not be served as a web font. + RequireFont(SystemFontsEngine, "Calibri"); + var font = SystemFontsEngine.LoadFont("Calibri"); + + Assert.IsFalse(font.NameTable.HasOpenLicense()); + Assert.AreEqual(FontEmbeddingDecision.Skip, + SystemFontsEngine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + // ---- Level 3b: callback with target ---- + + [TestMethod] + public void ResolveEmbeddingDecision_Web_CallbackReceivesTargetPermissionAndBitmapFlag() + { + FontEmbeddingInfo captured = null; + var engine = CreateEngineWithCallback(info => + { + captured = info; + return FontEmbeddingDecision.Default; + }); + + var font = engine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.Editable | FsTypeFlags.BitmapEmbeddingOnly; + + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web); + + Assert.IsNotNull(captured); + Assert.AreEqual(FontRenderTarget.Web, captured.Target); + Assert.AreEqual(FontEmbeddingPermission.Editable, captured.Permission); + Assert.IsTrue(captured.BitmapEmbeddingOnly); + Assert.AreEqual(FontEmbeddingRestriction.None, captured.Restriction); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Document_CallbackReceivesDocumentTarget() + { + FontEmbeddingInfo captured = null; + var engine = CreateEngineWithCallback(info => + { + captured = info; + return FontEmbeddingDecision.Default; + }); + + var font = engine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.PreviewPrint; + + engine.ResolveEmbeddingDecision(font); + + Assert.IsNotNull(captured); + Assert.AreEqual(FontRenderTarget.Document, captured.Target); + Assert.AreEqual(FontEmbeddingPermission.PreviewAndPrint, captured.Permission); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_CallbackSubset_OverridesWebPolicy() + { + // A caller holding a web-font licence can opt in to embedding a Preview & Print font. + var engine = CreateEngineWithCallback(info => FontEmbeddingDecision.Subset); + var font = engine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.PreviewPrint; + + Assert.AreEqual(FontEmbeddingDecision.Subset, + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + [TestMethod] + public void ResolveEmbeddingDecision_Web_CallbackDefault_FallsThroughToWebPolicy() + { + var engine = CreateEngineWithCallback(info => FontEmbeddingDecision.Default); + var font = engine.LoadFont("Roboto", ignoreCache: true); + font.Os2Table.fsType = FsTypeFlags.PreviewPrint; + + Assert.AreEqual(FontEmbeddingDecision.Skip, + engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web)); + } + + // ---- FontEmbeddingInfo backward compatibility ---- + + [TestMethod] + public void FontEmbeddingInfo_TwoArgumentConstructor_DefaultsToInstallableDocument() + { + var info = new FontEmbeddingInfo("Some Font", FontEmbeddingRestriction.None); + + Assert.AreEqual(FontEmbeddingPermission.Installable, info.Permission); + Assert.IsFalse(info.BitmapEmbeddingOnly); + Assert.AreEqual(FontRenderTarget.Document, info.Target); + } + + [TestMethod] + public void FontEmbeddingInfo_FiveArgumentConstructor_HasNoOpenLicense() + { + var info = new FontEmbeddingInfo("Some Font", FontEmbeddingRestriction.None, + FontEmbeddingPermission.Editable, false, FontRenderTarget.Web); + + Assert.IsFalse(info.HasOpenLicense); + Assert.IsNull(info.LicenseDescription); + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontPlanCodePointStackTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontPlanCodePointStackTests.cs new file mode 100644 index 0000000000..0a0b98e6a9 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontPlanCodePointStackTests.cs @@ -0,0 +1,157 @@ +using EPPlus.Fonts.OpenType.Subsetting; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Tests for the stacks per code point () + /// and for the script chains that follow a glyph fallback written by name. + /// + /// Hiragana is routed to BIZ UDGothic, the only Japanese test font. Its script chain also names + /// Yu Gothic and Meiryo, which are not installed here. + /// + [TestClass] + public class WebFontPlanCodePointStackTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private const int LatinA = 'a'; + private const int HiraganaA = 0x3042; // あ + private const int HiraganaI = 0x3044; // い + + private static OpenTypeFontEngine CreateEngine(bool embedFallback) + { + return new OpenTypeFontEngine(cfg => + { + foreach (var folder in FontFolders) + cfg.FontDirectories.Add(folder); + cfg.SearchSystemDirectories = false; + cfg.SetScriptFallback(UnicodeScript.Hiragana, "BIZ UDGothic", "Yu Gothic", "Meiryo"); + if (!embedFallback) + { + cfg.OnFontEmbedding(info => info.FontName.StartsWith("BIZ UDGothic", StringComparison.OrdinalIgnoreCase) + ? FontEmbeddingDecision.Skip + : FontEmbeddingDecision.Default); + } + }); + } + + private static WebFontPlan Plan(OpenTypeFontEngine engine, string text) + { + var planner = new WebFontSubsetPlanner(engine); + planner.AddText("Roboto", FontSubFamily.Regular, text); + return planner.Build(); + } + + [TestMethod] + public void FallbackByName_CodePointsGetAStackStartingWithTheFallback() + { + using (var engine = CreateEngine(embedFallback: false)) + { + var plan = Plan(engine, "ab あい"); + + var fontStack = plan.GetFamilyNames("Roboto", FontSubFamily.Regular); + var kana = plan.GetFamilyNames("Roboto", FontSubFamily.Regular, HiraganaA); + + CollectionAssert.AreEqual(new[] { "BIZ UDGothic", "Yu Gothic", "Meiryo" }, kana.Take(3).ToArray()); + CollectionAssert.IsSubsetOf(fontStack.ToArray(), kana.ToArray(), "The font's stack follows the fallback's."); + Assert.AreSame(kana, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, HiraganaI), + "Code points routed to the same fallback share one stack instance."); + } + } + + [TestMethod] + public void FallbackByName_OtherCodePointsGetTheFontStack() + { + using (var engine = CreateEngine(embedFallback: false)) + { + var plan = Plan(engine, "ab あい"); + var fontStack = plan.GetFamilyNames("Roboto", FontSubFamily.Regular); + + Assert.AreSame(fontStack, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, LatinA)); + Assert.AreSame(fontStack, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, ' ')); + Assert.AreSame(fontStack, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, 'Z'), "A code point that was never added."); + } + } + + [TestMethod] + public void FallbackByName_FontStackListsTheScriptChainAfterTheFallback() + { + using (var engine = CreateEngine(embedFallback: false)) + { + var plan = Plan(engine, "ab あい"); + var fontStack = plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToList(); + + Assert.IsTrue(fontStack[0].EndsWith("+Roboto"), string.Join(", ", fontStack)); + var fallback = fontStack.IndexOf("BIZ UDGothic"); + Assert.IsTrue(fallback > 0, string.Join(", ", fontStack)); + Assert.AreEqual("Yu Gothic", fontStack[fallback + 1]); + Assert.AreEqual("Meiryo", fontStack[fallback + 2]); + Assert.AreEqual(1, plan.Faces.Count, "Only Roboto is embedded."); + } + } + + [TestMethod] + public void EmbeddedFallback_HasNoStackOfItsOwn() + { + using (var engine = CreateEngine(embedFallback: true)) + { + var plan = Plan(engine, "ab あい"); + var fontStack = plan.GetFamilyNames("Roboto", FontSubFamily.Regular); + + Assert.AreSame(fontStack, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, HiraganaA), + "A subset only has the code points routed to it, so the font's stack draws them right."); + Assert.AreEqual(2, plan.Faces.Count); + Assert.IsFalse(fontStack.Contains("Yu Gothic"), "No script chain follows an embedded fallback."); + } + } + + [TestMethod] + public void NoEmbedding_EmbedsNothingAndStartsWithTheRequestedFamily() + { + using (var engine = CreateEngine(embedFallback: true)) + { + var planner = new WebFontSubsetPlanner(engine, false); + planner.AddText("Roboto", FontSubFamily.Regular, "ab あい"); + planner.AddText("Calibri", FontSubFamily.Regular, "ab"); + var plan = planner.Build(); + + Assert.AreEqual(0, plan.Faces.Count); + CollectionAssert.AreEqual(new[] { "Roboto", "BIZ UDGothic", "Yu Gothic", "Meiryo" }, + plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + + // Calibri is not installed: no Archivo Narrow safety net, Calibri first, then its chain. + var calibri = plan.GetFamilyNames("Calibri", FontSubFamily.Regular).ToList(); + Assert.AreEqual("Calibri", calibri[0]); + CollectionAssert.DoesNotContain(calibri, "Archivo Narrow"); + } + } + + [TestMethod] + public void NoEmbedding_FallbackCodePointsStillGetAStackOfTheirOwn() + { + using (var engine = CreateEngine(embedFallback: true)) + { + var planner = new WebFontSubsetPlanner(engine, false); + planner.AddText("Roboto", FontSubFamily.Regular, "ab あい"); + var plan = planner.Build(); + + var fontStack = plan.GetFamilyNames("Roboto", FontSubFamily.Regular); + var kana = plan.GetFamilyNames("Roboto", FontSubFamily.Regular, HiraganaA); + Assert.AreNotSame(fontStack, kana); + Assert.AreEqual("BIZ UDGothic", kana[0]); + Assert.AreSame(fontStack, plan.GetFamilyNames("Roboto", FontSubFamily.Regular, LatinA)); + } + } + + [TestMethod] + public void UnknownFont_ReturnsNull() + { + using (var engine = CreateEngine(embedFallback: false)) + { + var plan = Plan(engine, "ab"); + Assert.IsNull(plan.GetFamilyNames("Arial", FontSubFamily.Regular, LatinA)); + } + } + } +} diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontSubsetPlannerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontSubsetPlannerTests.cs new file mode 100644 index 0000000000..e7b4c8da7a --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/WebFontSubsetPlannerTests.cs @@ -0,0 +1,382 @@ +using EPPlus.Fonts.OpenType.Subsetting; +using OfficeOpenXml.Interfaces.Fonts; +using System.Text.RegularExpressions; + +namespace EPPlus.Fonts.OpenType.Tests.Subsetting +{ + /// + /// Tests for : which fonts are embedded as subsets in web + /// output, what each subset contains, and the font-family stack per measured font. + /// + /// The engines search only the test font folder, so Calibri and the other Office fonts are + /// never installed here. + /// + [TestClass] + public class WebFontSubsetPlannerTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private const string ChartIncreasing = "\U0001F4C8"; // 📈 + + private static OpenTypeFontEngine CreateEngine(Action? configure = null) + { + return new OpenTypeFontEngine(cfg => + { + foreach (var folder in FontFolders) + cfg.FontDirectories.Add(folder); + cfg.SearchSystemDirectories = false; + configure?.Invoke(cfg); + }); + } + + private static WebFontPlan Plan(OpenTypeFontEngine engine, params (string Family, FontSubFamily SubFamily, string Text)[] texts) + { + var planner = new WebFontSubsetPlanner(engine); + foreach (var t in texts) + planner.AddText(t.Family, t.SubFamily, t.Text); + return planner.Build(); + } + + private static WebFontFace SingleFace(WebFontPlan plan, string sourceFamily) + { + var faces = plan.Faces.Where(f => f.SourceFamily == sourceFamily).ToList(); + Assert.AreEqual(1, faces.Count, "Expected one subset of " + sourceFamily + "."); + return faces[0]; + } + + private static OpenTypeFont Parse(WebFontFace face) + { + return new OpenTypeFont(face.FontData); + } + + private static bool HasGlyph(OpenTypeFont font, int codePoint) + { + return font.CmapTable.TryGetGlyphId((uint)codePoint, out _); + } + + private static void AssertSubsetName(WebFontFace face) + { + StringAssert.Matches(face.FamilyName, new Regex("^[A-Z]{6}\\+" + Regex.Escape(face.SourceFamily) + "$")); + } + + // ----------------------------------------------------------------------------------------- + // Embeddable font + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void OpenFont_IsSubsetAndFirstInStack() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + + var face = SingleFace(plan, "Roboto"); + AssertSubsetName(face); + CollectionAssert.AreEqual(new[] { face.FamilyName, "Roboto" }, plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + Assert.AreEqual(GenericFontFamily.SansSerif, plan.GetGenericFamily("Roboto", FontSubFamily.Regular)); + } + } + + [TestMethod] + public void OpenFont_SubsetRoundTrips_WithTheRoutedCodePointsOnly() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + + var parsed = Parse(SingleFace(plan, "Roboto")); + foreach (var c in "Helo") + Assert.IsTrue(HasGlyph(parsed, c), "Missing '" + c + "'."); + Assert.IsFalse(HasGlyph(parsed, 'z')); + } + } + + [TestMethod] + public void FamilyLookup_IsCaseInsensitive() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + Assert.IsNotNull(plan.GetFamilyNames("ROBOTO", FontSubFamily.Regular)); + Assert.IsNull(plan.GetFamilyNames("Roboto", FontSubFamily.Bold)); + } + } + + [TestMethod] + public void BoldAndItalic_SetDescriptors() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, + ("Roboto", FontSubFamily.Bold, "Hi"), + ("Roboto", FontSubFamily.Italic, "Hi"), + ("Roboto", FontSubFamily.Regular, "Hi")); + + var bold = plan.Faces.Single(f => f.SubFamily == FontSubFamily.Bold); + var italic = plan.Faces.Single(f => f.SubFamily == FontSubFamily.Italic); + var regular = plan.Faces.Single(f => f.SubFamily == FontSubFamily.Regular); + + Assert.AreEqual(700, bold.FontWeight); + Assert.IsFalse(bold.IsItalic); + Assert.AreEqual(400, italic.FontWeight); + Assert.IsTrue(italic.IsItalic); + Assert.AreEqual(400, regular.FontWeight); + Assert.IsFalse(regular.IsItalic); + } + } + + [TestMethod] + public void EmptyText_GivesStackWithoutFace() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "")); + + Assert.AreEqual(0, plan.Faces.Count); + CollectionAssert.AreEqual(new[] { "Roboto" }, plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + } + } + + // ----------------------------------------------------------------------------------------- + // Shared subsets + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void SameFontInTwoRequests_IsSubsetOnce_WithUnionOfCodePoints() + { + // "Calibri" is not installed; the user chain resolves it to Roboto, so both requests + // are measured with Roboto. + using (var engine = CreateEngine(cfg => cfg.FontFallbacks["Calibri"] = new[] { "Roboto" })) + { + var plan = Plan(engine, + ("Roboto", FontSubFamily.Regular, "abc"), + ("Calibri", FontSubFamily.Regular, "xyz")); + + var face = SingleFace(plan, "Roboto"); + var parsed = Parse(face); + foreach (var c in "abcxyz") + Assert.IsTrue(HasGlyph(parsed, c), "Missing '" + c + "'."); + + CollectionAssert.AreEqual(new[] { face.FamilyName, "Roboto" }, plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + var calibri = plan.GetFamilyNames("Calibri", FontSubFamily.Regular).ToArray(); + Assert.AreEqual(face.FamilyName, calibri[0]); + Assert.AreEqual("Calibri", calibri[1]); + Assert.AreEqual("Roboto", calibri[2]); + } + } + + [TestMethod] + public void Callback_IsCalledOncePerFont() + { + var calls = new Dictionary(); + using (var engine = CreateEngine(cfg => + { + cfg.FontFallbacks["Calibri"] = new[] { "Roboto" }; + cfg.OnFontEmbedding(info => + { + calls.TryGetValue(info.FontName, out var n); + calls[info.FontName] = n + 1; + return FontEmbeddingDecision.Default; + }); + })) + { + Plan(engine, + ("Roboto", FontSubFamily.Regular, "abc"), + ("Calibri", FontSubFamily.Regular, "xyz")); + + Assert.IsTrue(calls.Count > 0); + foreach (var kvp in calls) + Assert.AreEqual(1, kvp.Value, "Callback called more than once for " + kvp.Key); + } + } + + // ----------------------------------------------------------------------------------------- + // Glyph fallback + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Emoji_IsInNotoEmojiSubset_AfterPrimary() + { + using (var engine = CreateEngine()) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Sales " + ChartIncreasing)); + + var roboto = SingleFace(plan, "Roboto"); + var emoji = plan.Faces.Single(f => f.SourceFamily.Contains("Emoji")); + AssertSubsetName(emoji); + + CollectionAssert.AreEqual(new[] { roboto.FamilyName, emoji.FamilyName, "Roboto" }, + plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + + Assert.IsTrue(HasGlyph(Parse(emoji), 0x1F4C8)); + Assert.IsFalse(HasGlyph(Parse(emoji), 'S')); + Assert.IsFalse(HasGlyph(Parse(roboto), 0x1F4C8)); + } + } + + [TestMethod] + public void CodePointNoFontHas_IsLeftOut() + { + using (var engine = CreateEngine()) + { + // U+E000 is private use; no test font and no bundled fallback has it. + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "ab\uE000")); + + Assert.AreEqual(1, plan.Faces.Count); + var parsed = Parse(SingleFace(plan, "Roboto")); + Assert.IsTrue(HasGlyph(parsed, 'a')); + Assert.IsFalse(HasGlyph(parsed, 0xE000)); + } + } + + // ----------------------------------------------------------------------------------------- + // Font that may not be embedded: name first, then the safety net + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void SkippedFont_NoChain_SafetyNetIsArchivoNarrow() + { + using (var engine = CreateEngine(cfg => + cfg.OnFontEmbedding(info => info.FontName.StartsWith("Roboto") ? FontEmbeddingDecision.Skip : FontEmbeddingDecision.Default))) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + + Assert.IsFalse(plan.Faces.Any(f => f.SourceFamily == "Roboto")); + var archivo = SingleFace(plan, "Archivo Narrow"); + Assert.IsTrue(HasGlyph(Parse(archivo), 'H')); + + CollectionAssert.AreEqual(new[] { "Roboto", archivo.FamilyName }, + plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + } + } + + [TestMethod] + public void SkippedFont_WithChain_SafetyNetIsFirstEmbeddableChainFont() + { + using (var engine = CreateEngine(cfg => + { + cfg.FontFallbacks["Roboto"] = new[] { "Not Installed", "Open Sans" }; + cfg.OnFontEmbedding(info => info.FontName.StartsWith("Roboto") ? FontEmbeddingDecision.Skip : FontEmbeddingDecision.Default); + })) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + + var openSans = SingleFace(plan, "Open Sans"); + Assert.IsFalse(plan.Faces.Any(f => f.SourceFamily == "Archivo Narrow")); + CollectionAssert.AreEqual(new[] { "Roboto", openSans.FamilyName, "Not Installed", "Open Sans" }, + plan.GetFamilyNames("Roboto", FontSubFamily.Regular).ToArray()); + } + } + + [TestMethod] + public void EmbedWhole_IsNotEmbedded() + { + using (var engine = CreateEngine(cfg => + cfg.OnFontEmbedding(info => info.FontName.StartsWith("Roboto") ? FontEmbeddingDecision.EmbedWhole : FontEmbeddingDecision.Default))) + { + var plan = Plan(engine, ("Roboto", FontSubFamily.Regular, "Hello")); + + Assert.IsFalse(plan.Faces.Any(f => f.SourceFamily == "Roboto")); + Assert.AreEqual("Roboto", plan.GetFamilyNames("Roboto", FontSubFamily.Regular)[0]); + } + } + + [TestMethod] + public void CffFont_IsNotEmbedded() + { + using (var engine = CreateEngine()) + { + RequireFont(engine, "Source Sans 3"); + var plan = Plan(engine, ("Source Sans 3", FontSubFamily.Regular, "Hello")); + + Assert.IsFalse(plan.Faces.Any(f => f.SourceFamily == "Source Sans 3")); + var archivo = SingleFace(plan, "Archivo Narrow"); + CollectionAssert.AreEqual(new[] { "Source Sans 3", archivo.FamilyName }, + plan.GetFamilyNames("Source Sans 3", FontSubFamily.Regular).ToArray()); + } + } + + // ----------------------------------------------------------------------------------------- + // Font not installed + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void MissingFont_MeasuredFromMetrics_IsWrittenByName() + { + using (var engine = CreateEngine(cfg => cfg.MetricsFallback = MetricsFallbackMode.WhenFontMissing)) + { + if (engine.GetMeasurementShaper("Calibri").HasGlyphIds) + Assert.Inconclusive("Test setup: Calibri is expected to be measured from serialized metrics."); + + var plan = Plan(engine, ("Calibri", FontSubFamily.Regular, "Hello")); + var archivo = SingleFace(plan, "Archivo Narrow"); + + CollectionAssert.AreEqual( + new[] { "Calibri", archivo.FamilyName, "Carlito", "Liberation Sans", "Arial", "Helvetica" }, + plan.GetFamilyNames("Calibri", FontSubFamily.Regular).ToArray()); + } + } + + [TestMethod] + public void MissingFont_WithoutMetrics_EmbedsArchivoNarrowAndWarns() + { + var logger = new CapturingLogger(); + using (var engine = CreateEngine(cfg => + { + cfg.MetricsFallback = MetricsFallbackMode.Disabled; + cfg.Logger = logger; + })) + { + var plan = Plan(engine, ("No Such Font", FontSubFamily.Regular, "Hello")); + + var archivo = SingleFace(plan, "Archivo Narrow"); + CollectionAssert.AreEqual(new[] { archivo.FamilyName, "No Such Font" }, + plan.GetFamilyNames("No Such Font", FontSubFamily.Regular).ToArray()); + Assert.IsTrue(logger.Events.Any(e => e.Severity == FontLogSeverity.Warning + && e.Type == FontLogEventType.EmbeddingDecision + && e.Message.Contains("last-resort"))); + } + } + + [TestMethod] + public void ArchivoNarrow_IsNeverWrittenByName() + { + using (var engine = CreateEngine(cfg => cfg.MetricsFallback = MetricsFallbackMode.Disabled)) + { + var plan = Plan(engine, + ("No Such Font", FontSubFamily.Regular, "Hello"), + ("Archivo Narrow", FontSubFamily.Regular, "Hello")); + + foreach (var family in new[] { "No Such Font", "Archivo Narrow" }) + { + foreach (var name in plan.GetFamilyNames(family, FontSubFamily.Regular)) + Assert.AreNotEqual("Archivo Narrow", name, "Archivo Narrow written by name in the stack for " + family); + } + } + } + + // ----------------------------------------------------------------------------------------- + // Usage + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Build_Twice_Throws() + { + using (var engine = CreateEngine()) + { + var planner = new WebFontSubsetPlanner(engine); + planner.AddText("Roboto", FontSubFamily.Regular, "a"); + planner.Build(); + Assert.ThrowsExactly(() => planner.Build()); + Assert.ThrowsExactly(() => planner.AddText("Roboto", FontSubFamily.Regular, "b")); + } + } + + private sealed class CapturingLogger : IFontLogger + { + public List Events { get; } = new List(); + public bool IsEnabled(FontLogSeverity severity) => true; + public void Log(FontLogEvent logEvent) => Events.Add(logEvent); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapTableTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapTableTests.cs new file mode 100644 index 0000000000..1caaddaa80 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapTableTests.cs @@ -0,0 +1,47 @@ +using EPPlus.Fonts.OpenType.Tests.Helpers; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace EPPlus.Fonts.OpenType.Tests.Tables +{ + [TestClass] + public class CmapTableTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + [TestMethod] + [DataRow("Mulish-Regular.ttf")] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("CrimsonText-Regular.ttf")] + public void Cmap_Subset_EncodingRecordsAreSorted(string fileName) + { + var font = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName))); + var bytes = new OpenTypeFontSerializer(font.CreateSubset("Hello World 123")).Serialize(); + SaveFontForCurrentTest(new OpenTypeFont(bytes), Path.GetFileNameWithoutExtension(fileName)); + + FontTestHelper.FindTableInDirectory(bytes, "cmap", out int cmapOffset, out _); + int numTables = (bytes[cmapOffset + 2] << 8) | bytes[cmapOffset + 3]; + + var records = new List>(); + for (int i = 0; i < numTables; i++) + { + int recordStart = cmapOffset + 4 + i * 8; + int platformId = (bytes[recordStart] << 8) | bytes[recordStart + 1]; + int encodingId = (bytes[recordStart + 2] << 8) | bytes[recordStart + 3]; + records.Add(new KeyValuePair(platformId, encodingId)); + } + + Console.WriteLine("Encoding records: " + string.Join(", ", records.Select(r => "(" + r.Key + "," + r.Value + ")").ToArray())); + + for (int i = 1; i < records.Count; i++) + { + bool inOrder = records[i - 1].Key < records[i].Key + || (records[i - 1].Key == records[i].Key && records[i - 1].Value < records[i].Value); + Assert.IsTrue(inOrder, "Encoding records are not sorted by platformID, encodingID"); + } + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Name/LicenseDetectionTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Name/LicenseDetectionTests.cs new file mode 100644 index 0000000000..ba93fdc130 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Name/LicenseDetectionTests.cs @@ -0,0 +1,163 @@ +using EPPlus.Fonts.OpenType.Tables.Name; +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Tests.Tables +{ + /// + /// Tests for licence detection in the name table: , + /// and . + /// + [TestClass] + public class LicenseDetectionTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + private const string MicrosoftDescription = + "Microsoft supplied font. You may use this font to create, display, and print content as permitted by the license terms or terms of use, of the Microsoft product, service, or content in which this font was included."; + + /// + /// Loads a private copy of a test font, so changes to its name records do not leak into the + /// shared engine. + /// + internal static OpenTypeFont LoadPrivate(string family) + { + RequireFont(TestFolderEngine, family); + return TestFolderEngine.LoadFont(family, FontSubFamily.Regular, ignoreCache: true); + } + + /// + /// Replaces the licence records (nameID 13 and 14) of the font. Pass null to leave a record out. + /// + internal static void SetLicenseRecords(OpenTypeFont font, string description, string url) + { + var records = font.NameTable.NameRecords + .Where(r => r.RecordType != NameRecordTypes.LicenseDescription && r.RecordType != NameRecordTypes.LicenseInfoUrl) + .ToList(); + + if (description != null) + records.Add(CreateWindowsRecord(NameRecordTypes.LicenseDescription, description)); + if (url != null) + records.Add(CreateWindowsRecord(NameRecordTypes.LicenseInfoUrl, url)); + + font.NameTable.NameRecords = records.ToArray(); + } + + private static NameRecord CreateWindowsRecord(NameRecordTypes type, string text) + { + return new NameRecord + { + platformId = 3, + encodingId = 1, + languageID = 0x0409, + nameId = (ushort)type, + RecordType = type, + Name = text + }; + } + + // ----------------------------------------------------------------------------------------- + // Test fonts as shipped + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void Roboto_IsApache() + { + var font = LoadPrivate("Roboto"); + Assert.IsTrue(font.NameTable.HasOpenLicense()); + StringAssert.Contains(font.NameTable.GetLicenseDescription(), "Apache License"); + StringAssert.Contains(font.NameTable.GetLicenseInfoUrl(), "apache.org/licenses"); + } + + [TestMethod] + [DataRow("Open Sans")] + [DataRow("EB Garamond")] + [DataRow("Mulish")] + public void OflFont_IsOpen(string family) + { + var font = LoadPrivate(family); + Assert.IsTrue(font.NameTable.HasOpenLicense()); + StringAssert.Contains(font.NameTable.GetLicenseDescription(), "SIL Open Font License"); + } + + // ----------------------------------------------------------------------------------------- + // Rules, on private copies with the licence records replaced + // ----------------------------------------------------------------------------------------- + + [TestMethod] + public void NoLicenseRecords_IsNotOpen() + { + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, null, null); + + Assert.IsFalse(font.NameTable.HasOpenLicense()); + Assert.IsNull(font.NameTable.GetLicenseDescription()); + Assert.IsNull(font.NameTable.GetLicenseInfoUrl()); + } + + [TestMethod] + public void CommercialDescription_IsNotOpen() + { + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, MicrosoftDescription, "https://docs.microsoft.com/typography"); + + Assert.IsFalse(font.NameTable.HasOpenLicense()); + Assert.AreEqual(MicrosoftDescription, font.NameTable.GetLicenseDescription()); + } + + [TestMethod] + [DataRow("This Font Software is licensed under the SIL Open Font License, Version 1.1.")] + [DataRow("Licensed under the Apache License, Version 2.0")] + [DataRow("Copyright 2011 Canonical Ltd. Licensed under the Ubuntu Font Licence 1.0")] + [DataRow("Fonts are (c) Bitstream (see below). DejaVu changes are in public domain. Bitstream Vera Fonts Copyright ...")] + [DataRow("this font software is licensed under the sil open font license")] // case-insensitive + public void OpenDescription_WithoutUrl_IsOpen(string description) + { + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, description, null); + Assert.IsTrue(font.NameTable.HasOpenLicense()); + } + + [TestMethod] + [DataRow("http://scripts.sil.org/OFL")] + [DataRow("https://openfontlicense.org")] + [DataRow("http://www.apache.org/licenses/LICENSE-2.0")] + public void OpenUrl_WithoutDescription_IsOpen(string url) + { + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, null, url); + Assert.IsTrue(font.NameTable.HasOpenLicense()); + } + + [TestMethod] + public void OpenLicenseOnOtherPlatformRecord_IsOpen() + { + // Any record counts, not only the English Windows record. + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, MicrosoftDescription, null); + var records = font.NameTable.NameRecords.ToList(); + records.Add(new NameRecord + { + platformId = 1, + encodingId = 0, + languageID = 0, + nameId = (ushort)NameRecordTypes.LicenseDescription, + RecordType = NameRecordTypes.LicenseDescription, + Name = "Licensed under the SIL Open Font License" + }); + font.NameTable.NameRecords = records.ToArray(); + + Assert.IsTrue(font.NameTable.HasOpenLicense()); + } + + [TestMethod] + public void GplFontException_IsNotOpen() + { + // Open decision in the plan: GPLv2 with font exception (Liberation 1.x) is not accepted yet. + var font = LoadPrivate("Roboto"); + SetLicenseRecords(font, + "Licensed under the GNU General Public License v2 with the font exception", + "http://www.gnu.org/licenses/gpl-2.0.html"); + Assert.IsFalse(font.NameTable.HasOpenLicense()); + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Os2/Os2TableTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Os2/Os2TableTests.cs new file mode 100644 index 0000000000..144f09c08c --- /dev/null +++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Os2/Os2TableTests.cs @@ -0,0 +1,65 @@ +using EPPlus.Fonts.OpenType.Tests.Helpers; +using System.IO; + +namespace EPPlus.Fonts.OpenType.Tests.Tables +{ + [TestClass] + public class Os2TableTests : FontTestBase + { + public override TestContext? TestContext { get; set; } + + [TestMethod] + [DataRow("Mulish-Regular.ttf")] + [DataRow("Roboto-Regular.ttf")] + [DataRow("OpenSans-Regular.ttf")] + [DataRow("EBGaramond-Regular.ttf")] + [DataRow("CrimsonText-Regular.ttf")] + public void Os2_Subset_HasLengthMatchingVersion(string fileName) + { + var font = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName))); + ushort version = font.Os2Table.version; + Console.WriteLine(fileName + ": OS/2 version " + version); + + if (version < 5) + { + // Optical size fields only exist from version 5; anything else was read past the table end + Assert.AreEqual((ushort)0, font.Os2Table.usLowerOpticalPointSize, "usLowerOpticalPointSize read for version " + version); + Assert.AreEqual((ushort)0, font.Os2Table.usUpperOpticalPointSize, "usUpperOpticalPointSize read for version " + version); + } + + var bytes = new OpenTypeFontSerializer(font.CreateSubset("Hello World 123")).Serialize(); + SaveFontForCurrentTest(new OpenTypeFont(bytes), Path.GetFileNameWithoutExtension(fileName)); + + Assert.AreEqual(GetExpectedOs2Length(version), GetTableLength(bytes, "OS/2"), "OS/2 length for version " + version); + } + + private static int GetExpectedOs2Length(ushort version) + { + if (version == 0) return 78; + if (version == 1) return 86; + if (version <= 4) return 96; + return 100; + } + + /// + /// Reads a table's length directly from the serialized table directory, so the test + /// does not depend on the font model. + /// + private static int GetTableLength(byte[] fontBytes, string tag) + { + int numTables = (fontBytes[4] << 8) | fontBytes[5]; + for (int i = 0; i < numTables; i++) + { + int recordStart = 12 + i * 16; + string recordTag = System.Text.Encoding.ASCII.GetString(fontBytes, recordStart, 4); + if (recordTag == tag) + { + return (fontBytes[recordStart + 12] << 24) | (fontBytes[recordStart + 13] << 16) + | (fontBytes[recordStart + 14] << 8) | fontBytes[recordStart + 15]; + } + } + Assert.Fail("Table " + tag + " not found"); + return 0; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/FontStore.cs b/src/EPPlus.Fonts.OpenType/FontStore.cs index e9d899f714..45dd195f59 100644 --- a/src/EPPlus.Fonts.OpenType/FontStore.cs +++ b/src/EPPlus.Fonts.OpenType/FontStore.cs @@ -30,6 +30,8 @@ internal class FontStore : IFontSource { private readonly object _syncRoot = new object(); private readonly Dictionary _fontLocks = new Dictionary(); + + private readonly Dictionary _availability = new Dictionary(); private readonly OpenTypeFontCache _fontCache = new OpenTypeFontCache(); private readonly IFontResolver _resolver; private readonly EpplusFontConfiguration _configuration; @@ -138,6 +140,8 @@ public OpenTypeFont LoadFont(string fontName, FontSubFamily subFamily) /// to it. Otherwise it probes via , which can only /// distinguish found from not found — never , and /// never NotFound at all for a resolver that substitutes internally. + /// The answer is cached for the lifetime of the store, like loaded fonts: a lookup searches + /// the font directories, and web output asks for the same fallback chains for every svg. /// public FontAvailability GetFontAvailability(string fontName, FontSubFamily subFamily) { @@ -145,13 +149,31 @@ public FontAvailability GetFontAvailability(string fontName, FontSubFamily subFa if (fontName == null) throw new ArgumentNullException("fontName"); + var key = BuildCacheKey(fontName, subFamily); + FontAvailability availability; + lock (_syncRoot) + { + if (_availability.TryGetValue(key, out availability)) + return availability; + } + var provider = _resolver as IFontAvailabilityProvider; if (provider != null) - return provider.GetFontAvailability(fontName, subFamily); + { + availability = provider.GetFontAvailability(fontName, subFamily); + } + else + { + availability = _resolver.ResolveFont(fontName, subFamily) != null + ? FontAvailability.Exact + : FontAvailability.NotFound; + } - return _resolver.ResolveFont(fontName, subFamily) != null - ? FontAvailability.Exact - : FontAvailability.NotFound; + lock (_syncRoot) + { + _availability[key] = availability; + } + return availability; } /// @@ -170,6 +192,7 @@ internal void Clear() { _fontCache.Clear(); _fontLocks.Clear(); + _availability.Clear(); } } diff --git a/src/EPPlus.Fonts.OpenType/GenericFontFamilyClassifier.cs b/src/EPPlus.Fonts.OpenType/GenericFontFamilyClassifier.cs new file mode 100644 index 0000000000..49dee2fef2 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/GenericFontFamilyClassifier.cs @@ -0,0 +1,69 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Generic font family for CSS font stacks + *************************************************************************************************/ +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType +{ + /// + /// Decides the CSS generic family of a font from its own tables. + /// + /// In order: + /// 1. post.isFixedPitch set → monospace + /// 2. OS/2 sFamilyClass, class 1-7 → serif (the IBM classes for serif designs) + /// 3. PANOSE, Latin text (family type 2): + /// proportion 9 (monospaced) → monospace + /// serif style 2-10 → serif + /// 4. anything else → sans-serif + /// + /// Many fonts, Google Fonts in particular, leave both sFamilyClass and PANOSE at 0. Such + /// fonts are reported as sans-serif even when they have serifs, since nothing in the font + /// says otherwise. + /// + internal static class GenericFontFamilyClassifier + { + private const int PanoseFamilyTypeLatinText = 2; + private const int PanoseProportionMonospaced = 9; + + internal static GenericFontFamily Classify(OpenTypeFont font) + { + if (font == null) + return GenericFontFamily.SansSerif; + + var post = font.PostTable; + if (post != null && post.isFixedPitch != 0) + return GenericFontFamily.Monospace; + + var os2 = font.Os2Table; + if (os2 == null) + return GenericFontFamily.SansSerif; + + // The class id is the high byte; the low byte is the subclass. + var familyClass = (os2.sFamilyClass >> 8) & 0xFF; + if (familyClass >= 1 && familyClass <= 7) + return GenericFontFamily.Serif; + + var panose = os2.panose; + if (panose != null && panose.Length >= 4 && panose[0] == PanoseFamilyTypeLatinText) + { + if (panose[3] == PanoseProportionMonospaced) + return GenericFontFamily.Monospace; + + var serifStyle = panose[1]; + if (serifStyle >= 2 && serifStyle <= 10) + return GenericFontFamily.Serif; + } + + return GenericFontFamily.SansSerif; + } + } +} diff --git a/src/EPPlus.Fonts.OpenType/Integration/DataHolders/TextLineCollection.cs b/src/EPPlus.Fonts.OpenType/Integration/DataHolders/TextLineCollection.cs index 4c71afeb63..4f722d89bb 100644 --- a/src/EPPlus.Fonts.OpenType/Integration/DataHolders/TextLineCollection.cs +++ b/src/EPPlus.Fonts.OpenType/Integration/DataHolders/TextLineCollection.cs @@ -290,7 +290,7 @@ public double GetBaseLinePosition(int lineIndex, double exactLineSpacing = doubl } else { - position = lineIndex+1 * exactLineSpacing; + position = (lineIndex + 1) * exactLineSpacing; } return position; diff --git a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs index 10c0e2a5b7..f496c17be4 100644 --- a/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs +++ b/src/EPPlus.Fonts.OpenType/Integration/TextLayoutEngine.RichText.cs @@ -471,6 +471,7 @@ private void WrapCurrentLine(StringBuilder lineBuilder, WrapStateRichText state, int fragIdxAtBreak = state.CurrentFragmentIdx; int adjustmentForLineBuilderLength = 0; + double movedCharWidth = 0; // Bounds check to prevent ArgumentOutOfRangeException if (state.WordStart >= 0 && state.WordStart < lineBuilder.Length) @@ -505,7 +506,11 @@ private void WrapCurrentLine(StringBuilder lineBuilder, WrapStateRichText state, //handle line data state.CurrentTextLine.Width = state.CurrentLineWidth - advanceWidth; state.CurrentTextLine.Text = line; - //state.CurrentTextLine. + + //The char that went over max was already added to the current line fragment. + //It leaves this line, so its width must leave the fragment too, or the fragment + //is wider than its text. + state.LineFrag.Width -= advanceWidth; //Add the char that went over max to the next line state.CurrentLineWidth = 0; @@ -522,6 +527,7 @@ private void WrapCurrentLine(StringBuilder lineBuilder, WrapStateRichText state, //must be added to the new line state.CurrentWordWidth = advanceWidth; state.CurrentLineWidth = advanceWidth; + movedCharWidth = advanceWidth; } else { @@ -532,6 +538,9 @@ private void WrapCurrentLine(StringBuilder lineBuilder, WrapStateRichText state, state.EndCurrentTextLineAndIntializeNext(lineBuilder.Length - adjustmentForLineBuilderLength); state.CurrentWordWidth = state.CurrentLineWidth; + //The fragment that starts the new line holds the moved char, so it carries its width. + state.LineFrag.Width += movedCharWidth; + state.WordStart = -1; state.LineStart = -1; } diff --git a/src/EPPlus.Fonts.OpenType/Integration/WrapStateRichText.cs b/src/EPPlus.Fonts.OpenType/Integration/WrapStateRichText.cs index de9d64891c..c411f86054 100644 --- a/src/EPPlus.Fonts.OpenType/Integration/WrapStateRichText.cs +++ b/src/EPPlus.Fonts.OpenType/Integration/WrapStateRichText.cs @@ -31,10 +31,11 @@ internal void EndCurrentTextLineAndIntializeNext(int startIdxOfNewFragment) if (_fragmentsForNextLine == null) { EndCurrentTextLine(); + //The new fragment continues the same input fragment, so it has the same space width. double spcWidthTemp = 0; if (LineFrag != null) { - spcWidthTemp = LineFrag.Width; + spcWidthTemp = LineFrag.SpaceWidth; } LineFrag = new LineFragment(CurrentFragmentIdx, startIdxOfNewFragment, CharIdxRt, CharIdxWithinOriginal); LineFrag.SpaceWidth = spcWidthTemp; diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs index d864c7f722..84b835f76f 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs @@ -651,10 +651,17 @@ public OpenTypeFont CreateSubset(IEnumerable usedChars) } internal OpenTypeFont CreateSubset(IEnumerable usedChars, bool addSubsetTag) + { + return CreateSubset(usedChars, new SubsetOptions { AddSubsetTag = addSubsetTag }); + } + + internal OpenTypeFont CreateSubset(IEnumerable usedChars, SubsetOptions options) { // Validate input if (usedChars == null) throw new ArgumentNullException(nameof(usedChars)); + if (options == null) + throw new ArgumentNullException(nameof(options)); if (!usedChars.Any()) throw new ArgumentException("Text cannot be empty", nameof(usedChars)); @@ -662,9 +669,9 @@ internal OpenTypeFont CreateSubset(IEnumerable usedChars, bool addSubsetTa var subsetBuilder = new SubsetFontBuilder(); var codePoints = CodePointUtil.ExtractCodePoints(usedChars); - var newFont = subsetBuilder.CreateSubset(this, codePoints); + var newFont = subsetBuilder.CreateSubset(this, codePoints, options.RemoveHinting); - if (addSubsetTag) + if (options.AddSubsetTag) { // Must happen BEFORE post-processing so lengths, checksums and any // preprocessed table bytes are computed from the final name table. @@ -741,7 +748,7 @@ public byte[] GetTableData(string tag) } } var ctx = new FontSerializationContext(this); - switch(tag) + switch (tag) { case TableNames.Head: return HeadTable.Serialize(ctx); @@ -774,6 +781,12 @@ public byte[] GetTableData(string tag) case TableNames.Vmtx: return VmtxTable?.Serialize(ctx); default: + // Tables without a typed accessor (e.g. RawFontTable) live only in the local cache. + if (_localTableCache.Contains(tag)) + { + var table = _localTableCache.Get(tag) as FontTableBase; + return table != null ? table.Serialize(ctx) : null; + } return null; } } diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs index cdf14be030..f2537b2117 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs @@ -126,7 +126,7 @@ internal FontStore FontStore /// The configured logger, or one that is never enabled. Read on each use, so a logger /// assigned after construction is picked up. /// - private IFontLogger Logger + internal IFontLogger Logger { get { return _configuration.ActiveLogger; } } @@ -334,15 +334,29 @@ private void ThrowIfDisposed() } internal FontEmbeddingDecision ResolveEmbeddingDecision(OpenTypeFont font) + { + return ResolveEmbeddingDecision(font, FontRenderTarget.Document); + } + + internal FontEmbeddingDecision ResolveEmbeddingDecision(OpenTypeFont font, FontRenderTarget target) { var logger = Logger; - var restriction = font.Os2Table != null - ? font.Os2Table.GetEmbeddingRestriction() + var os2 = font.Os2Table; + var restriction = os2 != null + ? os2.GetEmbeddingRestriction() : FontEmbeddingRestriction.None; + var permission = os2 != null + ? os2.GetEmbeddingPermission() + : FontEmbeddingPermission.Installable; + var bitmapEmbeddingOnly = os2 != null && os2.IsBitmapEmbeddingOnly(); var fontName = font.NameTable != null ? font.NameTable.GetFullFontName() : null; + var hasOpenLicense = font.NameTable != null && font.NameTable.HasOpenLicense(); + var licenseDescription = font.NameTable != null ? font.NameTable.GetLicenseDescription() : null; + // Bundled fonts (Archivo Narrow, Noto Emoji, Noto Math) are OFL-licensed and may be + // subsetted for every target. if (font.NameTable != null && EmbeddedFonts.IsBundledFamily(font.GetEnglishFontFamilyName())) { LogEmbedding(logger, FontLogSeverity.Debug, fontName, restriction, @@ -353,7 +367,8 @@ internal FontEmbeddingDecision ResolveEmbeddingDecision(OpenTypeFont font) var callback = _configuration.GetEmbeddingCallback(); if (callback != null) { - var decision = callback(new FontEmbeddingInfo(fontName, restriction)); + var decision = callback(new FontEmbeddingInfo( + fontName, restriction, permission, bitmapEmbeddingOnly, target, hasOpenLicense, licenseDescription)); if (decision != FontEmbeddingDecision.Default) { LogEmbedding(logger, FontLogSeverity.Information, fontName, restriction, @@ -362,7 +377,10 @@ internal FontEmbeddingDecision ResolveEmbeddingDecision(OpenTypeFont font) } } - // No callback, or callback returned Default → derive from the restriction. + // No callback, or callback returned Default → derive from fsType and the target. + if (target == FontRenderTarget.Web) + return ResolveDefaultWebDecision(logger, fontName, restriction, permission, bitmapEmbeddingOnly, hasOpenLicense); + switch (restriction) { case FontEmbeddingRestriction.NoEmbedding: @@ -397,6 +415,49 @@ internal FontEmbeddingDecision ResolveEmbeddingDecision(OpenTypeFont font) } } + /// + /// Default embedding policy for web output (SVG/HTML), where an embedded font is delivered as a + /// web font. A font is subsetted only when both hold: + /// * its fsType permits embedding of outlines and subsetting, and + /// * its name table names an open licence (see ). + /// fsType Editable means the font may be embedded in documents, not that it may be served as a + /// web font, so commercial fonts are skipped whatever their fsType. Everything else is skipped, + /// never thrown on: the fallback chain and the CSS font-family list always provide a replacement, + /// so a font that may not be embedded is not an error in web output. The OnFontEmbedding callback + /// can return Subset for any font the caller holds a web font licence for. + /// + private FontEmbeddingDecision ResolveDefaultWebDecision( + IFontLogger logger, + string fontName, + FontEmbeddingRestriction restriction, + FontEmbeddingPermission permission, + bool bitmapEmbeddingOnly, + bool hasOpenLicense) + { + string reason = null; + if (permission == FontEmbeddingPermission.RestrictedLicense) + reason = "fsType declares a restricted license"; + else if (permission == FontEmbeddingPermission.PreviewAndPrint) + reason = "fsType permits Preview & Print embedding only"; + else if (bitmapEmbeddingOnly) + reason = "fsType permits bitmap embedding only, and web output embeds outlines"; + else if (restriction == FontEmbeddingRestriction.NoSubsetting) + reason = "fsType forbids subsetting, and a whole font is not embedded in web output"; + else if (!hasOpenLicense) + reason = "the name table names no open licence (nameID 13/14), so the font is treated as commercial"; + + if (reason != null) + { + LogEmbedding(logger, FontLogSeverity.Information, fontName, restriction, + FontEmbeddingDecision.Skip, reason + " (web default policy)"); + return FontEmbeddingDecision.Skip; + } + + LogEmbedding(logger, FontLogSeverity.Information, fontName, restriction, + FontEmbeddingDecision.Subset, "web default policy"); + return FontEmbeddingDecision.Subset; + } + // ----------------------------------------------------------------------------------------- // Shaper resolution — policy // ----------------------------------------------------------------------------------------- @@ -550,6 +611,59 @@ public string GetFamilyForTarget(string fontName, FontRenderTarget target) return fontName; } + /// + /// Returns the fallback chain for a font: the user-configured chain + /// () followed by the built-in chain, + /// in the order the default font resolver tries them. Names are compared case-insensitively + /// and only the first occurrence is kept. The font itself and the embedded last-resort font + /// are not included. Returns an empty array when no chain is known for the font. + /// + /// The chain lists names only; it does not tell which of them are installed. + /// + public string[] GetFallbackChain(string fontName) + { + ThrowIfDisposed(); + if (string.IsNullOrEmpty(fontName)) + return new string[0]; + + var result = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase) { fontName }; + + AddChain(result, seen, _configuration.GetFallbacks(fontName)); + AddChain(result, seen, BuiltinFontFallbackChains.GetFallbacks(fontName)); + + return result.ToArray(); + } + + private static void AddChain(List result, HashSet seen, string[] chain) + { + if (chain == null) + return; + + foreach (var name in chain) + { + if (string.IsNullOrEmpty(name)) + continue; + if (seen.Add(name)) + result.Add(name); + } + } + + /// + /// Returns the CSS generic family (sans-serif, serif or monospace) of the font that + /// resolves for the given name, which is the font text in that + /// family is measured with. See for the rules. + /// Returns when nothing resolves. + /// + public GenericFontFamily GetGenericFamily(string fontName, FontSubFamily subFamily = FontSubFamily.Regular) + { + ThrowIfDisposed(); + if (string.IsNullOrEmpty(fontName)) + return GenericFontFamily.SansSerif; + + return GenericFontFamilyClassifier.Classify(LoadFont(fontName, subFamily)); + } + // ----------------------------------------------------------------------------------------- // Logging // ----------------------------------------------------------------------------------------- diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFontSerializer.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFontSerializer.cs index b49fc02a58..966d764c92 100644 --- a/src/EPPlus.Fonts.OpenType/OpenTypeFontSerializer.cs +++ b/src/EPPlus.Fonts.OpenType/OpenTypeFontSerializer.cs @@ -32,7 +32,7 @@ public byte[] Serialize() using (var stream = new MemoryStream()) using (var writer = new FontsBinaryWriter(stream)) { - var sortedTags = _font.TableRecords.Keys.OrderBy(k => k).ToList(); + var sortedTags = _font.TableRecords.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(); int numTables = sortedTags.Count; // 1. First pass: serialize all tables to get their actual bytes diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs b/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs index 3a1f9b5715..5bd9c700b9 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/FontSubsettingContext.cs @@ -37,6 +37,12 @@ public class FontSubsettingContext public Dictionary GlyphIdMap { get; } = new Dictionary(); internal GposSubsetProcessor GposProcessor { get; set; } + /// + /// True when the subset is created without TrueType hinting, see . + /// Read by the processors that write glyf, maxp, head and the hinting tables. + /// + internal bool RemoveHinting { get; set; } + /// /// Creates a new subsetting context and initializes all collections. /// diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/GlyphAndLocaSubsetProcessor.cs b/src/EPPlus.Fonts.OpenType/Subsetting/GlyphAndLocaSubsetProcessor.cs index ed6bae3a58..6b84cb7296 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/GlyphAndLocaSubsetProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/GlyphAndLocaSubsetProcessor.cs @@ -52,7 +52,7 @@ public void Rewrite(FontSubsettingContext context) } else { - newGlyphs.Add(CloneGlyphWithRemappedComponents(originalGlyph, context.OldToNewGlyphId)); + newGlyphs.Add(CloneGlyphWithRemappedComponents(originalGlyph, context.OldToNewGlyphId, context.RemoveHinting)); } } @@ -95,7 +95,13 @@ private static bool IsEmpty(Glyph g) return g.Header.numberOfContours == 0 && g.CompositeData == null && g.SimpleData == null; } - private static Glyph CloneGlyphWithRemappedComponents(Glyph original, Dictionary oldToNewMap) + /// + /// Clones a glyph with its component glyph IDs remapped to the subset. With removeHinting the + /// glyph is written without instructions: a simple glyph gets an empty instruction array, and a + /// composite glyph loses its instructions and the WE_HAVE_INSTRUCTIONS flag on its components, + /// so nothing calls into the fpgm and cvt tables that an unhinted subset leaves out. + /// + private static Glyph CloneGlyphWithRemappedComponents(Glyph original, Dictionary oldToNewMap, bool removeHinting) { GlyphHeader header = new GlyphHeader(original.Header.numberOfContours, original.Header.Bounds); @@ -105,7 +111,7 @@ private static Glyph CloneGlyphWithRemappedComponents(Glyph original, Dictionary SimpleGlyph simple = new SimpleGlyph { EndPtsOfContours = (ushort[])original.SimpleData.EndPtsOfContours.Clone(), - Instructions = (byte[])original.SimpleData.Instructions.Clone(), + Instructions = removeHinting ? new byte[0] : (byte[])original.SimpleData.Instructions.Clone(), XBytes = (byte[])original.SimpleData.XBytes.Clone(), YBytes = (byte[])original.SimpleData.YBytes.Clone(), FlagRuns = new List() @@ -124,7 +130,7 @@ private static Glyph CloneGlyphWithRemappedComponents(Glyph original, Dictionary { CompositeGlyph composite = new CompositeGlyph { - Instructions = (byte[])original.CompositeData.Instructions.Clone(), + Instructions = removeHinting ? new byte[0] : (byte[])original.CompositeData.Instructions.Clone(), Components = new List() }; @@ -136,9 +142,14 @@ private static Glyph CloneGlyphWithRemappedComponents(Glyph original, Dictionary newGid = 0; // Fallback to .notdef } + // The flag belongs on the last component; it is cleared on all of them, which is harmless. + var flags = removeHinting + ? comp.Flags & ~CompositeGlyphFlags.WE_HAVE_INSTRUCTIONS + : comp.Flags; + composite.Components.Add(new GlyphComponent { - Flags = comp.Flags, + Flags = flags, GlyphIndex = newGid, Argument1 = comp.Argument1, Argument2 = comp.Argument2, diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/MaxpSubsetProcessor.cs b/src/EPPlus.Fonts.OpenType/Subsetting/MaxpSubsetProcessor.cs index 58bd5e5c96..559cb8e797 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/MaxpSubsetProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/MaxpSubsetProcessor.cs @@ -21,12 +21,25 @@ public void Discover(FontSubsettingContext context) public void Rewrite(FontSubsettingContext context) { - var original = context.OriginalFont.MaxpTable; if (original == null) return; var maxp = original.Clone(); maxp.numGlyphs = (ushort)context.NewToOldGlyphId.Count; + + if (context.RemoveHinting) + { + // No instructions remain, so nothing is reserved for them. maxZones is 1 rather than 0: + // 1 means no twilight zone, and 0 is not a valid value. + maxp.maxZones = 1; + maxp.maxTwilightPoints = 0; + maxp.maxStorage = 0; + maxp.maxFunctionDefs = 0; + maxp.maxInstructionDefs = 0; + maxp.maxStackElements = 0; + maxp.maxSizeOfInstructions = 0; + } + context.SubsetFont.AddOrReplaceTable(maxp); } } diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/PassThroughTableSubsetProcessor.cs b/src/EPPlus.Fonts.OpenType/Subsetting/PassThroughTableSubsetProcessor.cs new file mode 100644 index 0000000000..0b2b8fa417 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Subsetting/PassThroughTableSubsetProcessor.cs @@ -0,0 +1,65 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/17/2026 EPPlus Software AB Pass-through of hinting tables + 11/23/2026 EPPlus Software AB Hinting tables left out of unhinted subsets + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables; + +namespace EPPlus.Fonts.OpenType.Subsetting.Processors +{ + /// + /// Copies tables that do not reference glyph IDs unchanged from the original font to the subset. + /// Glyph instructions in 'glyf' call functions in 'fpgm' and read values from 'cvt ', so these + /// tables must be kept for the hinted glyphs to execute correctly in rasterizers and pass OTS. + /// In an unhinted subset () the glyphs have no + /// instructions, so only 'gasp' is copied; its grid-fitting flags then have no effect. + /// Tables missing in the original are not added. + /// + internal class PassThroughTableSubsetProcessor : IFontSubsetProcessor + { + private static readonly string[] PassThroughTags = new string[] + { + TableNames.Cvt, + TableNames.Fpgm, + TableNames.Prep, + TableNames.Gasp + }; + + public void Discover(FontSubsettingContext context) + { + // No glyph dependencies + } + + public void Rewrite(FontSubsettingContext context) + { + var original = context.OriginalFont; + foreach (var tag in PassThroughTags) + { + if (context.RemoveHinting && IsHintingProgramTable(tag)) + continue; + + if (!original.TableRecords.ContainsKey(tag)) + continue; + + var data = original.GetTableData(tag); + if (data == null) + continue; + + context.SubsetFont.AddOrReplaceTable(new RawFontTable(tag, data)); + } + } + + private static bool IsHintingProgramTable(string tag) + { + return tag == TableNames.Cvt || tag == TableNames.Fpgm || tag == TableNames.Prep; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs index 9cd9806b58..6dba1d5d73 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs @@ -43,15 +43,28 @@ internal class SubsetFontBuilder new VmtxSubsetProcessor(), new Os2SubsetProcessor(), new PostSubsetProcessor(), - new KernSubsetProcessor() + new KernSubsetProcessor(), + new PassThroughTableSubsetProcessor() // cvt, fpgm, prep, gasp - copied unchanged; only gasp when hinting is removed }; /// /// Creates a new containing only the necessary data for the specified characters. /// public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable unicodeChars) + { + return CreateSubset(originalFont, unicodeChars, false); + } + + /// + /// Creates a new containing only the necessary data for the specified characters. + /// + /// The font to subset. + /// The code points the subset must contain. + /// True to create an unhinted subset, see . + public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable unicodeChars, bool removeHinting) { var context = new FontSubsettingContext(originalFont, unicodeChars); + context.RemoveHinting = removeHinting; 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 new file mode 100644 index 0000000000..6bc430deab --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetOptions.cs @@ -0,0 +1,35 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/23/2026 EPPlus Software AB Unhinted subsets for web output + *************************************************************************************************/ +namespace EPPlus.Fonts.OpenType.Subsetting +{ + /// + /// Options for creating a font subset. + /// + internal sealed class SubsetOptions + { + /// + /// Prefixes the names of the subset with a six-letter subset tag, e.g. "ABCDEF+Roboto". + /// + internal bool AddSubsetTag { get; set; } + + /// + /// Removes TrueType hinting so the subset is a valid unhinted font: the hinting tables + /// (cvt, fpgm, prep), the instructions of every glyph, and the hinting limits in maxp. + /// Meant for web output, where browsers on most platforms ignore hinting and text is laid out + /// with geometric precision and a fixed textLength. False keeps hinting, as PDF export does. + /// The tables and the glyph instructions are always removed together: instructions that call + /// functions in a missing fpgm make the font invalid. + /// + internal bool RemoveHinting { get; set; } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetPostProcessor.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetPostProcessor.cs index 580ff88f88..5762849f46 100644 --- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetPostProcessor.cs +++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetPostProcessor.cs @@ -25,7 +25,7 @@ public void PostProcessSubset(OpenTypeFont font) { // 1) Sort table records by tag (spec requires directory sorted alphabetically) var sortedRecords = font.TableRecords - .OrderBy(r => r.Key) + .OrderBy(r => r.Key, StringComparer.Ordinal) .Select(r => r.Value) .ToList(); diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/WebFontFace.cs b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontFace.cs new file mode 100644 index 0000000000..59d46b3af2 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontFace.cs @@ -0,0 +1,73 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Web font subsetting for SVG export + *************************************************************************************************/ +using OfficeOpenXml.Interfaces.Fonts; + +namespace EPPlus.Fonts.OpenType.Subsetting +{ + /// + /// One subsetted font to declare with @font-face in web output (SVG/HTML). + /// + public sealed class WebFontFace + { + internal WebFontFace(string familyName, string sourceFamily, FontSubFamily subFamily, byte[] fontData) + { + FamilyName = familyName; + SourceFamily = sourceFamily; + SubFamily = subFamily; + FontData = fontData; + } + + /// + /// The CSS family name of the subset, e.g. "ABCDEF+Carlito". The prefix is derived from the + /// font and the code points in the subset, so the name is unique per subset: an inline SVG's + /// @font-face applies to the whole HTML document. Two identical subsets get the same name and + /// the same data, which is harmless. + /// + public string FamilyName { get; private set; } + + /// + /// The family of the font the subset was made from, e.g. "Carlito". + /// + public string SourceFamily { get; private set; } + + /// + /// The subfamily of the font the subset was made from. + /// + public FontSubFamily SubFamily { get; private set; } + + /// + /// The CSS font-weight descriptor: 700 for bold subfamilies, otherwise 400. Declaring it keeps + /// the browser from synthesizing bold on top of glyphs that are already bold. + /// + public int FontWeight + { + get + { + return SubFamily == FontSubFamily.Bold || SubFamily == FontSubFamily.BoldItalic ? 700 : 400; + } + } + + /// + /// True for italic subfamilies; the CSS font-style descriptor is then "italic", otherwise "normal". + /// + public bool IsItalic + { + get { return SubFamily == FontSubFamily.Italic || SubFamily == FontSubFamily.BoldItalic; } + } + + /// + /// The subset as a TrueType font file. + /// + public byte[] FontData { get; private set; } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/WebFontPlan.cs b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontPlan.cs new file mode 100644 index 0000000000..0344f8e8be --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontPlan.cs @@ -0,0 +1,104 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Web font subsetting for SVG export + *************************************************************************************************/ +using OfficeOpenXml.Interfaces.Fonts; +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.Subsetting +{ + /// + /// The result of : the subsets to declare with @font-face + /// and the font-family stack for every font that was added. + /// + public sealed class WebFontPlan + { + private readonly Dictionary _stacks; + + internal WebFontPlan(List faces, Dictionary stacks) + { + Faces = faces.AsReadOnly(); + _stacks = stacks; + } + + /// + /// The subsets to declare with @font-face, each once, in the order they were first needed. + /// + public IReadOnlyList Faces { get; private set; } + + /// + /// The family names of the font-family stack for a font added with + /// , in order and without quotes. Subset names + /// () and installed family names are mixed; the generic + /// family is not included, see . Returns null for a font that + /// was never added. The family name is matched case-insensitively. + /// + public IReadOnlyList GetFamilyNames(string family, FontSubFamily subFamily) + { + Stack stack; + return _stacks.TryGetValue(WebFontSubsetPlanner.RequestKey(family, subFamily), out stack) + ? stack.Names + : null; + } + + /// + /// The family names of the font-family stack to draw one code point of a font added with + /// with. A code point that measurement routed to a + /// glyph fallback written by name gets a stack that starts with that fallback, so the browser + /// does not draw it with another font earlier in the font's stack. Every other code point gets + /// the font's stack (). Code points that share + /// a stack get the same list instance, so text can be split where the instance changes. + /// Returns null for a font that was never added. + /// + public IReadOnlyList GetFamilyNames(string family, FontSubFamily subFamily, int codePoint) + { + Stack stack; + if (!_stacks.TryGetValue(WebFontSubsetPlanner.RequestKey(family, subFamily), out stack)) + return null; + + IReadOnlyList names; + if (stack.CodePointStacks != null && stack.CodePointStacks.TryGetValue(codePoint, out names)) + return names; + return stack.Names; + } + + /// + /// The generic family that ends the font-family stack for a font added with + /// . for + /// a font that was never added. + /// + public GenericFontFamily GetGenericFamily(string family, FontSubFamily subFamily) + { + Stack stack; + return _stacks.TryGetValue(WebFontSubsetPlanner.RequestKey(family, subFamily), out stack) + ? stack.Generic + : GenericFontFamily.SansSerif; + } + + internal sealed class Stack + { + internal Stack(List names, GenericFontFamily generic, Dictionary> codePointStacks) + { + Names = names.AsReadOnly(); + Generic = generic; + CodePointStacks = codePointStacks; + } + + internal IReadOnlyList Names { get; private set; } + internal GenericFontFamily Generic { get; private set; } + + /// + /// Stacks for code points routed to glyph fallbacks written by name. Null when there are none. + /// + internal Dictionary> CodePointStacks { get; private set; } + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/WebFontSubsetPlanner.cs b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontSubsetPlanner.cs new file mode 100644 index 0000000000..f4aaab3720 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Subsetting/WebFontSubsetPlanner.cs @@ -0,0 +1,660 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Web font subsetting for SVG export + *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Integration; +using EPPlus.Fonts.OpenType.Logging; +using EPPlus.Fonts.OpenType.Scanner; +using EPPlus.Fonts.OpenType.Utils; +using OfficeOpenXml.Interfaces.Fonts; +using System; +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.Subsetting +{ + /// + /// Plans the fonts embedded in web output (SVG/HTML): which subsets to declare with @font-face, + /// and the font-family stack for each font the text was measured with. + /// + /// For every added font R (the measured family) the planner finds the font M that measurement + /// used, routes each code point with exactly as measurement + /// does, decides per font whether it may be embedded (web policy and OnFontEmbedding callback), + /// and subsets every embedded font once with the union of the code points routed to it. + /// + /// The stack for R: + /// M may be embedded: subset(M), glyph fallbacks, R, R's fallback chain + /// M may not be embedded: M, subset(S), glyph fallbacks, R, R's fallback chain + /// followed by a generic family (). S is a safety net + /// carrying the code points routed to M: the first font of R's chain that is installed and may be + /// embedded, otherwise the bundled Archivo Narrow. Archivo Narrow is never written by name, since + /// browsers do not have it; it is only used embedded. + /// + /// A font is not embedded when the policy skips it, when it has CFF outlines, when the policy or + /// callback asks for the whole font (whole fonts are never embedded in web output), or when + /// subsetting it fails. When measurement used serialized metrics because R is not installed, + /// M is R itself and is written by name. + /// + /// Glyph fallbacks are the fonts the provider routed code points to, in priority order (Noto + /// Emoji, Noto Math, then script fonts). A fallback that may not be embedded is written by name, + /// without a safety net, followed by the other fonts of its script's fallback chain so a viewer + /// without it still gets a font for the script. Code points that no font has are left out of + /// every subset; the browser picks a system font for them. + /// + /// A browser walks the stack per character and takes the first font that has it, which for fonts + /// written by name need not be the font measurement used: a Chinese font early in the stack may + /// also have the kana that were measured with a Japanese font. Code points routed to a fallback + /// written by name therefore get a stack of their own that starts with that fallback, see + /// . Embedded subsets need + /// no such stack: a subset only has the code points routed to it. + /// + /// A planner created with embedFonts false embeds nothing: every font is written by name, there is + /// no safety net, and the stack starts with R rather than M. Stacks and the stacks per code point + /// are planned the same way, so text can still be split where measurement used a glyph fallback. + /// + /// + /// One instance plans one output. Not thread-safe. + /// + public sealed class WebFontSubsetPlanner + { + private const string LastResortFamily = "Archivo Narrow"; + private readonly OpenTypeFontEngine _engine; + private readonly bool _embedFonts; + private readonly List _requests = new List(); + private readonly Dictionary _requestByKey = new Dictionary(StringComparer.Ordinal); + + // Whether a font may be embedded, cached per font so the OnFontEmbedding callback runs once per font. + private readonly Dictionary _embeddable = new Dictionary(); + private readonly HashSet _subsetFailed = new HashSet(); + private bool _built; + + /// + /// Creates a planner that embeds the fonts the web policy and the OnFontEmbedding callback allow. + /// + public WebFontSubsetPlanner(OpenTypeFontEngine engine) + : this(engine, true) + { + } + + /// + /// Creates a planner. + /// + /// The engine the text was measured with. + /// + /// False to embed nothing and write every font by name. The embedding policy and the + /// OnFontEmbedding callback are then never consulted. + /// + public WebFontSubsetPlanner(OpenTypeFontEngine engine, bool embedFonts) + { + if (engine == null) + throw new ArgumentNullException("engine"); + _engine = engine; + _embedFonts = embedFonts; + } + + /// + /// Adds text measured with the given family and subfamily. Call once per text run; text for the + /// same font is collected. An empty text only registers the font, so it still gets a stack + /// (for instance a paragraph's default font, which has no text of its own). + /// + /// The family the text was measured with (after any web font substitution). + /// The subfamily the text was measured with. + /// The text, or null or empty to only register the font. + public void AddText(string family, FontSubFamily subFamily, string text) + { + if (_built) + throw new InvalidOperationException("Cannot add text after Build()."); + if (string.IsNullOrEmpty(family)) + throw new ArgumentException("A family name is required.", "family"); + + var key = RequestKey(family, subFamily); + Request request; + if (!_requestByKey.TryGetValue(key, out request)) + { + request = new Request(family, subFamily); + _requestByKey.Add(key, request); + _requests.Add(request); + } + + if (string.IsNullOrEmpty(text)) + return; + + foreach (var cp in CodePointUtil.ExtractCodePoints(text)) + request.CodePoints.Add(cp); + } + + /// + /// Routes, decides and subsets. Can be called once. + /// + /// + /// Routes, decides and subsets. Can be called once. + /// + public WebFontPlan Build() + { + if (_built) + throw new InvalidOperationException("Build() can only be called once."); + _built = true; + + foreach (var request in _requests) + Route(request); + + // A failed subset marks its font as not embeddable and reruns the assignment, so a failed + // primary is written by name followed by a safety net (ultimately the bundled Archivo + // Narrow), and a failed glyph fallback is written by name. The loop ends: a font that + // failed is never assigned again, and there are finitely many fonts. When it ends, every + // font the assignment embeds has a subset. + while (true) + { + var assignment = Assign(); + var failed = new List(); + var faces = SubsetAll(assignment, failed); + + if (failed.Count == 0) + return Compose(assignment, faces); + + foreach (var id in failed) + _subsetFailed.Add(id); + } + } + + internal static string RequestKey(string family, FontSubFamily subFamily) + { + return (family ?? string.Empty).ToUpperInvariant() + "|" + (int)subFamily; + } + + // ----------------------------------------------------------------------------------------- + // Routing: which font each code point is drawn with, as measurement routes it + // ----------------------------------------------------------------------------------------- + + private void Route(Request request) + { + // Measurement uses serialized metrics, not a font file, when R is not installed and + // resolution fell through to the last-resort font. M is then R itself. + var shaper = _engine.GetMeasurementShaper(request.Family, request.SubFamily); + request.MeasuredFromMetrics = shaper == null || !shaper.HasGlyphIds; + + // Routing needs a real font even when measurement used metrics: the code points that + // stay with the primary are the ones M (or its safety net) must carry. + request.Primary = _engine.LoadFont(request.Family, request.SubFamily); + if (request.Primary == null) + { + request.PrimaryCodePoints.UnionWith(request.CodePoints); + return; + } + + var provider = new DefaultFontProvider(_engine, request.Primary); + var sorted = new List(request.CodePoints); + sorted.Sort(); + + foreach (var cp in sorted) + { + OpenTypeFont dest; + ushort glyphId; + if (!provider.TryGetGlyphFont((uint)cp, out dest, out glyphId)) + continue; // no font has it + + if (ReferenceEquals(dest, request.Primary)) + { + request.PrimaryCodePoints.Add(cp); + continue; + } + + var id = IdentityOf(dest); + Fallback fallback; + if (!request.FallbackById.TryGetValue(id, out fallback)) + { + fallback = new Fallback(dest, id, Rank(cp), cp); + request.FallbackById.Add(id, fallback); + request.Fallbacks.Add(fallback); + } + fallback.CodePoints.Add(cp); + var script = UnicodeScriptClassifier.OfCodePoint((uint)cp); + if (!fallback.Scripts.Contains(script)) + fallback.Scripts.Add(script); + } + + // Priority order of the provider: emoji, math, then script fonts. + request.Fallbacks.Sort((a, b) => + a.Rank != b.Rank ? a.Rank.CompareTo(b.Rank) : a.FirstCodePoint.CompareTo(b.FirstCodePoint)); + } + + private static int Rank(int codePoint) + { + switch (UnicodeScriptClassifier.OfCodePoint((uint)codePoint)) + { + case UnicodeScript.Emoji: + return 0; + case UnicodeScript.Math: + return 1; + default: + return 2; + } + } + + // ----------------------------------------------------------------------------------------- + // Assignment: which fonts are embedded and which code points each subset carries + // ----------------------------------------------------------------------------------------- + + private Assignment Assign() + { + var assignment = new Assignment(); + + foreach (var request in _requests) + { + var slot = new Slot(request); + + if (_embedFonts && !request.MeasuredFromMetrics && request.Primary != null && CanEmbed(request.Primary)) + { + slot.PrimaryFace = IdentityOf(request.Primary); + assignment.Add(request.Primary, request.PrimaryCodePoints); + + if (IsLastResort(request.Primary.GetEnglishFontFamilyName()) && !IsLastResort(request.Family)) + { + LogWarning(request.Family, LastResortFamily, string.Format( + "'{0}' {1} and its fallback chain are not installed; the text was measured with the last-resort font '{2}', which is embedded in the web output.", + request.Family, request.SubFamily, LastResortFamily)); + } + } + else + { + // Without embedding the requested family comes first, as the fonts are made + // available by other means; the font measurement resolved to follows in its chain. + slot.PrimaryName = !_embedFonts || request.MeasuredFromMetrics || request.Primary == null + ? request.Family + : request.Primary.GetEnglishFontFamilyName(); + + var safetyNet = _embedFonts ? FindSafetyNet(request) : null; + if (safetyNet != null) + { + slot.SafetyNet = safetyNet; + assignment.Add(safetyNet, request.PrimaryCodePoints); + } + } + + foreach (var fallback in request.Fallbacks) + { + if (_embedFonts && CanEmbed(fallback.Font)) + { + slot.Fallbacks.Add(new StackEntry(fallback, fallback.Id, null)); + assignment.Add(fallback.Font, fallback.CodePoints); + } + else + { + slot.Fallbacks.Add(new StackEntry(fallback, null, fallback.Font.GetEnglishFontFamilyName())); + } + } + + assignment.Slots.Add(slot); + } + + return assignment; + } + + /// + /// The first font of R's fallback chain that is installed and may be embedded, otherwise the + /// bundled Archivo Narrow. Null only if Archivo Narrow cannot be embedded either. + /// + private OpenTypeFont FindSafetyNet(Request request) + { + foreach (var name in _engine.GetFallbackChain(request.Family)) + { + if (_engine.GetFontAvailability(name, request.SubFamily) != FontAvailability.Exact) + continue; + + var candidate = _engine.LoadFont(name, request.SubFamily); + if (candidate != null && CanEmbed(candidate)) + return candidate; + } + + var lastResort = EmbeddedFonts.LoadArchivoNarrow(request.SubFamily); + if (CanEmbed(lastResort)) + { + LogWarning(request.Family, LastResortFamily, string.Format( + "'{0}' {1} may not be embedded and no font in its fallback chain is installed and embeddable; '{2}' is embedded as the safety net.", + request.Family, request.SubFamily, LastResortFamily)); + return lastResort; + } + return null; + } + + private bool CanEmbed(OpenTypeFont font) + { + var id = IdentityOf(font); + if (_subsetFailed.Contains(id)) + return false; + + bool embeddable; + if (_embeddable.TryGetValue(id, out embeddable)) + return embeddable; + + if (font.Format != FontFormat.Ttf) + { + LogInformation(id.Family, string.Format( + "'{0}' {1} has CFF outlines, which are not subsetted for web output; it is referenced by name.", + id.Family, id.SubFamily)); + embeddable = false; + } + else + { + var decision = _engine.ResolveEmbeddingDecision(font, FontRenderTarget.Web); + if (decision == FontEmbeddingDecision.EmbedWhole) + { + LogInformation(id.Family, string.Format( + "'{0}' {1}: EmbedWhole was requested, but whole fonts are never embedded in web output; it is referenced by name. Return Subset from OnFontEmbedding to embed it.", + id.Family, id.SubFamily)); + } + embeddable = decision == FontEmbeddingDecision.Subset; + } + + _embeddable[id] = embeddable; + return embeddable; + } + + // ----------------------------------------------------------------------------------------- + // Subsetting + // ----------------------------------------------------------------------------------------- + + private Dictionary SubsetAll(Assignment assignment, List failed) + { + var faces = new Dictionary(); + + foreach (var id in assignment.Order) + { + var font = assignment.FontById[id]; + var codePoints = assignment.CodePointsById[id]; + + try + { + // Web subsets are unhinted: browsers on most platforms ignore TrueType hinting, text is + // laid out with geometric precision and a fixed textLength, and the hinting programs + // are often the largest part of a small subset. + var subset = font.CreateSubset(CodePointUtil.CodePointsToString(codePoints), + new SubsetOptions { AddSubsetTag = true, RemoveHinting = true }); + var data = subset.Serialize(); + var familyName = SubsetTag.Create(id, codePoints) + id.Family; + faces.Add(id, new WebFontFace(familyName, id.Family, id.SubFamily, data)); + } + catch (Exception ex) + { + LogWarning(id.Family, null, string.Format( + "Subsetting '{0}' {1} for web output failed ({2}: {3}); it is referenced by name instead.", + id.Family, id.SubFamily, ex.GetType().Name, ex.Message)); + failed.Add(id); + } + } + + return faces; + } + + // ----------------------------------------------------------------------------------------- + // Stacks + // ----------------------------------------------------------------------------------------- + + private WebFontPlan Compose(Assignment assignment, Dictionary faces) + { + var stacks = new Dictionary(StringComparer.Ordinal); + + foreach (var slot in assignment.Slots) + { + var request = slot.Request; + var names = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + if (slot.PrimaryFace.HasValue) + { + AddFace(names, seen, faces, slot.PrimaryFace.Value); + } + else + { + AddName(names, seen, slot.PrimaryName); + if (slot.SafetyNet != null) + AddFace(names, seen, faces, IdentityOf(slot.SafetyNet)); + } + + var byName = new List(); + foreach (var entry in slot.Fallbacks) + { + if (entry.Face.HasValue) + { + AddFace(names, seen, faces, entry.Face.Value); + } + else + { + AddName(names, seen, entry.Name); + AddScriptChains(names, seen, entry.Source); + byName.Add(entry); + } + } + + AddName(names, seen, request.Family); + foreach (var name in _engine.GetFallbackChain(request.Family)) + AddName(names, seen, name); + + stacks[RequestKey(request.Family, request.SubFamily)] = + new WebFontPlan.Stack(names, GetGenericFamily(slot), ComposeCodePointStacks(byName, names)); + } + + var orderedFaces = new List(); + foreach (var id in assignment.Order) + { + WebFontFace face; + if (faces.TryGetValue(id, out face)) + orderedFaces.Add(face); + } + + return new WebFontPlan(orderedFaces, stacks); + } + + /// + /// Stacks for code points routed to fallbacks written by name: the fallback, the rest of its + /// scripts' fallback chains, then the font's own stack. Null when there are none. + /// + private Dictionary> ComposeCodePointStacks(List byName, List fontStack) + { + if (byName.Count == 0) + return null; + + var result = new Dictionary>(); + foreach (var entry in byName) + { + var names = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + AddName(names, seen, entry.Name); + AddScriptChains(names, seen, entry.Source); + foreach (var name in fontStack) + AddName(names, seen, name); + + var stack = names.AsReadOnly(); + foreach (var cp in entry.Source.CodePoints) + result[cp] = stack; + } + return result; + } + + /// + /// Adds the configured fallback chain of every script the fallback was used for. + /// + private void AddScriptChains(List names, HashSet seen, Fallback fallback) + { + foreach (var script in fallback.Scripts) + { + var chain = _engine.FontStore.GetScriptFallback(script); + if (chain == null) + continue; + foreach (var name in chain) + AddName(names, seen, name); + } + } + + /// + /// The generic family of the font M stands for. When M is R itself (measured from metrics), + /// the safety net from R's chain represents it, being a metric-compatible substitute, or, + /// without a safety net, the font R resolves to. + /// + private static GenericFontFamily GetGenericFamily(Slot slot) + { + var request = slot.Request; + if (!request.MeasuredFromMetrics && request.Primary != null) + return GenericFontFamilyClassifier.Classify(request.Primary); + + if (slot.SafetyNet != null && !IsLastResort(slot.SafetyNet.GetEnglishFontFamilyName())) + return GenericFontFamilyClassifier.Classify(slot.SafetyNet); + + // Without a safety net (fonts are not embedded), the font R resolves to stands for it. + if (request.Primary != null && !IsLastResort(request.Primary.GetEnglishFontFamilyName())) + return GenericFontFamilyClassifier.Classify(request.Primary); + + return GenericFontFamily.SansSerif; + } + + private static void AddFace(List names, HashSet seen, Dictionary faces, FontKey id) + { + WebFontFace face; + if (faces.TryGetValue(id, out face) && seen.Add(face.FamilyName)) + names.Add(face.FamilyName); + } + + private static void AddName(List names, HashSet seen, string name) + { + // Archivo Narrow is only ever used embedded: browsers do not have it installed. + if (string.IsNullOrEmpty(name) || IsLastResort(name)) + return; + if (seen.Add(name)) + names.Add(name); + } + + // ----------------------------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------------------------- + + private static FontKey IdentityOf(OpenTypeFont font) + { + return new FontKey(font.GetEnglishFontFamilyName(), font.NameTable.GetSubfamilyEnum()); + } + + private static bool IsLastResort(string family) + { + return string.Equals(LastResortFamily, family, StringComparison.OrdinalIgnoreCase); + } + + private void LogWarning(string requested, string resolved, string message) + { + var logger = _engine.Logger; + if (FontLog.IsEnabled(logger, FontLogSeverity.Warning)) + FontLog.Write(logger, FontLogSeverity.Warning, FontLogEventType.EmbeddingDecision, message, requested, resolved); + } + + private void LogInformation(string requested, string message) + { + var logger = _engine.Logger; + if (FontLog.IsEnabled(logger, FontLogSeverity.Information)) + FontLog.Write(logger, FontLogSeverity.Information, FontLogEventType.EmbeddingDecision, message, requested, null); + } + + // ----------------------------------------------------------------------------------------- + // Working data + // ----------------------------------------------------------------------------------------- + + private sealed class Request + { + internal Request(string family, FontSubFamily subFamily) + { + Family = family; + SubFamily = subFamily; + } + + internal string Family { get; private set; } + internal FontSubFamily SubFamily { get; private set; } + internal HashSet CodePoints { get; } = new HashSet(); + + internal bool MeasuredFromMetrics { get; set; } + internal OpenTypeFont Primary { get; set; } + internal HashSet PrimaryCodePoints { get; } = new HashSet(); + internal List Fallbacks { get; } = new List(); + internal Dictionary FallbackById { get; } = new Dictionary(); + } + + private sealed class Fallback + { + internal Fallback(OpenTypeFont font, FontKey id, int rank, int firstCodePoint) + { + Font = font; + Id = id; + Rank = rank; + FirstCodePoint = firstCodePoint; + } + + internal OpenTypeFont Font { get; private set; } + internal FontKey Id { get; private set; } + internal int Rank { get; private set; } + internal int FirstCodePoint { get; private set; } + internal HashSet CodePoints { get; } = new HashSet(); + + /// The scripts of the code points routed to the font, in the order first met. + internal List Scripts { get; } = new List(); + } + + private sealed class Assignment + { + internal List Slots { get; } = new List(); + internal List Order { get; } = new List(); + internal Dictionary FontById { get; } = new Dictionary(); + internal Dictionary> CodePointsById { get; } = new Dictionary>(); + + /// Adds code points to a font's subset. A font without code points gets no subset. + internal void Add(OpenTypeFont font, HashSet codePoints) + { + if (codePoints == null || codePoints.Count == 0) + return; + + var id = IdentityOf(font); + HashSet set; + if (!CodePointsById.TryGetValue(id, out set)) + { + set = new HashSet(); + CodePointsById.Add(id, set); + FontById.Add(id, font); + Order.Add(id); + } + set.UnionWith(codePoints); + } + } + + private sealed class Slot + { + internal Slot(Request request) + { + Request = request; + } + + internal Request Request { get; private set; } + internal FontKey? PrimaryFace { get; set; } + internal string PrimaryName { get; set; } + internal OpenTypeFont SafetyNet { get; set; } + internal List Fallbacks { get; } = new List(); + } + + private sealed class StackEntry + { + internal StackEntry(Fallback source, FontKey? face, string name) + { + Source = source; + Face = face; + Name = name; + } + + /// The fallback the entry is for. + internal Fallback Source { get; private set; } + + internal FontKey? Face { get; private set; } + internal string Name { get; private set; } + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTable.cs index d1fae6dba2..d28915f30a 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTable.cs @@ -56,70 +56,65 @@ internal CmapTable() internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializationContext context) { - // Start of cmap table long tableStart = writer.BaseStream.Position; - // Write header + // Only records that actually have a subtable to write become part of the serialized table. + // A skipped record would otherwise be written with a stale offset pointing at nothing. + // The OpenType spec requires the records sorted by platform ID, then encoding ID. + // OrderBy/ThenBy is a stable sort, so records with equal keys keep their relative order. + var recordsToWrite = EncodingRecords + .Where(r => !r.IsSkipped && r.Subtable != null) + .OrderBy(r => (ushort)r.PlatformId) + .ThenBy(r => r.EncodingId) + .ToList(); + + // Header writer.WriteUInt16BigEndian(Version); - writer.WriteUInt16BigEndian((ushort)EncodingRecords.Count); + writer.WriteUInt16BigEndian((ushort)recordsToWrite.Count); - // Reserve space for encoding records + // Reserve space for the encoding records; they are written once the offsets are known long encodingRecordStart = writer.BaseStream.Position; - foreach (var _ in EncodingRecords) + for (int i = 0; i < recordsToWrite.Count; i++) { - writer.Write(new byte[8]); // placeholder + writer.Write(new byte[8]); } - // Precompute offsets for unique subtables. Deduplication is keyed by the SUBTABLE - // INSTANCE, not by SubtableOffset: for a freshly-built cmap (e.g. a subset's cmap), - // every EncodingRecord starts out with the same placeholder SubtableOffset (0), so - // keying on that value would wrongly alias two DIFFERENT subtables (e.g. a subset's - // format 4 and format 12 tables) onto the same bytes the first time this ran with two - // fresh tables sharing that placeholder. Keying by the actual object reference only - // dedups encoding records that genuinely point at the SAME subtable (e.g. (3,1) and - // (0,3) both referencing one shared Unicode BMP subtable), which is what this is for. - var subtableOffsetsMap = new Dictionary(); - var subTableStartIndex = writer.BaseStream.Position; - var encRecordsToSerialize = EncodingRecords.OrderBy(er => er.SubtableOffset); - foreach (var encRecord in encRecordsToSerialize) + // Write each unique subtable once. Deduplication is keyed by the subtable instance, not by + // SubtableOffset: in a freshly built cmap (e.g. a subset's) every record starts with the + // same placeholder offset (0), so keying on that would alias different subtables. Keying by + // reference only shares bytes between records that genuinely point at the same subtable, + // such as (0,3) and (3,1) referencing one Unicode BMP subtable. + // Subtables are written in their original offset order, so a loaded font keeps its layout. + var subtableOffsets = new Dictionary(); + foreach (var record in recordsToWrite.OrderBy(r => r.SubtableOffset)) { - // Skip any explicitly marked skipped records. Format 14 (Unicode Variation - // Sequences) subtables ARE serialized like any other format now - they used to be - // unconditionally dropped here, which silently discarded variation-sequence data - // from every embedded font. - if (encRecord.IsSkipped) + if (subtableOffsets.ContainsKey(record.Subtable)) { continue; } - uint existingOffset; - if (encRecord.Subtable != null && subtableOffsetsMap.TryGetValue(encRecord.Subtable, out existingOffset)) - { - encRecord.SubtableOffset = existingOffset; - continue; - } - var subTableBytes = encRecord.Subtable.Serialize(); - writer.Write(subTableBytes); - if (encRecord.Subtable != null) - subtableOffsetsMap[encRecord.Subtable] = (uint)subTableStartIndex; - encRecord.SubtableOffset = (uint)subTableStartIndex; - subTableStartIndex += subTableBytes.Length; + // Offsets are relative to the start of the cmap table, as the spec requires, so the + // result does not depend on where in the stream the table is written. + subtableOffsets[record.Subtable] = (uint)(writer.BaseStream.Position - tableStart); + writer.Write(record.Subtable.Serialize()); } - // Go back and write encoding records with correct offsets - long currentPos = writer.BaseStream.Position; + // Go back and write the encoding records with their final offsets + long endPosition = writer.BaseStream.Position; writer.BaseStream.Seek(encodingRecordStart, SeekOrigin.Begin); - for (int i = 0; i < EncodingRecords.Count; i++) + foreach (var record in recordsToWrite) { - var record = EncodingRecords[i]; + uint offset = subtableOffsets[record.Subtable]; + record.SubtableOffset = offset; + writer.WriteUInt16BigEndian((ushort)record.PlatformId); writer.WriteUInt16BigEndian(record.EncodingId); - writer.WriteUInt32BigEndian(record.SubtableOffset); + writer.WriteUInt32BigEndian(offset); } - // Return to end of stream - writer.BaseStream.Seek(currentPos, SeekOrigin.Begin); + // Return to the end of the table + writer.BaseStream.Seek(endPosition, SeekOrigin.Begin); } diff --git a/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/ILookupRecordContainer.cs b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/ILookupRecordContainer.cs new file mode 100644 index 0000000000..283bfb1cfd --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/ILookupRecordContainer.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; + +namespace EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups +{ + /// + /// Implemented by contextual lookup subtables (GSUB types 5/6, GPOS types 7/8) that + /// reference other lookups by index through lookup records. + /// + internal interface ILookupRecordContainer + { + /// + /// Remaps every lookup record's LookupListIndex from the original LookupList to the + /// subset LookupList. Records whose target lookup was removed are dropped: a lookup is + /// only removed when it became empty in the subset, so such a record was a no-op and + /// dropping it preserves the font's shaping behavior. + /// + void RemapLookupListIndices(Dictionary oldToNewIndexMap); + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs index 8b57abd8a4..0b0e234347 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs @@ -56,7 +56,6 @@ internal override void Serialize(FontsBinaryWriter writer) /// internal LookupRewriteResult Rewrite(FontSubsettingContext context) { - var result = new LookupRewriteResult { NewLookupList = new LookupListTable(), @@ -74,11 +73,40 @@ internal LookupRewriteResult Rewrite(FontSubsettingContext context) int newIndex = result.NewLookupList.Lookups.Count; result.NewLookupList.Lookups.Add(rewrittenLookup); result.OldToNewIndexMap[i] = newIndex; - } } + // Contextual subtables still reference lookups by their original index. The new + // lookup order is only known now, after all lookups have been rewritten. + result.NewLookupList.RemapLookupRecords(result.OldToNewIndexMap); + return result; } + + /// + /// Remaps lookup records in all contextual subtables of this list, including subtables + /// wrapped in Extension lookups. Must only be called on a rewritten (subset) list. + /// + internal void RemapLookupRecords(Dictionary oldToNewIndexMap) + { + foreach (LookupTable lookup in this.Lookups) + { + foreach (FontTableElement subTable in lookup.SubTables) + { + FontTableElement target = subTable; + ExtensionSubTableBase extension = target as ExtensionSubTableBase; + if (extension != null) + { + target = extension.ExtendedSubTable; + } + + ILookupRecordContainer container = target as ILookupRecordContainer; + if (container != null) + { + container.RemapLookupListIndices(oldToNewIndexMap); + } + } + } + } } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs index 9f0df7753f..29cb6ad5f8 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs @@ -102,7 +102,11 @@ private LookupListTable ReadLookupList(FontsBinaryReader reader, long lookupList for (int i = 0; i < lookupCount; i++) { if (lookupOffsets[i] == 0) + { + // Invalid per spec, but keep a placeholder so that feature lookup indices stay valid + lookupList.Lookups.Add(new LookupTable()); continue; + } reader.BaseStream.Position = lookupListStart + lookupOffsets[i]; var lookup = ReadLookup(reader, lookupListStart + lookupOffsets[i]); 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 aa6e4b9e17..340a2e167a 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ChainingContextualSubstFormat3.cs @@ -10,15 +10,16 @@ Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; +using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; using System; using System.Collections.Generic; using System.Linq; -using EPPlus.Fonts.OpenType.Subsetting; -using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage; namespace EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups { - public class ChainingContextualSubstFormat3 : FontTableElement + public class ChainingContextualSubstFormat3 : FontTableElement, ILookupRecordContainer { public List BacktrackCoverages { get; set; } = new(); public List InputCoverages { get; set; } = new(); @@ -76,27 +77,30 @@ private void SerializeCoverageList(FontsBinaryWriter writer, List internal ChainingContextualSubstFormat3 Rewrite(FontSubsettingContext context) { - var newTable = new ChainingContextualSubstFormat3(); + // A rule can only match if every backtrack, input and lookahead position can still be + // matched by at least one glyph in the subset. If any position lost all its glyphs, the + // rule can never fire and is dropped. Dropping only the backtrack or lookahead context + // instead would make the rule match more broadly than in the original font. + List backtrack = RewriteCoverageList(this.BacktrackCoverages, context); + if (backtrack == null) return null; - // 1. Mappa om listorna. - // Vår hjälpmetod RewriteCoverageList returnerar nu en tom lista istället för null - // om originalet var tomt/null, för att tillfredsställa Writer-koden. - newTable.BacktrackCoverages = RewriteCoverageList(this.BacktrackCoverages, context) ?? new List(); - newTable.InputCoverages = RewriteCoverageList(this.InputCoverages, context); - newTable.LookaheadCoverages = RewriteCoverageList(this.LookaheadCoverages, context) ?? new List(); + List input = RewriteCoverageList(this.InputCoverages, context); + if (input == null || input.Count == 0) return null; - // 2. Validering: Input MÅSTE finnas för att regeln ska vara giltig. - if (newTable.InputCoverages == null || newTable.InputCoverages.Count == 0) return null; + List lookahead = RewriteCoverageList(this.LookaheadCoverages, context); + if (lookahead == null) return null; - // 3. Kopiera records - if (this.SubstLookupRecords != null) - { - newTable.SubstLookupRecords = new List(this.SubstLookupRecords); - } - else - { - newTable.SubstLookupRecords = new List(); - } + var newTable = new ChainingContextualSubstFormat3(); + newTable.BacktrackCoverages = backtrack; + newTable.InputCoverages = input; + newTable.LookaheadCoverages = lookahead; + + // Lookup indices still refer to the original LookupList at this point. They are + // remapped by LookupListTable.Rewrite once the new lookup order is known. The remap + // creates new record instances, so the original font's records are never modified. + newTable.SubstLookupRecords = this.SubstLookupRecords != null + ? new List(this.SubstLookupRecords) + : new List(); return newTable; } @@ -135,5 +139,26 @@ private List RewriteCoverageList(List oldCoverages } return newCoverages; } + + void ILookupRecordContainer.RemapLookupListIndices(Dictionary oldToNewIndexMap) + { + var remapped = new List(SubstLookupRecords.Count); + foreach (SubstLookupRecord record in SubstLookupRecords) + { + int newIndex; + if (oldToNewIndexMap.TryGetValue(record.LookupListIndex, out newIndex)) + { + remapped.Add(new SubstLookupRecord + { + SequenceIndex = record.SequenceIndex, + LookupListIndex = (ushort)newIndex + }); + } + // Otherwise the target lookup became empty in the subset and was removed, so the + // record was a no-op. The subtable itself is kept even if no records remain: a + // matching rule still stops later subtables in the same lookup from being tried. + } + SubstLookupRecords = remapped; + } } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ExtensionSubstSubTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ExtensionSubstSubTable.cs index d6e06ed3bd..5de8bd4f56 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ExtensionSubstSubTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Data/Lookups/ExtensionSubstSubTable.cs @@ -22,31 +22,6 @@ namespace EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups /// public class ExtensionSubstSubTable : ExtensionSubTableBase { - /// - /// Rewrites the extension by rewriting the inner subtable. - /// - internal ExtensionSubstSubTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) - { - if (ExtendedSubTable == null) return null; - - // We delegate the rewrite to the specific type of the inner table - FontTableElement rewrittenInner = null; - - if (ExtendedSubTable is SingleSubstSubTable single) - rewrittenInner = single.Rewrite(context, oldLookup); - else if (ExtendedSubTable is LigatureSubstSubTable ligature) - rewrittenInner = ligature.Rewrite(context, oldLookup); - else if (ExtendedSubTable is ChainingContextualSubstFormat3 contextual) - rewrittenInner = contextual.Rewrite(context); - // Add more types here as they are implemented - - if (rewrittenInner == null) return null; - - return new ExtensionSubstSubTable - { - ExtensionLookupType = this.ExtensionLookupType, - ExtendedSubTable = rewrittenInner - }; - } + } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ExtensionSubstHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ExtensionSubstHandler.cs index 65eeb092d8..51df32abe6 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ExtensionSubstHandler.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ExtensionSubstHandler.cs @@ -1,60 +1,92 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - https://polyformproject.org/licenses/noncommercial/1.0.0/ - - A commercial license to use this software can be purchased at https://epplussoftware.com - ************************************************************************************************* - Date Author Change - ************************************************************************************************* - 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 - *************************************************************************************************/ -using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Subsetting; +using EPPlus.Fonts.OpenType.Tables; using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups; using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups; -using System; +using EPPlus.Fonts.OpenType.Tables.Gsub.Handlers; using System.Collections.Generic; -using System.Linq; -using System.Text; -namespace EPPlus.Fonts.OpenType.Tables.Gsub.Handlers +/// +/// Handler for GSUB Lookup Type 7: Extension Substitution. +/// +/// The loader keeps each wrapped subtable in an together +/// with its inner lookup type. This handler unwraps them into a lookup of the inner type and +/// delegates to the handler for that type. +/// +/// +/// The rewritten lookup is returned with the inner lookup type, not re-wrapped as type 7. +/// The subset is written from scratch and is small, so there is no 16 bit offset overflow +/// to avoid. This matches how ExtensionPosHandler handles GPOS type 9. +/// +/// +internal class ExtensionSubstHandler : IGsubLookupHandler { - internal class ExtensionSubstHandler : IGsubLookupHandler - { - public ushort LookupType => 7; + public ushort LookupType => 7; - public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubsetProcessor processor) + public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubsetProcessor processor) + { + LookupTable unwrapped = Unwrap(lookup); + if (unwrapped != null) { - foreach (var subTable in lookup.SubTables.OfType()) - { - // Extension-tabellen är bara en skal som pekar på den riktiga datan - if (subTable.ExtendedSubTable == null) continue; - - // Vi skapar en "fejkad" LookupTable som vi kan skicka vidare till processorn - // för att återanvända den logik vi redan har för t.ex. Typ 4. - var dummyLookup = new LookupTable - { - LookupType = subTable.ExtensionLookupType, - LookupFlag = lookup.LookupFlag, - SubTables = new List { subTable.ExtendedSubTable } - }; - - // Nu skickar vi tillbaka den inre tabellen till processorn - processor.DiscoverLookup(context, dummyLookup); - } + processor.DiscoverLookup(context, unwrapped); } + } + + public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) + { + LookupTable unwrapped = Unwrap(oldLookup); + if (unwrapped == null) return null; + + IGsubLookupHandler handler = context.GsubProcessor.GetHandler(unwrapped.LookupType); + if (handler == null) return null; + + // The inner handlers set LookupType to their own type, so the result already + // carries the inner type. + LookupTable rewritten = handler.Rewrite(context, unwrapped); + if (rewritten == null || rewritten.SubTables.Count == 0) return null; + + return rewritten; + } - public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup) + /// + /// Builds a lookup of the inner lookup type from the wrapped subtables. + /// Returns null if no wrapped subtables were loaded. + /// + private static LookupTable Unwrap(LookupTable lookup) + { + if (lookup.SubTables == null || lookup.SubTables.Count == 0) return null; + + ushort innerLookupType = 0; + List innerSubTables = new List(); + + foreach (FontTableElement subTable in lookup.SubTables) { - // För Rewrite låter vi din befintliga arkitektur sköta omskrivningen av subtabeller - var newLookup = new LookupTable { LookupType = 7, LookupFlag = oldLookup.LookupFlag, SubTables = new List() }; - foreach (var subtable in oldLookup.SubTables.OfType()) + ExtensionSubstSubTable extension = subTable as ExtensionSubstSubTable; + if (extension == null || extension.ExtendedSubTable == null) continue; + + if (innerLookupType == 0) + { + innerLookupType = extension.ExtensionLookupType; + } + else if (extension.ExtensionLookupType != innerLookupType) { - var rewritten = subtable.Rewrite(context, oldLookup); - if (rewritten != null) newLookup.SubTables.Add(rewritten); + // All subtables of a lookup must share the same type per the OpenType + // specification. Ignore mismatching ones rather than emitting a lookup + // whose type does not describe its subtables. + continue; } - return newLookup.SubTables.Count > 0 ? newLookup : null; + + innerSubTables.Add(extension.ExtendedSubTable); } + + // Type 7 can never be the inner type; guard against recursion on malformed fonts. + if (innerLookupType == 0 || innerLookupType == 7) return null; + + return new LookupTable + { + LookupType = innerLookupType, + LookupFlag = lookup.LookupFlag, + MarkFilteringSet = lookup.MarkFilteringSet, + SubTables = innerSubTables + }; } -} +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/ExtensionSubstSubTableDeserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/ExtensionSubstSubTableDeserializer.cs index 340668b37e..91ca81abf1 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/ExtensionSubstSubTableDeserializer.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/ExtensionSubstSubTableDeserializer.cs @@ -10,6 +10,7 @@ Date Author Change ************************************************************************************************* 10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 *************************************************************************************************/ +using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups; using System.IO; namespace EPPlus.Fonts.OpenType.Tables.Gsub.IO @@ -32,26 +33,45 @@ public FontTableElement Deserialize(long absoluteStart) { _reader.BaseStream.Seek(absoluteStart, SeekOrigin.Begin); - ushort format = _reader.ReadUInt16BigEndian(); // Extension format (must be 1) - ushort lookuptype = _reader.ReadUInt16BigEndian(); // The actual substitution type being extended - uint offset = _reader.ReadUInt32BigEndian(); // 32-bit offset to the actual subtable + ushort format = _reader.ReadUInt16BigEndian(); // Extension format (must be 1) + ushort extensionLookupType = _reader.ReadUInt16BigEndian(); // The wrapped substitution type + uint offset = _reader.ReadUInt32BigEndian(); // 32-bit offset to the wrapped subtable + + if (format != 1) return null; long innerSubTableAbsoluteStart = absoluteStart + offset; + FontTableElement inner; - // Redirect to the appropriate deserializer based on the encapsulated lookup type - switch (lookuptype) + switch (extensionLookupType) { case 1: - return new SingleSubstSubTableDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + inner = new SingleSubstSubTableDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + break; + case 2: + inner = new MultipleSubstSubTableDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + break; case 4: - return new LigatureSubstSubTableDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + inner = new LigatureSubstSubTableDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + break; case 6: - // Note: We will add the ChainingContextualDeserializer here once implemented - return null; + // Returns null for formats 1 and 2, which are not supported yet + inner = new ChainingContextualDeserializer(_reader).Deserialize(innerSubTableAbsoluteStart); + break; default: - // Other types can be added here as support grows - return null; + // Types 3, 5 and 8 are not supported yet. Type 7 must never be wrapped in itself. + inner = null; + break; } + + if (inner == null) return null; + + // Keep the wrapper so the inner lookup type is preserved in the model, rather than + // having to be guessed from the subtable's class later. + return new ExtensionSubstSubTable + { + ExtensionLookupType = extensionLookupType, + ExtendedSubTable = inner + }; } } } \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs index 41b0821b41..42dcf89b17 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs @@ -221,19 +221,6 @@ private static Encoding GetWindowsEncoding(ushort encodingId) } } - //private Encoding GetEncodingForRecord(NameRecord record) - //{ - // if (record.platformId == 0) - // return Encoding.GetEncoding("utf-16BE"); - - // if (record.platformId == 1) - // return Encoding.GetEncoding(10000); // MacRoman - - // if (record.platformId == 3) - // return NameTableLoader.GetWindowsEncoding(record.encodingId); - - // return Encoding.UTF8; // Fallback - //} /// /// Loads the name table from raw table bytes (used during font scanning). @@ -310,6 +297,52 @@ public void LoadFromBytes(byte[] tableBytes) } } + /// + /// Returns the licence description (nameID 13): English first, otherwise the first + /// non-empty record. Null when the font has none. + /// + public string GetLicenseDescription() + { + return GetEnglishName(NameRecordTypes.LicenseDescription) + ?? GetFirstNonEmpty(NameRecordTypes.LicenseDescription); + } + + /// + /// Returns the licence URL (nameID 14): English first, otherwise the first non-empty + /// record. Null when the font has none. + /// + public string GetLicenseInfoUrl() + { + return GetEnglishName(NameRecordTypes.LicenseInfoUrl) + ?? GetFirstNonEmpty(NameRecordTypes.LicenseInfoUrl); + } + + /// + /// True when any licence description (nameID 13) or licence URL (nameID 14) record, on + /// any platform and in any language, names one of the open licences in + /// . A font without these records is not open. + /// + public bool HasOpenLicense() + { + if (NameRecords == null) + return false; + + foreach (var record in NameRecords) + { + if (record == null) + continue; + + if (record.RecordType == NameRecordTypes.LicenseDescription + && OpenFontLicenses.IsOpenLicenseDescription(record.Name)) + return true; + + if (record.RecordType == NameRecordTypes.LicenseInfoUrl + && OpenFontLicenses.IsOpenLicenseUrl(record.Name)) + return true; + } + return false; + } + /// /// Returns the preferred Full Font Name (name ID 4) with proper language fallback. /// First tries platform-specific record without language (common default), diff --git a/src/EPPlus.Fonts.OpenType/Tables/Name/OpenFontLicenses.cs b/src/EPPlus.Fonts.OpenType/Tables/Name/OpenFontLicenses.cs new file mode 100644 index 0000000000..fef0f81f21 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Tables/Name/OpenFontLicenses.cs @@ -0,0 +1,72 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Open licence detection for web font embedding + *************************************************************************************************/ +using System; + +namespace EPPlus.Fonts.OpenType.Tables.Name +{ + /// + /// The font licences EPPlus accepts as open, so that a font under one of them may be embedded + /// as a web font without the caller confirming it. Matched as case-insensitive substrings of the + /// licence description (nameID 13) and the licence URL (nameID 14). + /// + /// Commercial fonts (Microsoft, Monotype, Adobe and fonts bought by customers) carry their own + /// licence texts, which match none of these, and are never embedded by default. + /// + internal static class OpenFontLicenses + { + /// + /// Phrases in nameID 13 that identify an open licence. + /// + internal static readonly string[] DescriptionPhrases = + { + "SIL Open Font License", + "Apache License", + "Ubuntu Font Licence", + "Ubuntu Font License", + "Bitstream Vera", + }; + + /// + /// URL fragments in nameID 14 that identify an open licence. + /// + internal static readonly string[] UrlFragments = + { + "scripts.sil.org/OFL", + "openfontlicense.org", + "apache.org/licenses", + }; + + internal static bool IsOpenLicenseDescription(string description) + { + return ContainsAny(description, DescriptionPhrases); + } + + internal static bool IsOpenLicenseUrl(string url) + { + return ContainsAny(url, UrlFragments); + } + + private static bool ContainsAny(string value, string[] candidates) + { + if (string.IsNullOrEmpty(value)) + return false; + + foreach (var candidate in candidates) + { + if (value.IndexOf(candidate, StringComparison.OrdinalIgnoreCase) >= 0) + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2Table.cs b/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2Table.cs index b7d3053e29..f88fa2edfd 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2Table.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2Table.cs @@ -74,6 +74,33 @@ public FontEmbeddingRestriction GetEmbeddingRestriction() return FontEmbeddingRestriction.None; } + /// + /// Interprets the usage-permission bits (0-3) of . When several bits are set, + /// the least restrictive one applies, as the OpenType specification prescribes. + /// Pure interpretation — carries no policy about what EPPlus does with it. + /// + public FontEmbeddingPermission GetEmbeddingPermission() + { + var usage = fsType & (FsTypeFlags)FsTypeUsageMask; + if ((usage & FsTypeFlags.Editable) != 0) + return FontEmbeddingPermission.Editable; + if ((usage & FsTypeFlags.PreviewPrint) != 0) + return FontEmbeddingPermission.PreviewAndPrint; + if ((usage & FsTypeFlags.RestrictedLicense) != 0) + return FontEmbeddingPermission.RestrictedLicense; + return FontEmbeddingPermission.Installable; + } + + /// + /// Returns true when declares that only bitmap data may be embedded, + /// which means the font's outlines must not be embedded. + /// Pure interpretation — carries no policy about what EPPlus does with it. + /// + public bool IsBitmapEmbeddingOnly() + { + return (fsType & FsTypeFlags.BitmapEmbeddingOnly) != 0; + } + /// /// The recommended horizontal size in font design units for subscripts for this font. /// @@ -250,15 +277,23 @@ internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializa writer.WriteUInt16BigEndian(usWinAscent); writer.WriteUInt16BigEndian(usWinDescent); - writer.WriteUInt32BigEndian(ulCodePageRange1); - writer.WriteUInt32BigEndian(ulCodePageRange2); + // Fields added in later versions; only write the groups that exist for this version + if (version >= 1) + { + writer.WriteUInt32BigEndian(ulCodePageRange1); + writer.WriteUInt32BigEndian(ulCodePageRange2); + } + + if (version >= 2) + { + writer.WriteInt16BigEndian(sxHeight); + writer.WriteInt16BigEndian(sCapHeight); + writer.WriteUInt16BigEndian(usDefaultChar); + writer.WriteUInt16BigEndian(usBreakChar); + writer.WriteUInt16BigEndian(usMaxContext); + } - writer.WriteInt16BigEndian(sxHeight); - writer.WriteInt16BigEndian(sCapHeight); - writer.WriteUInt16BigEndian(usDefaultChar); - writer.WriteUInt16BigEndian(usBreakChar); - writer.WriteUInt16BigEndian(usMaxContext); - if(version > 3) + if (version >= 5) { writer.WriteUInt16BigEndian(usLowerOpticalPointSize); writer.WriteUInt16BigEndian(usUpperOpticalPointSize); diff --git a/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2TableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2TableLoader.cs index 68c753b62e..97b5e961ab 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2TableLoader.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/Os2/Os2TableLoader.cs @@ -59,21 +59,39 @@ protected override Os2Table LoadInternal() var usWinAscent = _reader.ReadUInt16BigEndian(); var usWinDescent = _reader.ReadUInt16BigEndian(); - var ulCodePageRange1 = _reader.ReadUInt32BigEndian(); - var ulCodePageRange2 = _reader.ReadUInt32BigEndian(); - var sxHeight = _reader.ReadInt16BigEndian(); - var sCapHeight = _reader.ReadInt16BigEndian(); - var usDefaultChar = _reader.ReadUInt16BigEndian(); - var usBreakChar = _reader.ReadUInt16BigEndian(); - var usMaxContext = _reader.ReadUInt16BigEndian(); - ushort usLowerOpticalPointSize = default; - ushort usUpperOpticalPointSize = default; - if (version > 3) + + // Fields added in later versions. Each group is only present from the version + // that introduced it; reading it for an older version would read past the table end. + uint ulCodePageRange1 = 0; + uint ulCodePageRange2 = 0; + if (version >= 1) + { + ulCodePageRange1 = _reader.ReadUInt32BigEndian(); + ulCodePageRange2 = _reader.ReadUInt32BigEndian(); + } + + short sxHeight = 0; + short sCapHeight = 0; + ushort usDefaultChar = 0; + ushort usBreakChar = 0; + ushort usMaxContext = 0; + if (version >= 2) + { + sxHeight = _reader.ReadInt16BigEndian(); + sCapHeight = _reader.ReadInt16BigEndian(); + usDefaultChar = _reader.ReadUInt16BigEndian(); + usBreakChar = _reader.ReadUInt16BigEndian(); + usMaxContext = _reader.ReadUInt16BigEndian(); + } + + ushort usLowerOpticalPointSize = 0; + ushort usUpperOpticalPointSize = 0; + if (version >= 5) { usLowerOpticalPointSize = _reader.ReadUInt16BigEndian(); usUpperOpticalPointSize = _reader.ReadUInt16BigEndian(); } - + var table = new Os2Table @@ -117,11 +135,8 @@ protected override Os2Table LoadInternal() usBreakChar = usBreakChar, usMaxContext = usMaxContext, }; - if(table.version > 3) - { - table.usLowerOpticalPointSize = usLowerOpticalPointSize; - table.usUpperOpticalPointSize = usUpperOpticalPointSize; - } + table.usLowerOpticalPointSize = usLowerOpticalPointSize; + table.usUpperOpticalPointSize = usUpperOpticalPointSize; return table; } } diff --git a/src/EPPlus.Fonts.OpenType/Tables/RawFontTable.cs b/src/EPPlus.Fonts.OpenType/Tables/RawFontTable.cs new file mode 100644 index 0000000000..cafd3ab007 --- /dev/null +++ b/src/EPPlus.Fonts.OpenType/Tables/RawFontTable.cs @@ -0,0 +1,55 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/17/2026 EPPlus Software AB Raw pass-through table + *************************************************************************************************/ +using System; + +namespace EPPlus.Fonts.OpenType.Tables +{ + /// + /// A font table without a typed model. The bytes are kept and serialized verbatim. + /// Used for tables that are copied unchanged into a subset (e.g. 'cvt ', 'fpgm', 'prep', 'gasp'). + /// + internal class RawFontTable : FontTableBase + { + private readonly string _tag; + private byte[] _data; + + internal RawFontTable(string tag, byte[] data) + { + if (tag == null) throw new ArgumentNullException(nameof(tag)); + if (tag.Length != 4) throw new ArgumentException("A table tag must be exactly four characters.", nameof(tag)); + if (data == null) throw new ArgumentNullException(nameof(data)); + + _tag = tag; + _data = data; + } + + public override string Name => _tag; + + public override bool IsEssentialTable => false; + + /// + /// The raw, unpadded table bytes. + /// + internal byte[] Data => _data; + + internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializationContext context) + { + writer.Write(_data); + } + + internal override void Clear() + { + _data = new byte[0]; + } + } +} \ No newline at end of file diff --git a/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs b/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs index 150a827f24..ba8bfba213 100644 --- a/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs +++ b/src/EPPlus.Fonts.OpenType/Tables/TableNames.cs @@ -29,5 +29,9 @@ internal static class TableNames public const string Cmap = "cmap"; public const string Gsub = "GSUB"; public const string Gpos = "GPOS"; + public const string Cvt = "cvt "; // Note: trailing space is part of the tag + public const string Fpgm = "fpgm"; + public const string Prep = "prep"; + public const string Gasp = "gasp"; } } diff --git a/src/EPPlus.Interfaces/Fonts/FontEmbeddingInfo.cs b/src/EPPlus.Interfaces/Fonts/FontEmbeddingInfo.cs index 545880d088..30181dd6ca 100644 --- a/src/EPPlus.Interfaces/Fonts/FontEmbeddingInfo.cs +++ b/src/EPPlus.Interfaces/Fonts/FontEmbeddingInfo.cs @@ -1,17 +1,4 @@ -/************************************************************************************************* - Required Notice: Copyright (C) EPPlus Software AB. - This software is licensed under PolyForm Noncommercial License 1.0.0 - and may only be used for noncommercial purposes - 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 - ************************************************************************************************* - 10/07/2026 EPPlus Software AB EPPlus.Fonts.OpenType 1.0 - *************************************************************************************************/ - -namespace OfficeOpenXml.Interfaces.Fonts +namespace OfficeOpenXml.Interfaces.Fonts { /// /// Information passed to the @@ -20,9 +7,36 @@ namespace OfficeOpenXml.Interfaces.Fonts public class FontEmbeddingInfo { public FontEmbeddingInfo(string fontName, FontEmbeddingRestriction restriction) + : this(fontName, restriction, FontEmbeddingPermission.Installable, false, FontRenderTarget.Document) + { + } + + public FontEmbeddingInfo( + string fontName, + FontEmbeddingRestriction restriction, + FontEmbeddingPermission permission, + bool bitmapEmbeddingOnly, + FontRenderTarget target) + : this(fontName, restriction, permission, bitmapEmbeddingOnly, target, false, null) + { + } + + public FontEmbeddingInfo( + string fontName, + FontEmbeddingRestriction restriction, + FontEmbeddingPermission permission, + bool bitmapEmbeddingOnly, + FontRenderTarget target, + bool hasOpenLicense, + string licenseDescription) { FontName = fontName; Restriction = restriction; + Permission = permission; + BitmapEmbeddingOnly = bitmapEmbeddingOnly; + Target = target; + HasOpenLicense = hasOpenLicense; + LicenseDescription = licenseDescription; } /// The full name of the font being prepared for embedding. @@ -30,5 +44,39 @@ public FontEmbeddingInfo(string fontName, FontEmbeddingRestriction restriction) /// The restriction the font declares via its OS/2 fsType field. public FontEmbeddingRestriction Restriction { get; private set; } + + /// + /// The usage permission the font declares via its OS/2 fsType field. Distinguishes + /// Preview & Print from Editable and Installable, which does not. + /// + public FontEmbeddingPermission Permission { get; private set; } + + /// + /// True when the font's OS/2 fsType field declares that only bitmap data may be embedded. + /// The font's outlines must then not be embedded. + /// + public bool BitmapEmbeddingOnly { get; private set; } + + /// + /// The output the font is embedded in. is a PDF; + /// is an SVG or HTML file, where an embedded font is + /// delivered as a web font. Font licences often treat the two differently. + /// + public FontRenderTarget Target { get; private set; } + + /// + /// True when the font's name table (licence description, nameID 13, or licence URL, + /// nameID 14) names an open licence that EPPlus recognises: SIL Open Font License, + /// Apache License, Ubuntu Font Licence or Bitstream Vera. The default web policy embeds + /// only such fonts. False for commercial fonts and for fonts that carry no licence text. + /// + public bool HasOpenLicense { get; private set; } + + /// + /// The font's licence description (nameID 13) as written in the font, or null when it has + /// none. Lets the callback apply its own rules, for instance for a licence EPPlus does not + /// recognise. + /// + public string LicenseDescription { get; private set; } } -} +} \ No newline at end of file diff --git a/src/EPPlus.Interfaces/Fonts/FontEmbeddingPermission.cs b/src/EPPlus.Interfaces/Fonts/FontEmbeddingPermission.cs new file mode 100644 index 0000000000..58ef4c3055 --- /dev/null +++ b/src/EPPlus.Interfaces/Fonts/FontEmbeddingPermission.cs @@ -0,0 +1,18 @@ +namespace OfficeOpenXml.Interfaces.Fonts +{ + /// + /// The usage permission a font declares via bits 0-3 of its OS/2 fsType field. + /// Pure interpretation of fsType — carries no policy about what EPPlus does. + /// + public enum FontEmbeddingPermission + { + /// No usage bit set. The font may be embedded and permanently installed by the recipient. + Installable, + /// The font must not be embedded (Restricted License). + RestrictedLicense, + /// The font may be embedded in documents that are viewed or printed, but not edited. + PreviewAndPrint, + /// The font may be embedded in documents that the recipient may view, print and edit. + Editable, + } +} \ No newline at end of file diff --git a/src/EPPlus.Interfaces/Fonts/GenericFontFamily.cs b/src/EPPlus.Interfaces/Fonts/GenericFontFamily.cs new file mode 100644 index 0000000000..429386249c --- /dev/null +++ b/src/EPPlus.Interfaces/Fonts/GenericFontFamily.cs @@ -0,0 +1,36 @@ +/************************************************************************************************* + 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 + ************************************************************************************************* + 11/19/2026 EPPlus Software AB Generic font family for CSS font stacks + *************************************************************************************************/ +namespace OfficeOpenXml.Interfaces.Fonts +{ + /// + /// The CSS generic font family a font belongs to. Used as the last entry of a CSS + /// font-family stack, so a browser that has none of the named fonts picks a font of + /// the same kind. + /// + public enum GenericFontFamily + { + /// + /// Proportional font without serifs. CSS keyword sans-serif. Also used when + /// the font does not say what it is. + /// + SansSerif, + /// + /// Proportional font with serifs. CSS keyword serif. + /// + Serif, + /// + /// Font where all glyphs have the same advance width. CSS keyword monospace. + /// + Monospace + } +} diff --git a/src/EPPlus.Interfaces/Fonts/IEpplusFontConfiguration.cs b/src/EPPlus.Interfaces/Fonts/IEpplusFontConfiguration.cs index ca5947dd6f..a149b77f02 100644 --- a/src/EPPlus.Interfaces/Fonts/IEpplusFontConfiguration.cs +++ b/src/EPPlus.Interfaces/Fonts/IEpplusFontConfiguration.cs @@ -98,7 +98,8 @@ public interface IEpplusFontConfiguration /// /// Registers a callback invoked for each font that is about to be embedded, letting the - /// caller override how EPPlus handles the font's declared embedding restriction (fsType). + /// caller override how EPPlus handles the font's declared embedding restriction (fsType) + /// and, for web output, its licence. /// Return to keep EPPlus's standard behaviour. /// /// @@ -107,7 +108,33 @@ public interface IEpplusFontConfiguration /// , the caller asserts they hold the rights /// to do so; EPPlus cannot verify any licence the caller may have obtained from the font's /// owner. Only one callback is active; a later call replaces the earlier one. + /// + /// The callback is called for every output that embeds fonts: PDF export + /// () and SVG export (), + /// where a subset is delivered to browsers as a web font. Many font licences permit embedding + /// in documents but not use as a web font, so check + /// before returning . + /// + /// + /// For web output the default policy subsets only fonts whose fsType permits it and that name + /// an open licence (); other fonts are referenced + /// by name. is not supported for web output, and + /// such a font is referenced by name. + /// + /// + /// Fonts bundled with EPPlus are always subsetted, and the callback is not called for them. + /// The callback may be called many times for the same font, for instance once per exported + /// drawing, so it should be fast and free of side effects. + /// /// + /// + /// Embed commercial fonts in PDF export only, and leave web output to the default policy: + /// + /// cfg.OnFontEmbedding(info => info.Target == FontRenderTarget.Document + /// ? FontEmbeddingDecision.Subset + /// : FontEmbeddingDecision.Default); + /// + /// void OnFontEmbedding(Func callback); /// diff --git a/src/EPPlus/Drawing/Chart/ExcelChart.cs b/src/EPPlus/Drawing/Chart/ExcelChart.cs index 47096ce546..97b4f08aa1 100644 --- a/src/EPPlus/Drawing/Chart/ExcelChart.cs +++ b/src/EPPlus/Drawing/Chart/ExcelChart.cs @@ -1270,7 +1270,7 @@ internal override void SaveDrawing(bool hasLoadedPivotTables) } } /// - /// Returns true if the chart supports svg export via the . + /// Returns true if the chart supports svg export via the method. /// public override bool SupportsSvgExport => _svgSupportedChartTypes.Contains(ChartType); diff --git a/src/EPPlus/Drawing/ExcelDrawing.cs b/src/EPPlus/Drawing/ExcelDrawing.cs index ecab9561c2..55a72fb4b3 100644 --- a/src/EPPlus/Drawing/ExcelDrawing.cs +++ b/src/EPPlus/Drawing/ExcelDrawing.cs @@ -1768,7 +1768,7 @@ public ExcelGroupShape ParentGroup internal ExcelDrawingCustomGeometry CustomGeom { get; private set; } /// - /// Returns true if the drawing supports svg export via the . + /// Returns true if the drawing supports svg export via the method. /// public virtual bool SupportsSvgExport { get => false; } internal eDrawingInclude? IncludeInHtmlExport { get; set; } = eDrawingInclude.Include; @@ -2610,7 +2610,7 @@ public string ToSvg() { return ToSvg(null); } - /// git statu + /// /// Converts the drawing to a SVG image. /// This is currently only supported for shapes, line-, column-, bar- and pie- charts. /// @@ -2631,7 +2631,7 @@ public string ToSvg(Action options) var sb = new StringBuilder(); - var shapeRenderer = new SvgShapeRenderer(this.GetBoundingBox(), sb, o); + var shapeRenderer = new SvgShapeRenderer(this.GetBoundingBox(), sb, o, cr.RenderContext); shapeRenderer.Render(cr.RenderItems); var str = sb.ToString(); diff --git a/src/EPPlus/Drawing/ExcelPicture.cs b/src/EPPlus/Drawing/ExcelPicture.cs index b8422080ee..e87f358ef5 100644 --- a/src/EPPlus/Drawing/ExcelPicture.cs +++ b/src/EPPlus/Drawing/ExcelPicture.cs @@ -649,7 +649,7 @@ public bool VerticalFlip internal ZipPackageRelationship LinkedImageRel = null; /// - /// Returns true if the drawing supports svg export via the . + /// Returns true if the drawing supports svg export via the method. /// public override bool SupportsSvgExport => true; } diff --git a/src/EPPlus/Drawing/ExcelShape.cs b/src/EPPlus/Drawing/ExcelShape.cs index d4e8eba92e..f8ff40ebfd 100644 --- a/src/EPPlus/Drawing/ExcelShape.cs +++ b/src/EPPlus/Drawing/ExcelShape.cs @@ -11,6 +11,7 @@ Date Author Change 01/27/2020 EPPlus Software AB Initial release EPPlus 5 *************************************************************************************************/ using EPPlus.DrawingRenderer.Svg; +using OfficeOpenXml.Interfaces.Fonts; using EPPlus.Export.Utils; using OfficeOpenXml.Drawing.Interfaces; using OfficeOpenXml.Drawing.Renderer; @@ -97,14 +98,15 @@ internal override void DeleteMe() } public string ToSvg(SvgRenderOptions options) { - var sr = new ShapeRenderer(this, options.FontTarget); + var sr = new ShapeRenderer(this, options.FontTarget, + options.FontTarget == FontRenderTarget.Web && !options.EmbedFonts); var sb = new StringBuilder(); - var svg = new SvgShapeRenderer(this.GetBoundingBox(), sb, options); + var svg = new SvgShapeRenderer(this.GetBoundingBox(), sb, options, sr.RenderContext); svg.Render(sr.RenderItems); return sb.ToString(); } /// - /// Returns true if the drawing supports svg export via the . + /// Returns true if the drawing supports svg export via the method. /// public override bool SupportsSvgExport => true; } diff --git a/src/EPPlus/Drawing/Renderer/Chart/ChartAxisRenderer.cs b/src/EPPlus/Drawing/Renderer/Chart/ChartAxisRenderer.cs index c154f8625d..9ab3acf9f6 100644 --- a/src/EPPlus/Drawing/Renderer/Chart/ChartAxisRenderer.cs +++ b/src/EPPlus/Drawing/Renderer/Chart/ChartAxisRenderer.cs @@ -424,10 +424,12 @@ private double GetHighestAxisValue(ITextShaper shaper, float fontSize, float lin private double GetTextWidest(ExcelChartAxisStandard ax, bool isMulti) { + //The shaper is obtained through the render context so the family is substituted + //for the render target, matching the font the axis labels are measured with. var mf = ax.Font.GetMeasureFont(DefaultFonts2007Style.Axis); - var shaper = RenderContext.FontEngine.GetShaperForFont(mf); + var shaper = ChartRenderer.RenderContext.GetMeasurementShaper(new FontFormatBase(mf)); var tm = new OpenTypeFontTextMeasurer(shaper); - + var widest = 0f; if (isMulti) { diff --git a/src/EPPlus/Drawing/Renderer/ChartRenderer.cs b/src/EPPlus/Drawing/Renderer/ChartRenderer.cs index 53b5878744..bb09264320 100644 --- a/src/EPPlus/Drawing/Renderer/ChartRenderer.cs +++ b/src/EPPlus/Drawing/Renderer/ChartRenderer.cs @@ -14,6 +14,7 @@ Date Author Change using EPPlus.DrawingRenderer; using EPPlus.DrawingRenderer.RenderItems; using EPPlus.DrawingRenderer.Svg; +using OfficeOpenXml.Interfaces.Fonts; using EPPlus.Export.ImageRenderer.Svg.Chart; using EPPlusImageRenderer.RenderItems; using EPPlusImageRenderer.Svg; @@ -66,7 +67,8 @@ internal class ChartRenderer : d.DrawingRenderer // From the docs: 'The default font color is the same as the Axis & Major Gridlines Line Color' internal Color? InbuiltStyleFontColor => GetDefaultFontColor(); - public ChartRenderer(ExcelChart chart, SvgRenderOptions options) : base(chart, options.FontTarget) + public ChartRenderer(ExcelChart chart, SvgRenderOptions options) + : base(chart, options.FontTarget, options.FontTarget == FontRenderTarget.Web && !options.EmbedFonts) { SetChartArea(options); diff --git a/src/EPPlus/Drawing/Renderer/DrawingRenderer.cs b/src/EPPlus/Drawing/Renderer/DrawingRenderer.cs index 63371ed7d5..8fe6c2eaf4 100644 --- a/src/EPPlus/Drawing/Renderer/DrawingRenderer.cs +++ b/src/EPPlus/Drawing/Renderer/DrawingRenderer.cs @@ -32,13 +32,25 @@ namespace OfficeOpenXml.Drawing.Renderer internal abstract class DrawingRenderer { internal DrawingRenderer(ExcelDrawing drawing, FontRenderTarget target = FontRenderTarget.Document) + : this(drawing, target, target == FontRenderTarget.Web) + { + } + + /// The drawing to render. + /// The output kind text is laid out for. + /// + /// Whether fonts are substituted for the web before measuring. False when the fonts are embedded + /// in the output, so text is measured with the requested font. Has no effect unless the target + /// is . + /// + internal DrawingRenderer(ExcelDrawing drawing, FontRenderTarget target, bool substituteWebFonts) { Drawing = drawing; Bounds = drawing.GetBoundingBox(); var wb = drawing._drawings.Worksheet.Workbook; Theme = wb.ThemeManager.GetOrCreateTheme(); - RenderContext = wb.RenderContext.ForTarget(target); + RenderContext = wb.RenderContext.ForTarget(target, substituteWebFonts); ShapeDefaultFont = new RichTextFormatDrawing(); if (drawing is ExcelShapeBase shapeBase) { diff --git a/src/EPPlus/Drawing/Renderer/ShapeRenderer.cs b/src/EPPlus/Drawing/Renderer/ShapeRenderer.cs index 2c584f879a..fb1ad1362e 100644 --- a/src/EPPlus/Drawing/Renderer/ShapeRenderer.cs +++ b/src/EPPlus/Drawing/Renderer/ShapeRenderer.cs @@ -48,14 +48,13 @@ internal class ShapeRenderer : DrawingRenderer /// public DrawingTextBody TextBody{ get; internal set; } - //public ShapeRenderer(eShapeStyle style, double top, double left, double width, double height, eTextAutofit autofit) : base() - //{ - // var parentBounds = new BoundingBox(top, left, width, height); - // var shapeGroup = new GroupRenderItem(parentBounds); - - //} + public ShapeRenderer(ExcelShape shape, FontRenderTarget target) + : this(shape, target, target == FontRenderTarget.Web) + { + } - public ShapeRenderer(ExcelShape shape, FontRenderTarget target) : base(shape, target) + public ShapeRenderer(ExcelShape shape, FontRenderTarget target, bool substituteWebFonts) + : base(shape, target, substituteWebFonts) { var style = shape.Style; diff --git a/src/EPPlusTest/ConfigureFontsTests.cs b/src/EPPlusTest/ConfigureFontsTests.cs index 2c1dc7283c..6c3bd78f66 100644 --- a/src/EPPlusTest/ConfigureFontsTests.cs +++ b/src/EPPlusTest/ConfigureFontsTests.cs @@ -61,9 +61,10 @@ public void ConfigureFonts_ConfiguredDirectory_ResolvesRoboto() var svg = RenderRobotoTextbox(package); - // The requested name always appears; the real proof is that rendering with the - // directory configured does not throw and produces a measurable tspan. - StringAssert.Contains(svg, "font-family=\"Roboto"); + // The requested name always appears in the stack (after the embedded subset); the real + // proof is that rendering with the directory configured does not throw and produces a + // measurable tspan. + StringAssert.Matches(svg, new System.Text.RegularExpressions.Regex("font-family=\"[^\"]*'Roboto'")); Assert.IsTrue(GetFirstTspanBaselineY(svg) > 0); }
Caseimginlineinline, hostile cssExcelFile
").Append(WebUtility.HtmlEncode(c.Title)).Append("
") + .Append(WebUtility.HtmlEncode(c.Check)).AppendLine("
\"\"").Append(svg).AppendLine("").Append(svg).AppendLine(""); + if (GetOutputFile(OutputFolder, excel).Exists) + html.Append("\"\""); + else + html.Append("").Append(excel).Append(""); + html.AppendLine("open