Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert fonts between TTF, OTF, WOFF, WOFF2 and EOT

KnifeLemon56f22d39c959
diff --git a/.gitattributes b/.gitattributes
index 39743c82..603fb607 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -9,6 +9,9 @@
*.ttf binary
*.otf binary
+*.woff binary
+*.woff2 binary
+*.eot binary
*.ico binary
*.png binary
*.jpg binary
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 05fb3bc0..18aa3f19 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -22,6 +22,7 @@ Each component remains under its own license.
| ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
+| cu2qu (fontTools): the cubic-to-quadratic approach followed by `Filee.Engines/Fonts/Cff/CubicToQuadratic.cs` | Apache-2.0, Copyright 2016 Google Inc. | https://github.com/fonttools/fonttools |
## Engines
@@ -48,4 +49,5 @@ These programs run as separate processes. Their source code is available from th
| Component | License | Project |
|---|---|---|
| Noto Sans, Noto Sans KR, Noto Sans SC | SIL Open Font License 1.1 | https://github.com/notofonts |
+| Test fonts in `tests/Filee.Engines.Tests/Fonts` (subsets of Noto Sans and Noto Sans KR; not shipped) | SIL Open Font License 1.1 | see `OFL.txt` in that folder |
| Material Design Icons (Pictogrammers) | Apache-2.0 | https://pictogrammers.com |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 15adb4d1..ff069caa 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -11,6 +11,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) |
+| Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; CFF (PostScript) outlines become TrueType for TTF and EOT |
| **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
@@ -92,6 +93,36 @@ text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/Do
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+## Fonts
+
+Fonts are converted in-process (`Filee.Engines/Fonts`); zlib and Brotli come with .NET. The input format is
+recognised by content, so a mislabelled file still converts.
+
+- **WOFF 1.0**: every table zlib-compressed (stored as-is when that isn't smaller). Lossless both ways.
+- **WOFF2**: one Brotli stream at the highest quality with the glyf/loca transform and, where it applies, the hmtx
+ transform, so files come out the size of Google's reference encoder's. Reading handles both transforms, the
+ overlap bitmap, untransformed tables and the first font of a WOFF2 collection. Like other encoders, Filee drops
+ the DSIG signature and sets bit 11 of head.flags. Brotli is slow on big fonts (about 10 s per MB, so about a
+ minute for a 4.6 MB CJK font); the job shows progress and can be cancelled.
+- **EOT**: written as version 0x00020001 (names and OS/2 fields in the header, no MicroType Express compression, no
+ XOR obfuscation, no URL restriction). Uncompressed EOT files are read (XOR-obfuscated ones too); MTX-compressed
+ ones fail with a clear message.
+- **TTF → OTF** keeps the TrueType outlines: TrueType-flavoured OpenType is valid OpenType and what systems and
+ browsers expect; cubic outlines would gain nothing.
+- **OTF with CFF outlines → TTF** (and → EOT, because Internet Explorer renders only TrueType outlines in EOT)
+ converts the glyphs: Type 2 charstrings with subroutines, flex, seac accents and CID-keyed fonts are drawn, curves
+ are approximated with quadratic splines within 1/1000 em (the approach of fontTools' cu2qu) and contours are
+ reversed to TrueType's direction. glyf, loca, maxp 1.0 and post (format 2 with the CFF glyph names, format 3 for
+ CID fonts) are built; head, hhea, hmtx and, from VORG, vmtx are updated; CFF, VORG and DSIG are dropped; every
+ other table (cmap, name, OS/2, GSUB, GPOS, kern, ...) is kept. PostScript hints are not converted: the font gets a
+ gasp table (smoothing at every size) and a prep that switches on dropout control instead.
+- Not supported: CFF2 (variable) outlines to TTF or EOT (to WOFF, WOFF2 and OTF they convert), writing font
+ collections, and WOFF/WOFF2 extended metadata (dropped).
+
+`tests/Filee.Engines.Tests/FontTests.cs` checks every conversion with small OFL fonts in
+`tests/Filee.Engines.Tests/Fonts` (see `OFL.txt` there): round trips keep every table byte for byte, a WOFF2 made
+by Google's encoder decodes to the source font, and converted CFF glyphs are compared with the originals in Skia.
+
## HWP ↔ HWPX
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index 31b45a74..f9887045 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -1,6 +1,7 @@
// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.
using Filee.Core.Conversion;
+using Filee.Engines.Fonts;
using Filee.Engines.Hwp;
using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Infrastructure;
@@ -29,6 +30,7 @@ public static class EngineRegistry
new MarkdownConverter(),
new SpreadsheetConverter(),
new HwpxConverter(),
+ new FontConverter(),
new PandocConverter(),
new LibreOfficeConverter(env),
];
diff --git a/src/Filee.Engines/Fonts/BigEndian.cs b/src/Filee.Engines/Fonts/BigEndian.cs
new file mode 100644
index 00000000..dc5fde3b
--- /dev/null
+++ b/src/Filee.Engines/Fonts/BigEndian.cs
@@ -0,0 +1,200 @@
+// Big-endian readers and writers for font data (SFNT, WOFF, WOFF2, CFF all store numbers big-endian), including the
+// variable-length integers of WOFF2 (UIntBase128 and 255UInt16).
+
+using System.Buffers.Binary;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Reads big-endian values from a byte array; every read is bounds-checked.</summary>
+internal sealed class BigEndianReader(byte[] data, int offset = 0, int? end = null)
+{
+ private readonly int _end = end ?? data.Length;
+
+ /// <summary>The underlying array (positions are absolute indices into it).</summary>
+ public byte[] Data => data;
+
+ /// <summary>Absolute read position.</summary>
+ public int Position { get; set; } = offset;
+
+ /// <summary>Bytes left before the end of this reader's window.</summary>
+ public int Remaining => _end - Position;
+
+ public byte U8()
+ {
+ Need(1);
+ return data[Position++];
+ }
+
+ public ushort U16()
+ {
+ Need(2);
+ var value = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(Position));
+ Position += 2;
+ return value;
+ }
+
+ public short I16() => (short)U16();
+
+ public uint U32()
+ {
+ Need(4);
+ var value = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(Position));
+ Position += 4;
+ return value;
+ }
+
+ public int I32() => (int)U32();
+
+ /// <summary>Returns the next <paramref name="count"/> bytes without copying.</summary>
+ public ReadOnlySpan<byte> Span(int count)
+ {
+ Need(count);
+ var span = data.AsSpan(Position, count);
+ Position += count;
+ return span;
+ }
+
+ public byte[] Bytes(int count) => Span(count).ToArray();
+
+ public void Skip(int count)
+ {
+ Need(count);
+ Position += count;
+ }
+
+ /// <summary>WOFF2 UIntBase128: up to five bytes of 7 bits each, most significant first, no leading zeros.</summary>
+ public uint UIntBase128()
+ {
+ uint value = 0;
+ for (var i = 0; i < 5; i++)
+ {
+ var b = U8();
+ if (i == 0 && b == 0x80)
+ throw new InvalidDataException("Invalid WOFF2 number (leading zeros).");
+ if ((value & 0xFE000000) != 0)
+ throw new InvalidDataException("Invalid WOFF2 number (overflow).");
+ value = (value << 7) | (uint)(b & 0x7F);
+ if ((b & 0x80) == 0)
+ return value;
+ }
+ throw new InvalidDataException("Invalid WOFF2 number (longer than five bytes).");
+ }
+
+ /// <summary>WOFF2 255UInt16: one byte below 253, else a marker byte followed by one or two bytes.</summary>
+ public ushort Read255UInt16()
+ {
+ var code = U8();
+ return code switch
+ {
+ 253 => U16(),
+ 254 => (ushort)(U8() + 253 * 2),
+ 255 => (ushort)(U8() + 253),
+ _ => code,
+ };
+ }
+
+ private void Need(int count)
+ {
+ if (count < 0 || Position < 0 || Position > _end - count)
+ throw new InvalidDataException("The font file is truncated or damaged.");
+ }
+}
+
+/// <summary>A growable buffer that writes big-endian values.</summary>
+internal sealed class BigEndianWriter(int capacity = 256)
+{
+ private byte[] _buffer = new byte[Math.Max(16, capacity)];
+
+ /// <summary>Number of bytes written so far (also the current write position).</summary>
+ public int Length { get; private set; }
+
+ /// <summary>The bytes written so far.</summary>
+ public Span<byte> Written => _buffer.AsSpan(0, Length);
+
+ public void U8(int value)
+ {
+ Grow(1);
+ _buffer[Length++] = (byte)value;
+ }
+
+ public void U16(int value)
+ {
+ Grow(2);
+ BinaryPrimitives.WriteUInt16BigEndian(_buffer.AsSpan(Length), (ushort)value);
+ Length += 2;
+ }
+
+ public void I16(int value) => U16((ushort)(short)value);
+
+ public void U32(uint value)
+ {
+ Grow(4);
+ BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(Length), value);
+ Length += 4;
+ }
+
+ public void Bytes(ReadOnlySpan<byte> bytes)
+ {
+ Grow(bytes.Length);
+ bytes.CopyTo(_buffer.AsSpan(Length));
+ Length += bytes.Length;
+ }
+
+ public void Zeros(int count)
+ {
+ Grow(count);
+ _buffer.AsSpan(Length, count).Clear();
+ Length += count;
+ }
+
+ /// <summary>Pads with zeros to the next multiple of four.</summary>
+ public void Pad4() => Zeros((4 - (Length & 3)) & 3);
+
+ public void SetU32(int position, uint value) => BinaryPrimitives.WriteUInt32BigEndian(_buffer.AsSpan(position), value);
+
+ /// <summary>Writes a WOFF2 UIntBase128 (see <see cref="BigEndianReader.UIntBase128"/>).</summary>
+ public void UIntBase128(uint value)
+ {
+ var groups = 1;
+ for (var v = value >> 7; v != 0; v >>= 7)
+ groups++;
+ for (var i = groups - 1; i >= 0; i--)
+ {
+ var bits = (int)(value >> (7 * i)) & 0x7F;
+ U8(i > 0 ? bits | 0x80 : bits);
+ }
+ }
+
+ /// <summary>Writes a WOFF2 255UInt16 in its shortest form.</summary>
+ public void Write255UInt16(int value)
+ {
+ if (value < 253)
+ {
+ U8(value);
+ }
+ else if (value < 506)
+ {
+ U8(255);
+ U8(value - 253);
+ }
+ else if (value < 762)
+ {
+ U8(254);
+ U8(value - 506);
+ }
+ else
+ {
+ U8(253);
+ U16(value);
+ }
+ }
+
+ public byte[] ToArray() => _buffer.AsSpan(0, Length).ToArray();
+
+ private void Grow(int count)
+ {
+ if (Length + count <= _buffer.Length)
+ return;
+ Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, Length + count));
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Cff/CffFont.cs b/src/Filee.Engines/Fonts/Cff/CffFont.cs
new file mode 100644
index 00000000..b63af293
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Cff/CffFont.cs
@@ -0,0 +1,361 @@
+// Parser for the Compact Font Format version 1 (Adobe Technical Note #5176), the 'CFF ' table of OpenType fonts
+// with PostScript outlines: charstrings, subroutines, private dictionaries, charsets and CID font dictionaries.
+
+using System.Globalization;
+using System.Text;
+
+namespace Filee.Engines.Fonts.Cff;
+
+/// <summary>Values from a Private DICT that charstrings need (widths are not: hmtx has them).</summary>
+internal sealed class CffPrivate
+{
+ /// <summary>Local subroutines.</summary>
+ public byte[][] Subrs { get; init; } = [];
+}
+
+/// <summary>A parsed CFF font (the first font of the table's FontSet).</summary>
+internal sealed class CffFont
+{
+ // DICT operators (two-byte operators are 1200 + second byte).
+ private const int OpCharset = 15;
+ private const int OpCharStrings = 17;
+ private const int OpPrivate = 18;
+ private const int OpSubrs = 19;
+ private const int OpCharstringType = 1206;
+ private const int OpFontMatrix = 1207;
+ private const int OpRos = 1230;
+ private const int OpFdArray = 1236;
+ private const int OpFdSelect = 1237;
+
+ private static readonly double[] DefaultMatrix = [0.001, 0, 0, 0.001, 0, 0];
+
+ private byte[] _fdSelect = [];
+ private Dictionary<int, int>? _glyphBySid;
+
+ /// <summary>Type 2 charstring of every glyph.</summary>
+ public byte[][] CharStrings { get; private init; } = [];
+
+ /// <summary>Global subroutines.</summary>
+ public byte[][] GlobalSubrs { get; private init; } = [];
+
+ /// <summary>Private DICT of each font dictionary (one for name-keyed fonts, one per FD for CID fonts).</summary>
+ public CffPrivate[] Privates { get; private init; } = [];
+
+ /// <summary>FontMatrix of the Top DICT combined with each font dictionary's own (CID fonts), per FD.</summary>
+ public double[][] FontMatrices { get; private init; } = [];
+
+ /// <summary>True for CID-keyed fonts (glyphs identified by CID, no glyph names).</summary>
+ public bool IsCid { get; private init; }
+
+ /// <summary>SID (name-keyed) or CID of each glyph; null when the charset is a predefined expert charset.</summary>
+ public ushort[]? Charset { get; private init; }
+
+ /// <summary>Strings of the String INDEX (SID 391 and up).</summary>
+ public string[] Strings { get; private init; } = [];
+
+ public int GlyphCount => CharStrings.Length;
+
+ /// <summary>Index of the font dictionary a glyph uses.</summary>
+ public int FontDictIndex(int glyph) => glyph < _fdSelect.Length ? _fdSelect[glyph] : 0;
+
+ /// <summary>Glyph name from the charset; null for CID fonts or unknown charsets.</summary>
+ public string? GlyphName(int glyph)
+ {
+ if (IsCid || Charset is null || glyph >= Charset.Length)
+ return null;
+ int sid = Charset[glyph];
+ return sid < CffStandardData.StandardStrings.Length ? CffStandardData.StandardStrings[sid]
+ : sid - CffStandardData.StandardStrings.Length < Strings.Length ? Strings[sid - CffStandardData.StandardStrings.Length]
+ : null;
+ }
+
+ /// <summary>The glyph whose charset entry is <paramref name="sid"/>, or -1.</summary>
+ public int GlyphBySid(int sid)
+ {
+ if (Charset is null || IsCid)
+ return -1;
+ _glyphBySid ??= Charset.Select((s, gid) => (s, gid)).GroupBy(p => (int)p.s).ToDictionary(g => g.Key, g => g.First().gid);
+ return _glyphBySid.TryGetValue(sid, out var glyph) ? glyph : -1;
+ }
+
+ /// <summary>Parses a 'CFF ' table.</summary>
+ /// <exception cref="NotSupportedException">The table is CFF2 or uses Type 1 charstrings.</exception>
+ public static CffFont Parse(byte[] data)
+ {
+ if (data.Length < 4)
+ throw new InvalidDataException("The CFF table is damaged.");
+ if (data[0] != 1)
+ throw new NotSupportedException($"CFF version {data[0]} outlines can't be converted.");
+ var position = (int)data[2]; // hdrSize
+ ReadIndex(data, ref position); // Name INDEX
+ var topDicts = ReadIndex(data, ref position);
+ var strings = ReadIndex(data, ref position);
+ var globalSubrs = ReadIndex(data, ref position);
+ if (topDicts.Length == 0)
+ throw new InvalidDataException("The CFF table has no font.");
+
+ var top = ParseDict(topDicts[0]);
+ if (Number(top, OpCharstringType, 2) != 2)
+ throw new NotSupportedException("The CFF font uses Type 1 charstrings, which aren't supported.");
+ if (!top.TryGetValue(OpCharStrings, out var charStringsOffset))
+ throw new InvalidDataException("The CFF font has no glyphs.");
+ var at = Offset(charStringsOffset[0], data);
+ var charStrings = ReadIndex(data, ref at);
+ var topMatrix = top.TryGetValue(OpFontMatrix, out var m) && m.Length == 6 ? m : DefaultMatrix;
+ var isCid = top.ContainsKey(OpRos);
+
+ CffPrivate[] privates;
+ double[][] matrices;
+ var fdSelect = Array.Empty<byte>();
+ if (isCid)
+ {
+ if (!top.TryGetValue(OpFdArray, out var fdArrayOffset))
+ throw new InvalidDataException("The CID-keyed CFF font has no font dictionaries.");
+ var fdAt = Offset(fdArrayOffset[0], data);
+ var fontDicts = ReadIndex(data, ref fdAt).Select(ParseDict).ToArray();
+ privates = [.. fontDicts.Select(fd => ReadPrivate(data, fd))];
+ // A font dictionary's FontMatrix applies first, then the Top DICT's.
+ matrices = [.. fontDicts.Select(fd => fd.TryGetValue(OpFontMatrix, out var fm) && fm.Length == 6 ? Multiply(fm, topMatrix) : topMatrix)];
+ if (top.TryGetValue(OpFdSelect, out var fdSelectOffset))
+ fdSelect = ReadFdSelect(data, Offset(fdSelectOffset[0], data), charStrings.Length, privates.Length);
+ }
+ else
+ {
+ privates = [ReadPrivate(data, top)];
+ matrices = [topMatrix];
+ }
+
+ return new CffFont
+ {
+ CharStrings = charStrings,
+ GlobalSubrs = globalSubrs,
+ Privates = privates,
+ FontMatrices = matrices,
+ IsCid = isCid,
+ Charset = ReadCharset(data, (int)Number(top, OpCharset, 0), charStrings.Length),
+ Strings = [.. strings.Select(s => Encoding.Latin1.GetString(s))],
+ _fdSelect = fdSelect,
+ };
+ }
+
+ /// <summary>Combines two FontMatrix transforms: <paramref name="first"/> is applied, then <paramref name="then"/>.</summary>
+ private static double[] Multiply(double[] first, double[] then) =>
+ [
+ then[0] * first[0] + then[2] * first[1],
+ then[1] * first[0] + then[3] * first[1],
+ then[0] * first[2] + then[2] * first[3],
+ then[1] * first[2] + then[3] * first[3],
+ then[0] * first[4] + then[2] * first[5] + then[4],
+ then[1] * first[4] + then[3] * first[5] + then[5],
+ ];
+
+ private static CffPrivate ReadPrivate(byte[] data, Dictionary<int, double[]> dict)
+ {
+ if (!dict.TryGetValue(OpPrivate, out var entry) || entry.Length < 2)
+ return new CffPrivate();
+ var size = (int)entry[0];
+ var offset = Offset(entry[1], data);
+ if (size < 0 || size > data.Length - offset)
+ throw new InvalidDataException("The CFF private dictionary lies outside the table.");
+ var priv = ParseDict(data.AsSpan(offset, size).ToArray());
+ var subrs = Array.Empty<byte[]>();
+ if (priv.TryGetValue(OpSubrs, out var subrsOffset))
+ {
+ var at = Offset(offset + subrsOffset[0], data);
+ subrs = ReadIndex(data, ref at);
+ }
+ return new CffPrivate { Subrs = subrs };
+ }
+
+ private static ushort[]? ReadCharset(byte[] data, int offset, int glyphCount)
+ {
+ var charset = new ushort[glyphCount];
+ if (offset == 0)
+ {
+ // ISOAdobe: glyph i is SID i.
+ for (var i = 0; i < glyphCount; i++)
+ charset[i] = (ushort)i;
+ return charset;
+ }
+ if (offset is 1 or 2)
+ return null; // Expert charsets: only used by old expert fonts; names are not needed to convert them.
+
+ var r = new BigEndianReader(data, Offset(offset, data));
+ var format = r.U8();
+ var glyph = 1;
+ while (glyph < glyphCount)
+ {
+ switch (format)
+ {
+ case 0:
+ charset[glyph++] = r.U16();
+ break;
+ case 1 or 2:
+ var first = r.U16();
+ var left = format == 1 ? r.U8() : r.U16();
+ for (var i = 0; i <= left && glyph < glyphCount; i++)
+ charset[glyph++] = (ushort)(first + i);
+ break;
+ default:
+ throw new InvalidDataException($"Unknown CFF charset format {format}.");
+ }
+ }
+ return charset;
+ }
+
+ private static byte[] ReadFdSelect(byte[] data, int offset, int glyphCount, int fdCount)
+ {
+ var fds = new byte[glyphCount];
+ var r = new BigEndianReader(data, offset);
+ var format = r.U8();
+ if (format == 0)
+ {
+ for (var i = 0; i < glyphCount; i++)
+ fds[i] = r.U8();
+ }
+ else if (format == 3)
+ {
+ int ranges = r.U16();
+ int first = r.U16();
+ for (var i = 0; i < ranges; i++)
+ {
+ var fd = r.U8();
+ int next = r.U16();
+ for (var g = first; g < next && g < glyphCount; g++)
+ fds[g] = fd;
+ first = next;
+ }
+ }
+ else
+ {
+ throw new InvalidDataException($"Unknown CFF FDSelect format {format}.");
+ }
+ if (fds.Any(fd => fd >= fdCount))
+ throw new InvalidDataException("The CFF FDSelect refers to a missing font dictionary.");
+ return fds;
+ }
+
+ /// <summary>Reads an INDEX (count, offset size, 1-based offsets, data) and advances past it.</summary>
+ internal static byte[][] ReadIndex(byte[] data, ref int position)
+ {
+ var r = new BigEndianReader(data, position);
+ int count = r.U16();
+ if (count == 0)
+ {
+ position = r.Position;
+ return [];
+ }
+ int offSize = r.U8();
+ if (offSize is < 1 or > 4)
+ throw new InvalidDataException("The CFF table is damaged (invalid INDEX).");
+ var offsets = new long[count + 1];
+ for (var i = 0; i <= count; i++)
+ {
+ long value = 0;
+ for (var b = 0; b < offSize; b++)
+ value = value << 8 | r.U8();
+ offsets[i] = value;
+ }
+ var dataStart = (long)r.Position - 1; // offsets are 1-based
+ var items = new byte[count][];
+ for (var i = 0; i < count; i++)
+ {
+ long start = dataStart + offsets[i], end = dataStart + offsets[i + 1];
+ if (start < r.Position || end < start || end > data.Length)
+ throw new InvalidDataException("The CFF table is damaged (INDEX data outside the table).");
+ items[i] = data.AsSpan((int)start, (int)(end - start)).ToArray();
+ }
+ position = (int)(dataStart + offsets[count]);
+ return items;
+ }
+
+ /// <summary>Parses a DICT into operator → operands.</summary>
+ internal static Dictionary<int, double[]> ParseDict(byte[] data)
+ {
+ var dict = new Dictionary<int, double[]>();
+ var operands = new List<double>();
+ var r = new BigEndianReader(data);
+ while (r.Remaining > 0)
+ {
+ int b0 = r.U8();
+ if (b0 <= 21)
+ {
+ var op = b0 == 12 ? 1200 + r.U8() : b0;
+ dict[op] = [.. operands];
+ operands.Clear();
+ }
+ else if (b0 == 28)
+ {
+ operands.Add(r.I16());
+ }
+ else if (b0 == 29)
+ {
+ operands.Add(r.I32());
+ }
+ else if (b0 == 30)
+ {
+ operands.Add(ReadReal(r));
+ }
+ else if (b0 is >= 32 and <= 246)
+ {
+ operands.Add(b0 - 139);
+ }
+ else if (b0 is >= 247 and <= 250)
+ {
+ operands.Add((b0 - 247) * 256 + r.U8() + 108);
+ }
+ else if (b0 is >= 251 and <= 254)
+ {
+ operands.Add(-(b0 - 251) * 256 - r.U8() - 108);
+ }
+ else
+ {
+ throw new InvalidDataException("The CFF table is damaged (invalid DICT data).");
+ }
+ }
+ return dict;
+ }
+
+ /// <summary>A real number: nibbles for digits, '.', 'E', 'E-' and '-', ended by 0xF.</summary>
+ private static double ReadReal(BigEndianReader r)
+ {
+ var text = new StringBuilder();
+ while (true)
+ {
+ var b = r.U8();
+ foreach (var nibble in new[] { b >> 4, b & 0xF })
+ {
+ switch (nibble)
+ {
+ case <= 9:
+ text.Append((char)('0' + nibble));
+ break;
+ case 0xA:
+ text.Append('.');
+ break;
+ case 0xB:
+ text.Append('E');
+ break;
+ case 0xC:
+ text.Append("E-");
+ break;
+ case 0xE:
+ text.Append('-');
+ break;
+ case 0xF:
+ return double.TryParse(text.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : 0;
+ }
+ }
+ }
+ }
+
+ private static double Number(Dictionary<int, double[]> dict, int op, double fallback) =>
+ dict.TryGetValue(op, out var values) && values.Length > 0 ? values[0] : fallback;
+
+ private static int Offset(double value, byte[] data)
+ {
+ if (value < 0 || value >= data.Length)
+ throw new InvalidDataException("The CFF table is damaged (offset outside the table).");
+ return (int)value;
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Cff/CffStandardData.cs b/src/Filee.Engines/Fonts/Cff/CffStandardData.cs
new file mode 100644
index 00000000..9c0c2947
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Cff/CffStandardData.cs
@@ -0,0 +1,92 @@
+// Fixed name lists from the font specifications: the 391 CFF standard strings and the Standard Encoding (Adobe
+// Technical Note #5176, appendices A and B), and the 258 standard Macintosh glyph names of the 'post' table.
+
+namespace Filee.Engines.Fonts.Cff;
+
+/// <summary>Standard strings and encodings shared by every CFF font, and the standard 'post' glyph names.</summary>
+internal static class CffStandardData
+{
+ /// <summary>CFF strings with SID 0–390; custom strings in the String INDEX start at SID 391.</summary>
+ public static readonly string[] StandardStrings = (
+ ".notdef space exclam quotedbl numbersign dollar percent ampersand quoteright parenleft parenright asterisk plus " +
+ "comma hyphen period slash zero one two three four five six seven eight nine colon semicolon less equal greater " +
+ "question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " +
+ "underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright asciitilde " +
+ "exclamdown cent sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft " +
+ "guilsinglleft guilsinglright fi fl endash dagger daggerdbl periodcentered paragraph bullet quotesinglbase " +
+ "quotedblbase quotedblright guillemotright ellipsis perthousand questiondown grave acute circumflex tilde macron " +
+ "breve dotaccent dieresis ring cedilla hungarumlaut ogonek caron emdash AE ordfeminine Lslash Oslash OE " +
+ "ordmasculine ae dotlessi lslash oslash oe germandbls onesuperior logicalnot mu trademark Eth onehalf plusminus " +
+ "Thorn onequarter divide brokenbar degree thorn threequarters twosuperior registered minus eth multiply " +
+ "threesuperior copyright Aacute Acircumflex Adieresis Agrave Aring Atilde Ccedilla Eacute Ecircumflex Edieresis " +
+ "Egrave Iacute Icircumflex Idieresis Igrave Ntilde Oacute Ocircumflex Odieresis Ograve Otilde Scaron Uacute " +
+ "Ucircumflex Udieresis Ugrave Yacute Ydieresis Zcaron aacute acircumflex adieresis agrave aring atilde ccedilla " +
+ "eacute ecircumflex edieresis egrave iacute icircumflex idieresis igrave ntilde oacute ocircumflex odieresis " +
+ "ograve otilde scaron uacute ucircumflex udieresis ugrave yacute ydieresis zcaron exclamsmall Hungarumlautsmall " +
+ "dollaroldstyle dollarsuperior ampersandsmall Acutesmall parenleftsuperior parenrightsuperior twodotenleader " +
+ "onedotenleader zerooldstyle oneoldstyle twooldstyle threeoldstyle fouroldstyle fiveoldstyle sixoldstyle " +
+ "sevenoldstyle eightoldstyle nineoldstyle commasuperior threequartersemdash periodsuperior questionsmall " +
+ "asuperior bsuperior centsuperior dsuperior esuperior isuperior lsuperior msuperior nsuperior osuperior rsuperior " +
+ "ssuperior tsuperior ff ffi ffl parenleftinferior parenrightinferior Circumflexsmall hyphensuperior Gravesmall " +
+ "Asmall Bsmall Csmall Dsmall Esmall Fsmall Gsmall Hsmall Ismall Jsmall Ksmall Lsmall Msmall Nsmall Osmall Psmall " +
+ "Qsmall Rsmall Ssmall Tsmall Usmall Vsmall Wsmall Xsmall Ysmall Zsmall colonmonetary onefitted rupiah Tildesmall " +
+ "exclamdownsmall centoldstyle Lslashsmall Scaronsmall Zcaronsmall Dieresissmall Brevesmall Caronsmall " +
+ "Dotaccentsmall Macronsmall figuredash hypheninferior Ogoneksmall Ringsmall Cedillasmall questiondownsmall " +
+ "oneeighth threeeighths fiveeighths seveneighths onethird twothirds zerosuperior foursuperior fivesuperior " +
+ "sixsuperior sevensuperior eightsuperior ninesuperior zeroinferior oneinferior twoinferior threeinferior " +
+ "fourinferior fiveinferior sixinferior seveninferior eightinferior nineinferior centinferior dollarinferior " +
+ "periodinferior commainferior Agravesmall Aacutesmall Acircumflexsmall Atildesmall Adieresissmall Aringsmall " +
+ "AEsmall Ccedillasmall Egravesmall Eacutesmall Ecircumflexsmall Edieresissmall Igravesmall Iacutesmall " +
+ "Icircumflexsmall Idieresissmall Ethsmall Ntildesmall Ogravesmall Oacutesmall Ocircumflexsmall Otildesmall " +
+ "Odieresissmall OEsmall Oslashsmall Ugravesmall Uacutesmall Ucircumflexsmall Udieresissmall Yacutesmall " +
+ "Thornsmall Ydieresissmall 001.000 001.001 001.002 001.003 Black Bold Book Light Medium Regular Roman Semibold")
+ .Split(' ');
+
+ /// <summary>
+ /// Standard Encoding as code → SID (0 = not encoded). Used by the deprecated <c>seac</c> form of
+ /// <c>endchar</c>, whose base and accent are given as Standard Encoding codes.
+ /// </summary>
+ public static readonly ushort[] StandardEncoding = BuildStandardEncoding();
+
+ /// <summary>The 258 glyph names a 'post' format 2 table can refer to by index.</summary>
+ public static readonly string[] MacGlyphNames = (
+ ".notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft " +
+ "parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon " +
+ "semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft " +
+ "backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z " +
+ "braceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute agrave " +
+ "acircumflex adieresis atilde aring ccedilla eacute egrave ecircumflex edieresis iacute igrave icircumflex " +
+ "idieresis ntilde oacute ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree " +
+ "cent sterling section bullet paragraph germandbls registered copyright trademark acute dieresis notequal AE " +
+ "Oslash infinity plusminus lessequal greaterequal yen mu partialdiff summation product pi integral ordfeminine " +
+ "ordmasculine Omega ae oslash questiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft " +
+ "guillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash quotedblleft quotedblright " +
+ "quoteleft quoteright divide lozenge ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl " +
+ "daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis Egrave " +
+ "Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute Ucircumflex Ugrave dotlessi " +
+ "circumflex tilde macron breve dotaccent ring cedilla hungarumlaut ogonek caron Lslash lslash Scaron scaron " +
+ "Zcaron zcaron brokenbar Eth eth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior " +
+ "onehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla Cacute cacute Ccaron ccaron " +
+ "dcroat")
+ .Split(' ');
+
+ private static ushort[] BuildStandardEncoding()
+ {
+ var map = new ushort[256];
+ // Printable ASCII maps to SIDs 1–95 in order.
+ for (var code = 32; code <= 126; code++)
+ map[code] = (ushort)(code - 31);
+ // The upper half, as (first code, first SID, count) runs.
+ (int Code, int Sid, int Count)[] runs =
+ [
+ (161, 96, 15), (177, 111, 4), (182, 115, 8), (191, 123, 1), (193, 124, 8), (202, 132, 2), (205, 134, 4),
+ (225, 138, 1), (227, 139, 1), (232, 140, 4), (241, 144, 1), (245, 145, 1), (248, 146, 4),
+ ];
+ foreach (var (code, sid, count) in runs)
+ {
+ for (var i = 0; i < count; i++)
+ map[code + i] = (ushort)(sid + i);
+ }
+ return map;
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Cff/CubicToQuadratic.cs b/src/Filee.Engines/Fonts/Cff/CubicToQuadratic.cs
new file mode 100644
index 00000000..8cc57fad
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Cff/CubicToQuadratic.cs
@@ -0,0 +1,159 @@
+// Approximates cubic Bézier curves (CFF) with quadratic splines (TrueType) within a distance tolerance. Follows the
+// approach of cu2qu (Google, Apache-2.0; part of fontTools): split the cubic into n equal pieces, give each piece one
+// quadratic control point, let TrueType's implied on-curve midpoints join them, and take the smallest n that fits.
+
+namespace Filee.Engines.Fonts.Cff;
+
+/// <summary>Cubic → quadratic curve conversion.</summary>
+internal static class CubicToQuadratic
+{
+ private const int MaxPieces = 100;
+ private const int MaxCheckDepth = 24;
+
+ /// <summary>
+ /// Returns the off-curve control points of a quadratic spline from <paramref name="p0"/> to
+ /// <paramref name="p3"/> that stays within <paramref name="tolerance"/> of the cubic. Consecutive off-curve
+ /// points have an implied on-curve point halfway between them. An empty result means a straight line.
+ /// </summary>
+ public static List<Vec2> Convert(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, double tolerance)
+ {
+ if (IsLine(p0, p1, p2, p3, tolerance))
+ return [];
+ for (var n = 1; n <= MaxPieces; n++)
+ {
+ var spline = n == 1 ? Single(p0, p1, p2, p3, tolerance) : Spline(p0, p1, p2, p3, n, tolerance);
+ if (spline is not null)
+ return spline;
+ }
+ // Not reachable for real outlines (100 pieces fit anything); keep the finest split rather than failing.
+ return Spline(p0, p1, p2, p3, MaxPieces, double.PositiveInfinity)!;
+ }
+
+ /// <summary>
+ /// True when the control points lie on the chord within a small fraction of the tolerance and between its ends:
+ /// the curve is then exactly the chord.
+ /// </summary>
+ private static bool IsLine(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, double tolerance)
+ {
+ var chord = p3 - p0;
+ var length = chord.Length;
+ if (length < 1e-9)
+ return (p1 - p0).Length < 1e-9 && (p2 - p0).Length < 1e-9;
+ foreach (var p in (ReadOnlySpan<Vec2>)[p1, p2])
+ {
+ var v = p - p0;
+ var along = Vec2.Dot(v, chord) / (length * length);
+ var distance = Math.Abs(v.X * chord.Y - v.Y * chord.X) / length;
+ if (along < 0 || along > 1 || distance > tolerance * 0.01)
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>One quadratic whose control point is where the cubic's end tangents meet.</summary>
+ private static List<Vec2>? Single(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, double tolerance)
+ {
+ if (Intersect(p0, p1, p2, p3) is not { } q)
+ return null;
+ // Degree-elevated quadratic vs. the cubic: compare the differences of their control points.
+ var c1 = p0 + (q - p0) * (2.0 / 3);
+ var c2 = p3 + (q - p3) * (2.0 / 3);
+ return FitsInside(default, c1 - p1, c2 - p2, default, tolerance, 0) ? [q] : null;
+ }
+
+ /// <summary>n quadratics chained through implied on-curve points; null when the error exceeds the tolerance.</summary>
+ private static List<Vec2>? Spline(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, int n, double tolerance)
+ {
+ var pieces = Split(p0, p1, p2, p3, n);
+ var controls = new List<Vec2>(n);
+ for (var i = 0; i < n; i++)
+ controls.Add(Control((double)i / (n - 1), pieces[i]));
+
+ var d1 = default(Vec2);
+ var q2 = p0;
+ for (var i = 0; i < n; i++)
+ {
+ var (_, c1, c2, c3) = pieces[i];
+ var q0 = q2;
+ var q1 = controls[i];
+ q2 = i + 1 < n ? (q1 + controls[i + 1]) * 0.5 : c3;
+ var d0 = d1;
+ d1 = q2 - c3;
+ if (d1.Length > tolerance ||
+ !FitsInside(d0, q0 + (q1 - q0) * (2.0 / 3) - c1, q2 + (q1 - q2) * (2.0 / 3) - c2, d1, tolerance, 0))
+ {
+ return null;
+ }
+ }
+ return controls;
+ }
+
+ /// <summary>
+ /// Control point for piece <paramref name="t"/> (0 = first, 1 = last): interpolates between the points where the
+ /// piece's start and end tangents, extended by 1.5, land.
+ /// </summary>
+ private static Vec2 Control(double t, (Vec2 A, Vec2 B, Vec2 C, Vec2 D) piece)
+ {
+ var start = piece.A + (piece.B - piece.A) * 1.5;
+ var end = piece.D + (piece.C - piece.D) * 1.5;
+ return start + (end - start) * t;
+ }
+
+ /// <summary>Splits the cubic into n pieces of equal parameter length.</summary>
+ private static (Vec2 A, Vec2 B, Vec2 C, Vec2 D)[] Split(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, int n)
+ {
+ // Power basis: B(t) = a t³ + b t² + c t + d.
+ var c = (p1 - p0) * 3;
+ var b = (p2 - p1) * 3 - c;
+ var d = p0;
+ var a = p3 - d - c - b;
+
+ var pieces = new (Vec2, Vec2, Vec2, Vec2)[n];
+ var dt = 1.0 / n;
+ for (var i = 0; i < n; i++)
+ {
+ // Substitute t = t0 + dt·u and convert the piece back to Bézier control points.
+ var t0 = i * dt;
+ var a1 = a * (dt * dt * dt);
+ var b1 = (a * (3 * t0) + b) * (dt * dt);
+ var c1 = (b * (2 * t0) + c + a * (3 * t0 * t0)) * dt;
+ var d1 = a * (t0 * t0 * t0) + b * (t0 * t0) + c * t0 + d;
+ var q1 = c1 * (1.0 / 3) + d1;
+ var q2 = (b1 + c1) * (1.0 / 3) + q1;
+ var q3 = a1 + d1 + c1 + b1;
+ pieces[i] = (d1, q1, q2, q3);
+ }
+ return pieces;
+ }
+
+ /// <summary>Where line a→b meets line c→d, or null when they are parallel.</summary>
+ private static Vec2? Intersect(Vec2 a, Vec2 b, Vec2 c, Vec2 d)
+ {
+ var ab = b - a;
+ var cd = d - c;
+ var normal = new Vec2(-ab.Y, ab.X);
+ var denominator = Vec2.Dot(normal, cd);
+ if (Math.Abs(denominator) < 1e-12)
+ return null;
+ var h = Vec2.Dot(normal, a - c) / denominator;
+ return c + cd * h;
+ }
+
+ /// <summary>
+ /// True when the cubic with these control points (a difference curve) stays within the tolerance of the origin
+ /// everywhere, checked by subdividing until its control points are all close enough.
+ /// </summary>
+ private static bool FitsInside(Vec2 p0, Vec2 p1, Vec2 p2, Vec2 p3, double tolerance, int depth)
+ {
+ if (p2.Length <= tolerance && p1.Length <= tolerance)
+ return true;
+ var mid = (p0 + (p1 + p2) * 3 + p3) * 0.125;
+ if (mid.Length > tolerance)
+ return false;
+ if (depth >= MaxCheckDepth)
+ return true;
+ var deriv = (p3 + p2 - p1 - p0) * 0.125;
+ return FitsInside(p0, (p0 + p1) * 0.5, mid - deriv, mid, tolerance, depth + 1) &&
+ FitsInside(mid, mid + deriv, (p2 + p3) * 0.5, p3, tolerance, depth + 1);
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Cff/Type2Interpreter.cs b/src/Filee.Engines/Fonts/Cff/Type2Interpreter.cs
new file mode 100644
index 00000000..37f04cc2
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Cff/Type2Interpreter.cs
@@ -0,0 +1,475 @@
+// Runs Type 2 charstrings (Adobe Technical Note #5177) and records the outline as cubic Bézier contours. Hints are
+// parsed only as far as needed to skip them; subroutines, flex, the arithmetic operators and seac accents work.
+
+namespace Filee.Engines.Fonts.Cff;
+
+/// <summary>A 2D point or vector in font units.</summary>
+internal readonly record struct Vec2(double X, double Y)
+{
+ public static Vec2 operator +(Vec2 a, Vec2 b) => new(a.X + b.X, a.Y + b.Y);
+ public static Vec2 operator -(Vec2 a, Vec2 b) => new(a.X - b.X, a.Y - b.Y);
+ public static Vec2 operator *(Vec2 a, double s) => new(a.X * s, a.Y * s);
+ public double Length => Math.Sqrt(X * X + Y * Y);
+ public static double Dot(Vec2 a, Vec2 b) => a.X * b.X + a.Y * b.Y;
+}
+
+/// <summary>A line (<see cref="IsCurve"/> false) or cubic Bézier segment ending at <see cref="End"/>.</summary>
+internal readonly record struct PathSegment(bool IsCurve, Vec2 C1, Vec2 C2, Vec2 End);
+
+/// <summary>A closed contour: a start point and the segments that follow it (the closing line is implied).</summary>
+internal sealed class PathContour(Vec2 start)
+{
+ public Vec2 Start { get; set; } = start;
+ public List<PathSegment> Segments { get; } = [];
+}
+
+/// <summary>Interprets the charstrings of one CFF font. Not thread-safe: use one instance per thread.</summary>
+internal sealed class Type2Interpreter(CffFont font)
+{
+ private const int MaxSubrDepth = 10;
+
+ private readonly double[] _stack = new double[513];
+ private readonly double[] _transient = new double[32];
+ private readonly int _globalBias = Bias(font.GlobalSubrs.Length);
+ private List<PathContour> _contours = [];
+ private PathContour? _current;
+ private CffPrivate _private = new();
+ private int _localBias;
+ private int _count;
+ private int _stems;
+ private bool _widthParsed;
+ private bool _ended;
+ private double _x;
+ private double _y;
+ private (double Adx, double Ady, int Base, int Accent)? _seac;
+
+ /// <summary>Runs a glyph's charstring and returns its contours (seac accents are drawn in place).</summary>
+ public List<PathContour> Run(int glyph) => Run(glyph, allowSeac: true);
+
+ private List<PathContour> Run(int glyph, bool allowSeac)
+ {
+ if (glyph < 0 || glyph >= font.GlyphCount)
+ throw new InvalidDataException("A CFF accent refers to a missing glyph.");
+ _contours = [];
+ _current = null;
+ _private = font.Privates[Math.Min(font.FontDictIndex(glyph), font.Privates.Length - 1)];
+ _localBias = Bias(_private.Subrs.Length);
+ _count = _stems = 0;
+ _widthParsed = _ended = false;
+ _x = _y = 0;
+ _seac = null;
+
+ Execute(font.CharStrings[glyph], 0);
+ ClosePath();
+
+ var contours = _contours;
+ if (_seac is { } seac)
+ {
+ if (!allowSeac)
+ throw new InvalidDataException("A CFF accent is itself an accented glyph.");
+ var baseGlyph = font.GlyphBySid(CffStandardData.StandardEncoding[seac.Base & 0xFF]);
+ var accentGlyph = font.GlyphBySid(CffStandardData.StandardEncoding[seac.Accent & 0xFF]);
+ contours.AddRange(Run(baseGlyph, allowSeac: false));
+ foreach (var contour in Run(accentGlyph, allowSeac: false))
+ contours.Add(Translate(contour, new Vec2(seac.Adx, seac.Ady)));
+ }
+ return contours;
+ }
+
+ private static PathContour Translate(PathContour contour, Vec2 offset)
+ {
+ var moved = new PathContour(contour.Start + offset);
+ foreach (var s in contour.Segments)
+ moved.Segments.Add(s with { C1 = s.C1 + offset, C2 = s.C2 + offset, End = s.End + offset });
+ return moved;
+ }
+
+ /// <summary>Subroutine number bias, which depends on how many subroutines there are.</summary>
+ private static int Bias(int count) => count < 1240 ? 107 : count < 33900 ? 1131 : 32768;
+
+ private void Execute(byte[] code, int depth)
+ {
+ if (depth > MaxSubrDepth)
+ throw new InvalidDataException("CFF subroutines are nested too deeply.");
+ var r = new BigEndianReader(code);
+ while (r.Remaining > 0 && !_ended)
+ {
+ int b0 = r.U8();
+ if (b0 >= 32 || b0 == 28)
+ {
+ Push(b0 switch
+ {
+ 28 => r.I16(),
+ <= 246 => b0 - 139,
+ <= 250 => (b0 - 247) * 256 + r.U8() + 108,
+ <= 254 => -(b0 - 251) * 256 - r.U8() - 108,
+ _ => r.I32() / 65536.0, // 255: 16.16 fixed
+ });
+ continue;
+ }
+
+ switch (b0)
+ {
+ case 1 or 3 or 18 or 23: // hstem, vstem, hstemhm, vstemhm
+ Stems();
+ break;
+ case 19 or 20: // hintmask, cntrmask: pending arguments are an implicit vstemhm
+ Stems();
+ r.Skip((_stems + 7) / 8);
+ break;
+ case 21: // rmoveto
+ ParseWidth(2);
+ MoveTo(Arg(0), Arg(1));
+ break;
+ case 22: // hmoveto
+ ParseWidth(1);
+ MoveTo(Arg(0), 0);
+ break;
+ case 4: // vmoveto
+ ParseWidth(1);
+ MoveTo(0, Arg(0));
+ break;
+ case 5: // rlineto
+ for (var i = 0; i + 1 < _count; i += 2)
+ LineTo(_stack[i], _stack[i + 1]);
+ Clear();
+ break;
+ case 6 or 7: // hlineto, vlineto: alternating horizontal and vertical lines
+ for (var i = 0; i < _count; i++)
+ {
+ if ((i % 2 == 0) == (b0 == 6))
+ LineTo(_stack[i], 0);
+ else
+ LineTo(0, _stack[i]);
+ }
+ Clear();
+ break;
+ case 8: // rrcurveto
+ for (var i = 0; i + 5 < _count; i += 6)
+ CurveTo(i);
+ Clear();
+ break;
+ case 24: // rcurveline
+ {
+ var i = 0;
+ for (; i + 7 < _count; i += 6)
+ CurveTo(i);
+ if (i + 1 < _count)
+ LineTo(_stack[i], _stack[i + 1]);
+ Clear();
+ break;
+ }
+ case 25: // rlinecurve
+ {
+ var i = 0;
+ for (; i + 7 < _count; i += 2)
+ LineTo(_stack[i], _stack[i + 1]);
+ if (i + 5 < _count)
+ CurveTo(i);
+ Clear();
+ break;
+ }
+ case 26: // vvcurveto
+ {
+ var i = _count % 2;
+ var dx1 = i == 1 ? _stack[0] : 0;
+ for (; i + 3 < _count; i += 4, dx1 = 0)
+ CurveTo(dx1, _stack[i], _stack[i + 1], _stack[i + 2], 0, _stack[i + 3]);
+ Clear();
+ break;
+ }
+ case 27: // hhcurveto
+ {
+ var i = _count % 2;
+ var dy1 = i == 1 ? _stack[0] : 0;
+ for (; i + 3 < _count; i += 4, dy1 = 0)
+ CurveTo(_stack[i], dy1, _stack[i + 1], _stack[i + 2], _stack[i + 3], 0);
+ Clear();
+ break;
+ }
+ case 30 or 31: // vhcurveto, hvcurveto: curves alternating between vertical and horizontal tangents
+ {
+ var horizontal = b0 == 31;
+ for (var i = 0; i + 3 < _count; i += 4, horizontal = !horizontal)
+ {
+ var last = _count - i == 5 ? _stack[i + 4] : 0;
+ if (horizontal)
+ CurveTo(_stack[i], 0, _stack[i + 1], _stack[i + 2], last, _stack[i + 3]);
+ else
+ CurveTo(0, _stack[i], _stack[i + 1], _stack[i + 2], _stack[i + 3], last);
+ }
+ Clear();
+ break;
+ }
+ case 10: // callsubr
+ Execute(Subroutine(_private.Subrs, _localBias), depth + 1);
+ break;
+ case 29: // callgsubr
+ Execute(Subroutine(font.GlobalSubrs, _globalBias), depth + 1);
+ break;
+ case 11: // return
+ return;
+ case 14: // endchar, optionally with the four seac arguments
+ if (!_widthParsed && _count is 1 or 5)
+ TakeWidth();
+ _widthParsed = true;
+ if (_count >= 4)
+ _seac = (_stack[_count - 4], _stack[_count - 3], (int)_stack[_count - 2], (int)_stack[_count - 1]);
+ ClosePath();
+ _ended = true;
+ return;
+ case 12:
+ Escape(r.U8());
+ break;
+ case 15 or 16:
+ throw new NotSupportedException("The font uses CFF2 charstring operators (variable fonts), which aren't supported.");
+ default:
+ throw new InvalidDataException($"The CFF charstring uses an unknown operator ({b0}).");
+ }
+ }
+ }
+
+ private void Escape(int op)
+ {
+ switch (op)
+ {
+ case 0: // dotsection (deprecated hint)
+ Clear();
+ break;
+ case 3: // and
+ Binary((a, b) => a != 0 && b != 0 ? 1 : 0);
+ break;
+ case 4: // or
+ Binary((a, b) => a != 0 || b != 0 ? 1 : 0);
+ break;
+ case 5: // not
+ Push(Pop() == 0 ? 1 : 0);
+ break;
+ case 9: // abs
+ Push(Math.Abs(Pop()));
+ break;
+ case 10: // add
+ Binary((a, b) => a + b);
+ break;
+ case 11: // sub
+ Binary((a, b) => a - b);
+ break;
+ case 12: // div
+ Binary((a, b) => b == 0 ? 0 : a / b);
+ break;
+ case 14: // neg
+ Push(-Pop());
+ break;
+ case 15: // eq
+ Binary((a, b) => a == b ? 1 : 0);
+ break;
+ case 18: // drop
+ Pop();
+ break;
+ case 20: // put
+ {
+ var index = (int)Pop();
+ var value = Pop();
+ if (index is >= 0 and < 32)
+ _transient[index] = value;
+ break;
+ }
+ case 21: // get
+ {
+ var index = (int)Pop();
+ Push(index is >= 0 and < 32 ? _transient[index] : 0);
+ break;
+ }
+ case 22: // ifelse
+ {
+ var v2 = Pop();
+ var v1 = Pop();
+ var s2 = Pop();
+ var s1 = Pop();
+ Push(v1 <= v2 ? s1 : s2);
+ break;
+ }
+ case 23: // random: any value in (0, 1]; a fixed one keeps conversions reproducible
+ Push(0.5);
+ break;
+ case 24: // mul
+ Binary((a, b) => a * b);
+ break;
+ case 26: // sqrt
+ Push(Math.Sqrt(Math.Max(0, Pop())));
+ break;
+ case 27: // dup
+ {
+ var value = Pop();
+ Push(value);
+ Push(value);
+ break;
+ }
+ case 28: // exch
+ {
+ var b = Pop();
+ var a = Pop();
+ Push(b);
+ Push(a);
+ break;
+ }
+ case 29: // index
+ {
+ var i = (int)Pop();
+ if (i < 0)
+ i = 0;
+ Push(i < _count ? _stack[_count - 1 - i] : 0);
+ break;
+ }
+ case 30: // roll
+ {
+ var j = (int)Pop();
+ var n = (int)Pop();
+ if (n > 0 && n <= _count)
+ {
+ var items = _stack.AsSpan(_count - n, n).ToArray();
+ j = ((j % n) + n) % n;
+ for (var i = 0; i < n; i++)
+ _stack[_count - n + (i + j) % n] = items[i];
+ }
+ break;
+ }
+ case 34: // hflex
+ Need(7);
+ CurveTo(_stack[0], 0, _stack[1], _stack[2], _stack[3], 0);
+ CurveTo(_stack[4], 0, _stack[5], -_stack[2], _stack[6], 0);
+ Clear();
+ break;
+ case 35: // flex
+ Need(12);
+ CurveTo(0);
+ CurveTo(6);
+ Clear();
+ break;
+ case 36: // hflex1
+ Need(9);
+ CurveTo(_stack[0], _stack[1], _stack[2], _stack[3], _stack[4], 0);
+ CurveTo(_stack[5], 0, _stack[6], _stack[7], _stack[8], -(_stack[1] + _stack[3] + _stack[7]));
+ Clear();
+ break;
+ case 37: // flex1: the last point moves along the dominant direction only
+ {
+ Need(11);
+ double dx = 0, dy = 0;
+ for (var i = 0; i < 10; i += 2)
+ {
+ dx += _stack[i];
+ dy += _stack[i + 1];
+ }
+ var horizontal = Math.Abs(dx) > Math.Abs(dy);
+ CurveTo(0);
+ CurveTo(_stack[6], _stack[7], _stack[8], _stack[9], horizontal ? _stack[10] : -dx, horizontal ? -dy : _stack[10]);
+ Clear();
+ break;
+ }
+ default:
+ throw new InvalidDataException($"The CFF charstring uses an unknown operator (12 {op}).");
+ }
+ }
+
+ private byte[] Subroutine(byte[][] subrs, int bias)
+ {
+ var index = (int)Pop() + bias;
+ if (index < 0 || index >= subrs.Length)
+ throw new InvalidDataException("A CFF charstring calls a missing subroutine.");
+ return subrs[index];
+ }
+
+ /// <summary>Stem hints: an odd argument count on the first hint means the width comes first.</summary>
+ private void Stems()
+ {
+ if (!_widthParsed && _count % 2 == 1)
+ TakeWidth();
+ _widthParsed = true;
+ _stems += _count / 2;
+ Clear();
+ }
+
+ /// <summary>
+ /// The first stack-clearing operator may carry the advance width as an extra first argument. It is dropped:
+ /// hmtx holds the same widths.
+ /// </summary>
+ private void ParseWidth(int expected)
+ {
+ if (!_widthParsed && _count > expected)
+ TakeWidth();
+ _widthParsed = true;
+ }
+
+ private void TakeWidth()
+ {
+ Array.Copy(_stack, 1, _stack, 0, _count - 1);
+ _count--;
+ }
+
+ private void MoveTo(double dx, double dy)
+ {
+ ClosePath();
+ _x += dx;
+ _y += dy;
+ _current = new PathContour(new Vec2(_x, _y));
+ Clear();
+ }
+
+ private void LineTo(double dx, double dy)
+ {
+ var start = EnsureContour();
+ _x += dx;
+ _y += dy;
+ start.Segments.Add(new PathSegment(false, default, default, new Vec2(_x, _y)));
+ }
+
+ private void CurveTo(int i) =>
+ CurveTo(_stack[i], _stack[i + 1], _stack[i + 2], _stack[i + 3], _stack[i + 4], _stack[i + 5]);
+
+ private void CurveTo(double dxa, double dya, double dxb, double dyb, double dxc, double dyc)
+ {
+ var contour = EnsureContour();
+ var c1 = new Vec2(_x + dxa, _y + dya);
+ var c2 = new Vec2(c1.X + dxb, c1.Y + dyb);
+ _x = c2.X + dxc;
+ _y = c2.Y + dyc;
+ contour.Segments.Add(new PathSegment(true, c1, c2, new Vec2(_x, _y)));
+ }
+
+ /// <summary>Drawing without a moveto starts a contour at the current point (sloppy but seen in the wild).</summary>
+ private PathContour EnsureContour() => _current ??= new PathContour(new Vec2(_x, _y));
+
+ private void ClosePath()
+ {
+ if (_current is { Segments.Count: > 0 })
+ _contours.Add(_current);
+ _current = null;
+ }
+
+ private double Arg(int i) => i < _count ? _stack[i] : 0;
+
+ private void Need(int count)
+ {
+ if (_count < count)
+ throw new InvalidDataException("A CFF charstring has too few arguments.");
+ }
+
+ private void Push(double value)
+ {
+ if (_count >= _stack.Length)
+ throw new InvalidDataException("A CFF charstring overflows the argument stack.");
+ _stack[_count++] = value;
+ }
+
+ private double Pop() => _count > 0 ? _stack[--_count] : throw new InvalidDataException("A CFF charstring has too few arguments.");
+
+ private void Binary(Func<double, double, double> op)
+ {
+ var b = Pop();
+ var a = Pop();
+ Push(op(a, b));
+ }
+
+ private void Clear() => _count = 0;
+}
diff --git a/src/Filee.Engines/Fonts/CffToTrueType.cs b/src/Filee.Engines/Fonts/CffToTrueType.cs
new file mode 100644
index 00000000..f89d1b0d
--- /dev/null
+++ b/src/Filee.Engines/Fonts/CffToTrueType.cs
@@ -0,0 +1,326 @@
+// Converts an OpenType font with CFF (PostScript, cubic) outlines to TrueType (quadratic) outlines: builds glyf,
+// loca, maxp 1.0 and post, updates head, hhea, hmtx and vmtx, and keeps every other table (cmap, name, OS/2, GSUB,
+// GPOS, kern, ...) unchanged. Hints are not converted; a gasp/prep pair asks rasterizers to smooth instead.
+
+using System.Buffers.Binary;
+using System.Text;
+using Filee.Engines.Fonts.Cff;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>CFF → TrueType outline conversion.</summary>
+internal static class CffToTrueType
+{
+ /// <summary>
+ /// Maximum distance between a converted curve and the original, in em units (1 unit at 1000 units per em), as
+ /// fontTools' otf2ttf uses.
+ /// </summary>
+ private const double ToleranceEm = 0.001;
+
+ /// <summary>prep that switches on dropout control (SCANCTRL 511, SCANTYPE 4), as recommended for unhinted fonts.</summary>
+ private static readonly byte[] UnhintedPrep = [0xB8, 0x01, 0xFF, 0x85, 0xB0, 0x04, 0x8D];
+
+ /// <summary>gasp version 1 with one range: grid-fit and smooth (symmetrically) at every size.</summary>
+ private static readonly byte[] SmoothGasp = [0, 1, 0, 1, 0xFF, 0xFF, 0, 0x0F];
+
+ /// <summary>Returns a TrueType-outline copy of <paramref name="source"/>.</summary>
+ /// <exception cref="NotSupportedException">CFF2 (variable) outlines.</exception>
+ public static SfntFont Convert(SfntFont source, CancellationToken cancellationToken = default, IProgress<double>? progress = null)
+ {
+ if (source["CFF2"] is not null)
+ throw new NotSupportedException(
+ "This is a variable font with CFF2 outlines. Converting CFF2 to TrueType isn't supported; WOFF, WOFF2 and OTF work.");
+ var cff = CffFont.Parse(source.Require("CFF "));
+ var glyphCount = source.GlyphCount;
+ if (cff.GlyphCount != glyphCount)
+ throw new InvalidDataException("The font's CFF outlines and glyph count don't match.");
+
+ var head = source.Require("head");
+ var upem = FontTables.UnitsPerEm(head);
+ var tolerance = Math.Max(upem, 16) * ToleranceEm;
+ var matrices = cff.FontMatrices.Select(m => ToFontUnits(m, upem)).ToArray();
+
+ var interpreter = new Type2Interpreter(cff);
+ var glyphs = new TrueTypeGlyph?[glyphCount];
+ for (var gid = 0; gid < glyphCount; gid++)
+ {
+ if (gid % 64 == 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report((double)gid / glyphCount);
+ }
+ var contours = interpreter.Run(gid);
+ if (matrices[Math.Min(cff.FontDictIndex(gid), matrices.Length - 1)] is { } matrix)
+ contours = [.. contours.Select(c => Transform(c, matrix))];
+ glyphs[gid] = BuildGlyph(contours, tolerance);
+ }
+
+ var font = source.Clone();
+ foreach (var tag in new[] { "CFF ", "VORG", "DSIG" })
+ font.Tables.Remove(tag);
+ font.Flavor = SfntFont.TrueTypeFlavor;
+
+ var (glyf, loca, longLoca) = GlyfTable.Build([.. glyphs.Select(g => g?.Serialize() ?? [])], longFormat: false, alignment: 2);
+ font.Tables["glyf"] = glyf;
+ font.Tables["loca"] = loca;
+ font.Tables["head"] = UpdateHead(head, glyphs, longLoca);
+ font.Tables["maxp"] = BuildMaxp(glyphs);
+ font.Tables["post"] = BuildPost(source["post"], Enumerable.Range(0, glyphCount).Select(cff.GlyphName).ToArray());
+ if (font["hhea"] is { Length: >= 36 } hhea && font["hmtx"] is { } hmtx)
+ (font.Tables["hhea"], font.Tables["hmtx"]) = UpdateHorizontalMetrics(hhea, hmtx, glyphs);
+ if (source["VORG"] is { } vorg && font["vhea"] is { Length: >= 36 } vhea && font["vmtx"] is { } vmtx)
+ (font.Tables["vhea"], font.Tables["vmtx"]) = UpdateVerticalMetrics(vhea, vmtx, vorg, glyphs);
+ if (!font.Tables.ContainsKey("gasp") && !font.Tables.ContainsKey("prep"))
+ {
+ font.Tables["gasp"] = SmoothGasp;
+ font.Tables["prep"] = UnhintedPrep;
+ }
+ progress?.Report(1);
+ return font;
+ }
+
+ /// <summary>FontMatrix scaled to font units; null when it is the identity (the usual 1/unitsPerEm matrix).</summary>
+ private static double[]? ToFontUnits(double[] matrix, int upem)
+ {
+ var m = matrix.Select(v => v * upem).ToArray();
+ double[] identity = [1, 0, 0, 1, 0, 0];
+ return m.Zip(identity).All(p => Math.Abs(p.First - p.Second) < 1e-9) ? null : m;
+ }
+
+ private static PathContour Transform(PathContour contour, double[] m)
+ {
+ Vec2 Apply(Vec2 p) => new(m[0] * p.X + m[2] * p.Y + m[4], m[1] * p.X + m[3] * p.Y + m[5]);
+ var result = new PathContour(Apply(contour.Start));
+ foreach (var s in contour.Segments)
+ result.Segments.Add(new PathSegment(s.IsCurve, Apply(s.C1), Apply(s.C2), Apply(s.End)));
+ return result;
+ }
+
+ /// <summary>
+ /// Builds a TrueType glyph: curves become quadratic splines, points are rounded to integers, and every contour is
+ /// reversed because TrueType fills clockwise outer contours while PostScript draws them counter-clockwise.
+ /// </summary>
+ private static TrueTypeGlyph? BuildGlyph(List<PathContour> contours, double tolerance)
+ {
+ var endPoints = new List<ushort>();
+ var points = new List<GlyphPoint>();
+ foreach (var contour in contours)
+ {
+ var raw = new List<(Vec2 P, bool On)> { (contour.Start, true) };
+ var current = contour.Start;
+ foreach (var segment in contour.Segments)
+ {
+ if (segment.IsCurve)
+ {
+ foreach (var control in CubicToQuadratic.Convert(current, segment.C1, segment.C2, segment.End, tolerance))
+ raw.Add((control, false));
+ }
+ raw.Add((segment.End, true));
+ current = segment.End;
+ }
+
+ var rounded = Clean([.. raw.Select(p => new GlyphPoint(Round(p.P.X), Round(p.P.Y), p.On))]);
+ if (rounded.Count < 3)
+ continue; // nothing left to fill
+ points.Add(rounded[0]);
+ for (var i = rounded.Count - 1; i > 0; i--)
+ points.Add(rounded[i]);
+ if (points.Count > 0xFFFF)
+ throw new InvalidDataException("A glyph has more points than TrueType allows.");
+ endPoints.Add((ushort)(points.Count - 1));
+ }
+ if (endPoints.Count == 0)
+ return null;
+
+ var glyph = new TrueTypeGlyph
+ {
+ NumberOfContours = (short)endPoints.Count,
+ EndPoints = [.. endPoints],
+ Points = [.. points],
+ };
+ (glyph.XMin, glyph.YMin, glyph.XMax, glyph.YMax) = glyph.ComputeBounds();
+ return glyph;
+ }
+
+ /// <summary>
+ /// Drops the closing point when it repeats the start (the contour closes by itself) and on-curve points that
+ /// repeat their predecessor after rounding (zero-length lines).
+ /// </summary>
+ private static List<GlyphPoint> Clean(List<GlyphPoint> points)
+ {
+ var result = new List<GlyphPoint>(points.Count);
+ foreach (var p in points)
+ {
+ if (result.Count > 0 && p.OnCurve && result[^1].OnCurve && result[^1].X == p.X && result[^1].Y == p.Y)
+ continue;
+ result.Add(p);
+ }
+ while (result.Count > 1 && result[^1].OnCurve && result[^1].X == result[0].X && result[^1].Y == result[0].Y)
+ result.RemoveAt(result.Count - 1);
+ return result;
+ }
+
+ private static int Round(double value) => (int)Math.Floor(value + 0.5);
+
+ private static byte[] UpdateHead(byte[] head, TrueTypeGlyph?[] glyphs, bool longLoca)
+ {
+ var result = FontTables.WithIndexToLocFormat(head, longLoca);
+ var outlines = glyphs.OfType<TrueTypeGlyph>().ToList();
+ if (outlines.Count > 0)
+ {
+ BinaryPrimitives.WriteInt16BigEndian(result.AsSpan(36), outlines.Min(g => g.XMin));
+ BinaryPrimitives.WriteInt16BigEndian(result.AsSpan(38), outlines.Min(g => g.YMin));
+ BinaryPrimitives.WriteInt16BigEndian(result.AsSpan(40), outlines.Max(g => g.XMax));
+ BinaryPrimitives.WriteInt16BigEndian(result.AsSpan(42), outlines.Max(g => g.YMax));
+ }
+ BinaryPrimitives.WriteInt16BigEndian(result.AsSpan(52), 0); // glyphDataFormat
+ return result;
+ }
+
+ /// <summary>maxp version 1.0: outline maxima; no hinting instructions beyond the dropout-control prep.</summary>
+ private static byte[] BuildMaxp(TrueTypeGlyph?[] glyphs)
+ {
+ var w = new BigEndianWriter(32);
+ w.U32(0x00010000);
+ w.U16(glyphs.Length);
+ w.U16(glyphs.Max(g => g?.Points.Length ?? 0)); // maxPoints
+ w.U16(glyphs.Max(g => (int?)g?.NumberOfContours ?? 0)); // maxContours
+ w.U16(0); // maxCompositePoints
+ w.U16(0); // maxCompositeContours
+ w.U16(1); // maxZones: no twilight zone
+ w.U16(0); // maxTwilightPoints
+ w.U16(0); // maxStorage
+ w.U16(0); // maxFunctionDefs
+ w.U16(0); // maxInstructionDefs
+ w.U16(1); // maxStackElements (the prep pushes one value at a time)
+ w.U16(0); // maxSizeOfInstructions
+ w.U16(0); // maxComponentElements
+ w.U16(0); // maxComponentDepth
+ return w.ToArray();
+ }
+
+ /// <summary>
+ /// post format 2.0 with the CFF glyph names when the font has them (name-keyed CFF), else format 3.0 (CID-keyed
+ /// fonts have no names). The header fields (italic angle, underline) are kept.
+ /// </summary>
+ internal static byte[] BuildPost(byte[]? old, string?[] names)
+ {
+ var w = new BigEndianWriter(64 + names.Length * 10);
+ var header = new byte[32];
+ old?.AsSpan(0, Math.Min(32, old.Length)).CopyTo(header);
+ var usable = names.All(n => n is { Length: > 0 and < 256 } && n.All(c => c is > ' ' and < (char)127));
+ BinaryPrimitives.WriteUInt32BigEndian(header, usable ? 0x00020000u : 0x00030000u);
+ w.Bytes(header);
+ if (!usable)
+ return w.ToArray();
+
+ var standard = CffStandardData.MacGlyphNames.Select((n, i) => (n, i)).ToDictionary(p => p.n, p => p.i);
+ var custom = new Dictionary<string, int>(StringComparer.Ordinal);
+ var extra = new List<string>();
+ w.U16(names.Length);
+ foreach (var name in names)
+ {
+ if (standard.TryGetValue(name!, out var index))
+ {
+ w.U16(index);
+ continue;
+ }
+ if (!custom.TryGetValue(name!, out index))
+ {
+ index = custom[name!] = standard.Count + extra.Count;
+ extra.Add(name!);
+ }
+ w.U16(index);
+ }
+ foreach (var name in extra)
+ {
+ w.U8(name.Length);
+ w.Bytes(Encoding.ASCII.GetBytes(name));
+ }
+ return w.ToArray();
+ }
+
+ /// <summary>Sets each left side bearing to the new xMin and recomputes hhea's extremes.</summary>
+ private static (byte[] Hhea, byte[] Hmtx) UpdateHorizontalMetrics(byte[] hhea, byte[] hmtx, TrueTypeGlyph?[] glyphs)
+ {
+ var metrics = FontTables.NumberOfMetrics(hhea);
+ var advances = ReadMetrics(hmtx, metrics, glyphs.Length, out _);
+ var lsbs = glyphs.Select(g => (int)(g?.XMin ?? 0)).ToArray();
+ var result = WriteMetrics(advances, lsbs, metrics);
+
+ var header = (byte[])hhea.Clone();
+ var withOutlines = Enumerable.Range(0, glyphs.Length).Where(i => glyphs[i] is not null).ToList();
+ BinaryPrimitives.WriteUInt16BigEndian(header.AsSpan(10), (ushort)advances.DefaultIfEmpty(0).Max());
+ if (withOutlines.Count > 0)
+ {
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(12), (short)withOutlines.Min(i => glyphs[i]!.XMin));
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(14), (short)withOutlines.Min(i => advances[i] - glyphs[i]!.XMax));
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(16), (short)withOutlines.Max(i => glyphs[i]!.XMax));
+ }
+ return (header, result);
+ }
+
+ /// <summary>
+ /// TrueType has no VORG: the vertical origin is yMax + top side bearing. Set each top side bearing so the origin
+ /// stays where VORG put it, and recompute vhea's extremes.
+ /// </summary>
+ private static (byte[] Vhea, byte[] Vmtx) UpdateVerticalMetrics(byte[] vhea, byte[] vmtx, byte[] vorg, TrueTypeGlyph?[] glyphs)
+ {
+ var metrics = FontTables.NumberOfMetrics(vhea);
+ var heights = ReadMetrics(vmtx, metrics, glyphs.Length, out var tsbs);
+ var r = new BigEndianReader(vorg);
+ r.Skip(4); // version
+ int defaultOrigin = r.I16();
+ int count = r.U16();
+ var origins = new Dictionary<int, int>();
+ for (var i = 0; i < count; i++)
+ origins[r.U16()] = r.I16();
+
+ for (var i = 0; i < glyphs.Length; i++)
+ {
+ if (glyphs[i] is { } glyph)
+ tsbs[i] = origins.GetValueOrDefault(i, defaultOrigin) - glyph.YMax;
+ }
+ var result = WriteMetrics(heights, tsbs, metrics);
+
+ var header = (byte[])vhea.Clone();
+ var withOutlines = Enumerable.Range(0, glyphs.Length).Where(i => glyphs[i] is not null).ToList();
+ if (withOutlines.Count > 0)
+ {
+ int Extent(int i) => tsbs[i] + glyphs[i]!.YMax - glyphs[i]!.YMin;
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(12), (short)withOutlines.Min(i => tsbs[i]));
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(14), (short)withOutlines.Min(i => heights[i] - Extent(i)));
+ BinaryPrimitives.WriteInt16BigEndian(header.AsSpan(16), (short)withOutlines.Max(Extent));
+ }
+ return (header, result);
+ }
+
+ /// <summary>Reads hmtx/vmtx: the advance of every glyph (the last one repeats) and the side bearings.</summary>
+ private static int[] ReadMetrics(byte[] table, int metrics, int glyphCount, out int[] bearings)
+ {
+ var r = new BigEndianReader(table);
+ var advances = new int[glyphCount];
+ bearings = new int[glyphCount];
+ var last = 0;
+ for (var i = 0; i < glyphCount; i++)
+ {
+ if (i < metrics)
+ last = r.U16();
+ advances[i] = last;
+ bearings[i] = r.Remaining >= 2 ? r.I16() : 0;
+ }
+ return advances;
+ }
+
+ private static byte[] WriteMetrics(int[] advances, int[] bearings, int metrics)
+ {
+ var w = new BigEndianWriter(advances.Length * 4);
+ for (var i = 0; i < advances.Length; i++)
+ {
+ if (i < metrics)
+ w.U16(advances[i]);
+ w.I16(bearings[i]);
+ }
+ return w.ToArray();
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Eot.cs b/src/Filee.Engines/Fonts/Eot.cs
new file mode 100644
index 00000000..c8286e38
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Eot.cs
@@ -0,0 +1,168 @@
+// Embedded OpenType (EOT, W3C Member Submission 2008), the web font format of Internet Explorer 6–8: a little-endian
+// header with names and OS/2 fields in front of the font. Writes version 0x00020001 without MicroType Express
+// compression or XOR obfuscation; reads uncompressed files of every version.
+
+using System.Buffers.Binary;
+using System.Text;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Encodes and decodes EOT files.</summary>
+internal static class Eot
+{
+ /// <summary>MagicNumber at offset 34 (little-endian 0x504C).</summary>
+ private const ushort Magic = 0x504C;
+
+ private const uint Version = 0x00020001;
+
+ /// <summary>TTEMBED_TTCOMPRESSED: the font data is MicroType Express compressed.</summary>
+ private const uint CompressedFlag = 0x4;
+
+ /// <summary>TTEMBED_XORENCRYPTDATA: every font byte is XORed with 0x50.</summary>
+ private const uint XorFlag = 0x10000000;
+
+ private const byte DefaultCharset = 1;
+
+ /// <summary>True when the data starts like an EOT header.</summary>
+ public static bool IsEot(ReadOnlySpan<byte> data) =>
+ data.Length >= 82 && BinaryPrimitives.ReadUInt16LittleEndian(data[34..]) == Magic &&
+ BinaryPrimitives.ReadUInt32LittleEndian(data[8..]) is 0x00010000 or 0x00020001 or 0x00020002;
+
+ /// <summary>Wraps a TrueType font in an EOT header (the caller converts CFF outlines first).</summary>
+ public static byte[] Encode(SfntFont font)
+ {
+ var sfnt = font.Write();
+ var written = SfntFont.Read(sfnt);
+ var os2 = written["OS/2"] ?? [];
+ var head = written.Require("head");
+ var names = NameTable.Read(written["name"]);
+
+ using var output = new MemoryStream(sfnt.Length + 512);
+ using (var w = new BinaryWriter(output, Encoding.Unicode, leaveOpen: true)) // BinaryWriter is little-endian
+ {
+ w.Write(0u); // EOTSize, patched below
+ w.Write((uint)sfnt.Length);
+ w.Write(Version);
+ w.Write(0u); // flags: not compressed, not obfuscated, not a subset
+ w.Write(Slice(os2, 32, 10)); // PANOSE
+ w.Write(DefaultCharset);
+ w.Write((byte)(U16(os2, 62) & 1)); // italic: fsSelection bit 0
+ w.Write((uint)U16(os2, 4)); // usWeightClass
+ w.Write(U16(os2, 8)); // fsType (embedding permissions)
+ w.Write(Magic);
+ for (var i = 0; i < 4; i++)
+ w.Write(U32(os2, 42 + 4 * i)); // ulUnicodeRange1–4
+ for (var i = 0; i < 2; i++)
+ w.Write(U32(os2, 78 + 4 * i)); // ulCodePageRange1–2 (OS/2 version 1 and later)
+ w.Write(U32(head, 8)); // checkSumAdjustment
+ for (var i = 0; i < 4; i++)
+ w.Write(0u); // reserved
+ w.Write((ushort)0); // padding1
+ WriteName(w, names.Get(1)); // family
+ w.Write((ushort)0);
+ WriteName(w, names.Get(2)); // style
+ w.Write((ushort)0);
+ WriteName(w, names.Get(5)); // version
+ w.Write((ushort)0);
+ WriteName(w, names.Get(4)); // full name
+ w.Write((ushort)0); // padding5
+ w.Write((ushort)0); // RootStringSize: no URL restriction
+ w.Write(sfnt);
+ }
+ var eot = output.ToArray();
+ BinaryPrimitives.WriteUInt32LittleEndian(eot, (uint)eot.Length);
+ return eot;
+ }
+
+ /// <summary>Extracts the font from an EOT file.</summary>
+ /// <exception cref="NotSupportedException">The font data is MicroType Express compressed.</exception>
+ public static SfntFont Decode(byte[] data)
+ {
+ if (!IsEot(data))
+ throw new InvalidDataException("This is not an EOT file.");
+ var eotSize = BinaryPrimitives.ReadUInt32LittleEndian(data);
+ var fontSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4));
+ var flags = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12));
+ if ((flags & CompressedFlag) != 0)
+ throw new NotSupportedException(
+ "This EOT file is compressed with MicroType Express, which Filee can't unpack. Only uncompressed EOT files can be converted.");
+ if (eotSize > data.Length || eotSize < 82 || fontSize > eotSize - 82)
+ throw new InvalidDataException("The EOT file is truncated or damaged.");
+
+ // The font data is the last field of every EOT version, so its offset doesn't depend on the header version.
+ var font = data.AsSpan((int)(eotSize - fontSize), (int)fontSize).ToArray();
+ if ((flags & XorFlag) != 0)
+ {
+ for (var i = 0; i < font.Length; i++)
+ font[i] ^= 0x50;
+ }
+ return SfntFont.Read(font);
+ }
+
+ private static void WriteName(BinaryWriter w, string value)
+ {
+ var bytes = Encoding.Unicode.GetBytes(value); // UTF-16LE
+ w.Write((ushort)bytes.Length);
+ w.Write(bytes);
+ }
+
+ private static byte[] Slice(byte[] table, int offset, int length) =>
+ table.Length >= offset + length ? table[offset..(offset + length)] : new byte[length];
+
+ private static ushort U16(byte[] table, int offset) =>
+ table.Length >= offset + 2 ? BinaryPrimitives.ReadUInt16BigEndian(table.AsSpan(offset)) : (ushort)0;
+
+ private static uint U32(byte[] table, int offset) =>
+ table.Length >= offset + 4 ? BinaryPrimitives.ReadUInt32BigEndian(table.AsSpan(offset)) : 0;
+}
+
+/// <summary>Reads strings from the 'name' table.</summary>
+internal sealed class NameTable
+{
+ private readonly List<(int Platform, int Encoding, int Language, int NameId, string Value)> _records = [];
+
+ public static NameTable Read(byte[]? name)
+ {
+ var table = new NameTable();
+ if (name is null || name.Length < 6)
+ return table;
+ try
+ {
+ var r = new BigEndianReader(name);
+ r.U16(); // format
+ int count = r.U16();
+ int stringOffset = r.U16();
+ for (var i = 0; i < count; i++)
+ {
+ int platform = r.U16(), encoding = r.U16(), language = r.U16(), nameId = r.U16(), length = r.U16(), offset = r.U16();
+ if (stringOffset + offset + length > name.Length)
+ continue;
+ var bytes = name.AsSpan(stringOffset + offset, length);
+ string? value = platform switch
+ {
+ 0 or 3 => Encoding.BigEndianUnicode.GetString(bytes),
+ 1 when encoding == 0 => Encoding.Latin1.GetString(bytes), // Mac Roman; ASCII names read the same
+ _ => null,
+ };
+ if (value is not null)
+ table._records.Add((platform, encoding, language, nameId, value));
+ }
+ }
+ catch (InvalidDataException)
+ {
+ // A damaged name table only costs the names.
+ }
+ return table;
+ }
+
+ /// <summary>Returns a name, preferring Windows English (US), then any Windows or Unicode entry, then Macintosh.</summary>
+ public string Get(int nameId)
+ {
+ var candidates = _records.Where(r => r.NameId == nameId).ToList();
+ return candidates.FirstOrDefault(r => r is { Platform: 3, Language: 0x409 }).Value
+ ?? candidates.FirstOrDefault(r => r.Platform == 3).Value
+ ?? candidates.FirstOrDefault(r => r.Platform == 0).Value
+ ?? candidates.FirstOrDefault().Value
+ ?? "";
+ }
+}
diff --git a/src/Filee.Engines/Fonts/FontConverter.cs b/src/Filee.Engines/Fonts/FontConverter.cs
new file mode 100644
index 00000000..9c0f8df8
--- /dev/null
+++ b/src/Filee.Engines/Fonts/FontConverter.cs
@@ -0,0 +1,43 @@
+// Font conversion between TTF, OTF, WOFF, WOFF2 and EOT, entirely in managed code (zlib and Brotli come with .NET).
+// CFF (PostScript) outlines are converted to TrueType when the target needs them (TTF, EOT). See docs/ENGINES.md.
+
+using Filee.Core.Conversion;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Converts web and desktop font formats into each other.</summary>
+public sealed class FontConverter : IConverter
+{
+ public string Id => "font";
+ public string DisplayName => "Fonts (built-in)";
+ public int MaxParallelism => 0;
+
+ /// <summary>Every format to every other one, directly.</summary>
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [.. from source in FontFile.Formats from target in FontFile.Formats where source != target select new ConversionEdge(source, target)];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("TTF, OTF, WOFF, WOFF2, EOT");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var font = FontFile.Load(File.ReadAllBytes(step.InputPath), cancellationToken);
+ progress?.Report(0.2);
+ var outlines = progress is null ? null : new SubProgress(progress, 0.2, 0.6);
+ var data = FontFile.Save(font, step.To, cancellationToken, outlines);
+ progress?.Report(0.9);
+
+ var output = step.Output.Allocate(step.To);
+ if (output is null)
+ return [];
+ File.WriteAllBytes(output, data);
+ progress?.Report(1);
+ return [output];
+ }, cancellationToken);
+
+ /// <summary>Maps 0–1 progress of one phase onto a slice of the step's progress, synchronously.</summary>
+ private sealed class SubProgress(IProgress<double> parent, double start, double length) : IProgress<double>
+ {
+ public void Report(double value) => parent.Report(start + length * value);
+ }
+}
diff --git a/src/Filee.Engines/Fonts/FontFile.cs b/src/Filee.Engines/Fonts/FontFile.cs
new file mode 100644
index 00000000..ca1627e0
--- /dev/null
+++ b/src/Filee.Engines/Fonts/FontFile.cs
@@ -0,0 +1,63 @@
+// Loads a font file of any supported container (TTF/OTF/TTC, WOFF, WOFF2, EOT), recognised by its content rather
+// than its extension, and saves a font as TTF, OTF, WOFF, WOFF2 or EOT.
+
+using System.Buffers.Binary;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Reading and writing font files in every supported format.</summary>
+internal static class FontFile
+{
+ /// <summary>Format ids (see FormatRegistry) this engine reads and writes.</summary>
+ public static readonly string[] Formats = ["ttf", "otf", "woff", "woff2", "eot"];
+
+ /// <summary>Decodes a font file, whatever its container.</summary>
+ public static SfntFont Load(byte[] data, CancellationToken cancellationToken = default)
+ {
+ if (data.Length >= 4)
+ {
+ switch (BinaryPrimitives.ReadUInt32BigEndian(data))
+ {
+ case Woff.Signature:
+ return Woff.Decode(data);
+ case Woff2.Signature:
+ return Woff2.Decode(data, cancellationToken);
+ }
+ }
+ if (SfntFont.IsSfnt(data))
+ return SfntFont.Read(data);
+ if (Eot.IsEot(data))
+ return Eot.Decode(data);
+ throw new InvalidDataException("This file is not a font Filee can read (TTF, OTF, WOFF, WOFF2 or EOT).");
+ }
+
+ /// <summary>
+ /// Encodes the font as <paramref name="format"/>. TTF and EOT need TrueType outlines, so CFF outlines are
+ /// converted first; OTF keeps whatever outlines the font has (TrueType-flavoured OpenType is valid OpenType).
+ /// </summary>
+ public static byte[] Save(SfntFont font, string format, CancellationToken cancellationToken = default, IProgress<double>? progress = null)
+ {
+ switch (format)
+ {
+ case "ttf":
+ return TrueTypeOutlines(font, cancellationToken, progress).Write();
+ case "otf":
+ return font.Write();
+ case "woff":
+ return Woff.Encode(font, cancellationToken);
+ case "woff2":
+ return Woff2.Encode(font, cancellationToken, progress);
+ case "eot":
+ // Internet Explorer, the only EOT consumer, renders EOT fonts with TrueType outlines only.
+ return Eot.Encode(TrueTypeOutlines(font, cancellationToken, progress));
+ default:
+ throw new ArgumentException($"Unknown font format '{format}'.", nameof(format));
+ }
+ }
+
+ /// <summary>The font itself when it has TrueType outlines, else a converted copy (CFF2 fails with a clear message).</summary>
+ private static SfntFont TrueTypeOutlines(SfntFont font, CancellationToken cancellationToken, IProgress<double>? progress) =>
+ font["glyf"] is null && (font["CFF "] is not null || font["CFF2"] is not null)
+ ? CffToTrueType.Convert(font, cancellationToken, progress)
+ : font;
+}
diff --git a/src/Filee.Engines/Fonts/SfntFont.cs b/src/Filee.Engines/Fonts/SfntFont.cs
new file mode 100644
index 00000000..fa77cec6
--- /dev/null
+++ b/src/Filee.Engines/Fonts/SfntFont.cs
@@ -0,0 +1,194 @@
+// The OpenType / TrueType container (SFNT): a flavour plus a set of tables. Reads TTF / OTF (and the first font of a
+// TTC collection) and writes them back with correct checksums, head.checkSumAdjustment and search fields.
+
+using System.Buffers.Binary;
+using System.Numerics;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>An OpenType font as a set of raw tables, independent of the container it came in.</summary>
+internal sealed class SfntFont
+{
+ /// <summary>sfntVersion of fonts with TrueType outlines.</summary>
+ public const uint TrueTypeFlavor = 0x00010000;
+
+ /// <summary>sfntVersion 'OTTO': fonts with CFF outlines.</summary>
+ public const uint CffFlavor = 0x4F54544F;
+
+ /// <summary>sfntVersion 'true', used by old Apple TrueType fonts.</summary>
+ public const uint AppleTrueTypeFlavor = 0x74727565;
+
+ /// <summary>'ttcf': a TrueType collection header.</summary>
+ public const uint CollectionTag = 0x74746366;
+
+ /// <summary>checkSumAdjustment = this value minus the checksum of the whole file.</summary>
+ private const uint ChecksumMagic = 0xB1B0AFBA;
+
+ /// <summary>Data order recommended by the OpenType spec for TrueType and CFF fonts; other tables follow by tag.</summary>
+ private static readonly string[] TrueTypeOrder =
+ ["head", "hhea", "maxp", "OS/2", "hmtx", "LTSH", "VDMX", "hdmx", "cmap", "fpgm", "prep", "cvt ", "loca", "glyf", "kern", "name", "post", "gasp", "PCLT"];
+
+ private static readonly string[] CffOrder = ["head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF "];
+
+ public SfntFont(uint flavor) => Flavor = flavor;
+
+ /// <summary>sfntVersion: <see cref="TrueTypeFlavor"/> or <see cref="CffFlavor"/>.</summary>
+ public uint Flavor { get; set; }
+
+ /// <summary>Table data by four-character tag (e.g. "head", "CFF ", "OS/2").</summary>
+ public Dictionary<string, byte[]> Tables { get; } = new(StringComparer.Ordinal);
+
+ /// <summary>Returns a table or null.</summary>
+ public byte[]? this[string tag] => Tables.GetValueOrDefault(tag);
+
+ /// <summary>True when the glyphs are CFF (PostScript) outlines.</summary>
+ public bool HasCffOutlines => Tables.ContainsKey("CFF ") && !Tables.ContainsKey("glyf");
+
+ /// <summary>Returns a table or throws a readable error when a required table is missing.</summary>
+ public byte[] Require(string tag) =>
+ this[tag] ?? throw new InvalidDataException($"The font has no '{tag.Trim()}' table.");
+
+ /// <summary>Number of glyphs (maxp.numGlyphs).</summary>
+ public int GlyphCount => BinaryPrimitives.ReadUInt16BigEndian(Require("maxp").AsSpan(4));
+
+ /// <summary>Converts a tag string to its 32-bit value.</summary>
+ public static uint TagValue(string tag) =>
+ (uint)tag[0] << 24 | (uint)tag[1] << 16 | (uint)tag[2] << 8 | tag[3];
+
+ /// <summary>Converts a 32-bit tag to its four-character string.</summary>
+ public static string TagName(uint tag) =>
+ string.Create(4, tag, static (span, t) =>
+ {
+ for (var i = 0; i < 4; i++)
+ span[i] = (char)((t >> (24 - 8 * i)) & 0xFF);
+ });
+
+ /// <summary>The OpenType table checksum: the sum of big-endian uint32s, the last one zero-padded.</summary>
+ public static uint Checksum(ReadOnlySpan<byte> data)
+ {
+ uint sum = 0;
+ var whole = data.Length & ~3;
+ for (var i = 0; i < whole; i += 4)
+ sum += BinaryPrimitives.ReadUInt32BigEndian(data[i..]);
+ if (whole < data.Length)
+ {
+ Span<byte> last = stackalloc byte[4];
+ last.Clear();
+ data[whole..].CopyTo(last);
+ sum += BinaryPrimitives.ReadUInt32BigEndian(last);
+ }
+ return sum;
+ }
+
+ /// <summary>Checksum of a table as stored in the table directory (head counts with checkSumAdjustment = 0).</summary>
+ public static uint TableChecksum(string tag, byte[] data)
+ {
+ if (tag != "head" || data.Length < 12)
+ return Checksum(data);
+ var copy = (byte[])data.Clone();
+ copy.AsSpan(8, 4).Clear();
+ return Checksum(copy);
+ }
+
+ /// <summary>True when the data starts like a TrueType/OpenType font or collection.</summary>
+ public static bool IsSfnt(ReadOnlySpan<byte> data) =>
+ data.Length >= 12 && BinaryPrimitives.ReadUInt32BigEndian(data) is TrueTypeFlavor or CffFlavor or AppleTrueTypeFlavor or CollectionTag;
+
+ /// <summary>Reads a TTF/OTF, or the first font of a TTC collection.</summary>
+ public static SfntFont Read(byte[] data, int offset = 0)
+ {
+ var reader = new BigEndianReader(data, offset);
+ var flavor = reader.U32();
+ if (flavor == CollectionTag)
+ {
+ if (offset != 0)
+ throw new InvalidDataException("Nested font collection.");
+ reader.Skip(4); // version
+ if (reader.U32() == 0)
+ throw new InvalidDataException("The font collection is empty.");
+ return Read(data, checked((int)reader.U32()));
+ }
+ if (flavor is not (TrueTypeFlavor or CffFlavor or AppleTrueTypeFlavor))
+ throw new InvalidDataException("This is not a TrueType or OpenType font.");
+
+ var font = new SfntFont(flavor == AppleTrueTypeFlavor ? TrueTypeFlavor : flavor);
+ int count = reader.U16();
+ reader.Skip(6); // searchRange, entrySelector, rangeShift
+ for (var i = 0; i < count; i++)
+ {
+ var tag = TagName(reader.U32());
+ reader.Skip(4); // checksum
+ var tableOffset = reader.U32();
+ var length = reader.U32();
+ if (tableOffset > data.Length || length > data.Length - tableOffset)
+ throw new InvalidDataException($"The font's '{tag.Trim()}' table lies outside the file.");
+ font.Tables[tag] = data.AsSpan((int)tableOffset, (int)length).ToArray();
+ }
+ return font;
+ }
+
+ /// <summary>
+ /// Writes the font: directory sorted by tag, table data in the order the OpenType spec recommends, every table
+ /// 4-byte aligned, checksums and head.checkSumAdjustment computed.
+ /// </summary>
+ public byte[] Write()
+ {
+ var tags = Tables.Keys.Order(StringComparer.Ordinal).ToList();
+ var order = Flavor == CffFlavor ? CffOrder : TrueTypeOrder;
+ var dataOrder = tags
+ .OrderBy(t => t == "DSIG" ? int.MaxValue : Array.IndexOf(order, t) is var i and >= 0 ? i : order.Length)
+ .ThenBy(t => t, StringComparer.Ordinal)
+ .ToList();
+
+ var headerSize = 12 + 16 * tags.Count;
+ var offsets = new Dictionary<string, int>(StringComparer.Ordinal);
+ var position = headerSize;
+ foreach (var tag in dataOrder)
+ {
+ offsets[tag] = position;
+ position += (Tables[tag].Length + 3) & ~3;
+ }
+
+ var output = new byte[position];
+ var writer = new BigEndianWriter(headerSize);
+ WriteOffsetTable(writer, Flavor, tags.Count);
+ foreach (var tag in tags)
+ {
+ var data = Tables[tag];
+ writer.U32(TagValue(tag));
+ writer.U32(TableChecksum(tag, data));
+ writer.U32((uint)offsets[tag]);
+ writer.U32((uint)data.Length);
+ data.CopyTo(output, offsets[tag]);
+ }
+ writer.Written.CopyTo(output);
+
+ if (offsets.TryGetValue("head", out var head) && Tables["head"].Length >= 12)
+ {
+ output.AsSpan(head + 8, 4).Clear();
+ BinaryPrimitives.WriteUInt32BigEndian(output.AsSpan(head + 8), ChecksumMagic - Checksum(output));
+ }
+ return output;
+ }
+
+ /// <summary>Writes sfntVersion, numTables and the binary-search fields derived from it.</summary>
+ private static void WriteOffsetTable(BigEndianWriter writer, uint flavor, int tableCount)
+ {
+ var entrySelector = tableCount == 0 ? 0 : BitOperations.Log2((uint)tableCount);
+ var searchRange = (1 << entrySelector) * 16;
+ writer.U32(flavor);
+ writer.U16(tableCount);
+ writer.U16(searchRange);
+ writer.U16(entrySelector);
+ writer.U16(tableCount * 16 - searchRange);
+ }
+
+ /// <summary>A copy with its own table dictionary (table arrays are shared until replaced).</summary>
+ public SfntFont Clone()
+ {
+ var copy = new SfntFont(Flavor);
+ foreach (var (tag, data) in Tables)
+ copy.Tables[tag] = data;
+ return copy;
+ }
+}
diff --git a/src/Filee.Engines/Fonts/TrueTypeGlyph.cs b/src/Filee.Engines/Fonts/TrueTypeGlyph.cs
new file mode 100644
index 00000000..2a22b4c0
--- /dev/null
+++ b/src/Filee.Engines/Fonts/TrueTypeGlyph.cs
@@ -0,0 +1,359 @@
+// TrueType glyph outlines (the 'glyf' and 'loca' tables): parse a glyph into points / components and write it back in
+// the compact standard encoding. Used by the WOFF2 glyf transform and the CFF → TrueType conversion.
+
+using System.Buffers.Binary;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>One point of a TrueType contour in font units.</summary>
+internal readonly record struct GlyphPoint(int X, int Y, bool OnCurve);
+
+/// <summary>A TrueType glyph: a simple glyph (contours of points) or a composite glyph (raw component records).</summary>
+internal sealed class TrueTypeGlyph
+{
+ // Simple glyph point flags.
+ private const byte OnCurveFlag = 0x01;
+ private const byte XShortFlag = 0x02;
+ private const byte YShortFlag = 0x04;
+ private const byte RepeatFlag = 0x08;
+ private const byte XSameFlag = 0x10;
+ private const byte YSameFlag = 0x20;
+ private const byte OverlapSimpleFlag = 0x40;
+ private const byte CubicFlag = 0x80;
+
+ // Composite glyph component flags.
+ public const ushort ArgsAreWords = 0x0001;
+ public const ushort HasScale = 0x0008;
+ public const ushort MoreComponents = 0x0020;
+ public const ushort HasXYScale = 0x0040;
+ public const ushort HasTwoByTwo = 0x0080;
+ public const ushort HasInstructions = 0x0100;
+
+ /// <summary>Contour count; -1 for a composite glyph.</summary>
+ public short NumberOfContours { get; set; }
+
+ public short XMin { get; set; }
+ public short YMin { get; set; }
+ public short XMax { get; set; }
+ public short YMax { get; set; }
+
+ /// <summary>Index of the last point of each contour.</summary>
+ public ushort[] EndPoints { get; set; } = [];
+
+ /// <summary>Points in absolute font units.</summary>
+ public GlyphPoint[] Points { get; set; } = [];
+
+ /// <summary>TrueType hinting instructions.</summary>
+ public byte[] Instructions { get; set; } = [];
+
+ /// <summary>OVERLAP_SIMPLE on the first point: contours overlap (tells rasterizers to use non-zero fill carefully).</summary>
+ public bool OverlapSimple { get; set; }
+
+ /// <summary>Points use the cubic flag of the newer glyf spec, which WOFF2's transform can't carry.</summary>
+ public bool HasCubicPoints { get; private set; }
+
+ /// <summary>Component records of a composite glyph, as stored in the font (without instructions).</summary>
+ public byte[] Components { get; set; } = [];
+
+ public bool IsComposite => NumberOfContours < 0;
+
+ /// <summary>Parses the glyph at <paramref name="offset"/>; returns null for an empty glyph (no outline).</summary>
+ public static TrueTypeGlyph? Parse(byte[] glyf, int offset, int length)
+ {
+ if (length == 0)
+ return null;
+ var r = new BigEndianReader(glyf, offset, offset + length);
+ var glyph = new TrueTypeGlyph
+ {
+ NumberOfContours = r.I16(),
+ XMin = r.I16(),
+ YMin = r.I16(),
+ XMax = r.I16(),
+ YMax = r.I16(),
+ };
+ if (glyph.NumberOfContours >= 0)
+ glyph.ParseSimple(r);
+ else if (glyph.NumberOfContours == -1)
+ glyph.ParseComposite(r);
+ else
+ throw new InvalidDataException("Invalid TrueType glyph (negative contour count).");
+ return glyph;
+ }
+
+ private void ParseSimple(BigEndianReader r)
+ {
+ var contours = NumberOfContours;
+ EndPoints = new ushort[contours];
+ for (var i = 0; i < contours; i++)
+ {
+ EndPoints[i] = r.U16();
+ if (i > 0 && EndPoints[i] <= EndPoints[i - 1])
+ throw new InvalidDataException("Invalid TrueType glyph (contour end points out of order).");
+ }
+ Instructions = r.Bytes(r.U16());
+ var count = contours == 0 ? 0 : EndPoints[^1] + 1;
+
+ var flags = new byte[count];
+ for (var i = 0; i < count; i++)
+ {
+ var flag = r.U8();
+ flags[i] = flag;
+ if ((flag & RepeatFlag) == 0)
+ continue;
+ for (int repeat = r.U8(); repeat > 0; repeat--)
+ {
+ if (++i >= count)
+ throw new InvalidDataException("Invalid TrueType glyph (too many point flags).");
+ flags[i] = flag;
+ }
+ }
+
+ var xs = ReadCoordinates(r, flags, XShortFlag, XSameFlag);
+ var ys = ReadCoordinates(r, flags, YShortFlag, YSameFlag);
+ Points = new GlyphPoint[count];
+ for (var i = 0; i < count; i++)
+ {
+ Points[i] = new GlyphPoint(xs[i], ys[i], (flags[i] & OnCurveFlag) != 0);
+ HasCubicPoints |= (flags[i] & CubicFlag) != 0;
+ }
+ OverlapSimple = count > 0 && (flags[0] & OverlapSimpleFlag) != 0;
+ }
+
+ private static int[] ReadCoordinates(BigEndianReader r, byte[] flags, byte shortFlag, byte sameFlag)
+ {
+ var values = new int[flags.Length];
+ var value = 0;
+ for (var i = 0; i < flags.Length; i++)
+ {
+ var flag = flags[i];
+ if ((flag & shortFlag) != 0)
+ value += (flag & sameFlag) != 0 ? r.U8() : -r.U8();
+ else if ((flag & sameFlag) == 0)
+ value += r.I16();
+ values[i] = value;
+ }
+ return values;
+ }
+
+ private void ParseComposite(BigEndianReader r)
+ {
+ var start = r.Position;
+ var instructions = SkipComponents(r);
+ Components = r.Data.AsSpan(start, r.Position - start).ToArray();
+ if (instructions)
+ Instructions = r.Bytes(r.U16());
+ }
+
+ /// <summary>Moves past the component records; returns true if any component announces instructions.</summary>
+ public static bool SkipComponents(BigEndianReader r)
+ {
+ var instructions = false;
+ ushort flags;
+ do
+ {
+ flags = r.U16();
+ r.Skip(2); // glyph index
+ r.Skip((flags & ArgsAreWords) != 0 ? 4 : 2);
+ if ((flags & HasScale) != 0)
+ r.Skip(2);
+ else if ((flags & HasXYScale) != 0)
+ r.Skip(4);
+ else if ((flags & HasTwoByTwo) != 0)
+ r.Skip(8);
+ instructions |= (flags & HasInstructions) != 0;
+ }
+ while ((flags & MoreComponents) != 0);
+ return instructions;
+ }
+
+ /// <summary>Bounding box of the points (all zero without points).</summary>
+ public (short XMin, short YMin, short XMax, short YMax) ComputeBounds()
+ {
+ if (Points.Length == 0)
+ return (0, 0, 0, 0);
+ int xMin = int.MaxValue, yMin = int.MaxValue, xMax = int.MinValue, yMax = int.MinValue;
+ foreach (var p in Points)
+ {
+ xMin = Math.Min(xMin, p.X);
+ yMin = Math.Min(yMin, p.Y);
+ xMax = Math.Max(xMax, p.X);
+ yMax = Math.Max(yMax, p.Y);
+ }
+ return ((short)xMin, (short)yMin, (short)xMax, (short)yMax);
+ }
+
+ /// <summary>
+ /// Writes the glyph in the standard compact form: repeated flags, one-byte deltas where they fit, "same as
+ /// before" flags for zero deltas.
+ /// </summary>
+ public byte[] Serialize()
+ {
+ var w = new BigEndianWriter(16 + Points.Length * 5 + Components.Length + Instructions.Length);
+ w.I16(NumberOfContours);
+ w.I16(XMin);
+ w.I16(YMin);
+ w.I16(XMax);
+ w.I16(YMax);
+ if (IsComposite)
+ {
+ w.Bytes(Components);
+ if (ComponentsHaveInstructions())
+ {
+ w.U16(Instructions.Length);
+ w.Bytes(Instructions);
+ }
+ return w.ToArray();
+ }
+
+ foreach (var end in EndPoints)
+ w.U16(end);
+ w.U16(Instructions.Length);
+ w.Bytes(Instructions);
+
+ var flags = new BigEndianWriter(Points.Length);
+ var xs = new BigEndianWriter(Points.Length * 2);
+ var ys = new BigEndianWriter(Points.Length * 2);
+ int lastX = 0, lastY = 0, lastFlag = -1, repeat = 0;
+ for (var i = 0; i < Points.Length; i++)
+ {
+ var p = Points[i];
+ var flag = p.OnCurve ? OnCurveFlag : 0;
+ if (i == 0 && OverlapSimple)
+ flag |= OverlapSimpleFlag;
+ flag |= Delta(xs, p.X - lastX, XShortFlag, XSameFlag);
+ flag |= Delta(ys, p.Y - lastY, YShortFlag, YSameFlag);
+ lastX = p.X;
+ lastY = p.Y;
+
+ if (flag == lastFlag && repeat < 255)
+ {
+ // Mark the previous flag byte as repeated; its count is written when the run ends.
+ if (repeat == 0)
+ flags.Written[^1] |= RepeatFlag;
+ repeat++;
+ }
+ else
+ {
+ if (repeat > 0)
+ flags.U8(repeat);
+ flags.U8(flag);
+ repeat = 0;
+ }
+ lastFlag = flag;
+ }
+ if (repeat > 0)
+ flags.U8(repeat);
+
+ w.Bytes(flags.Written);
+ w.Bytes(xs.Written);
+ w.Bytes(ys.Written);
+ return w.ToArray();
+ }
+
+ private static int Delta(BigEndianWriter coordinates, int delta, byte shortFlag, byte sameFlag)
+ {
+ if (delta == 0)
+ return sameFlag;
+ if (delta is > -256 and < 256)
+ {
+ coordinates.U8(Math.Abs(delta));
+ return shortFlag | (delta > 0 ? sameFlag : 0);
+ }
+ coordinates.I16(delta);
+ return 0;
+ }
+
+ /// <summary>True when a component record sets WE_HAVE_INSTRUCTIONS.</summary>
+ public bool ComponentsHaveInstructions()
+ {
+ var r = new BigEndianReader(Components);
+ return Components.Length > 0 && SkipComponents(r);
+ }
+}
+
+/// <summary>Reads and builds the 'glyf' + 'loca' pair.</summary>
+internal static class GlyfTable
+{
+ /// <summary>Largest glyf size a short (offset / 2) loca can address.</summary>
+ public const int MaxShortLocaSize = 0xFFFF * 2;
+
+ /// <summary>Offset and length of every glyph in glyf according to loca.</summary>
+ public static (int Offset, int Length)[] ReadLoca(byte[] loca, int glyphCount, bool longFormat, int glyfLength)
+ {
+ var r = new BigEndianReader(loca);
+ var offsets = new long[glyphCount + 1];
+ for (var i = 0; i <= glyphCount; i++)
+ offsets[i] = longFormat ? r.U32() : r.U16() * 2L;
+
+ var result = new (int, int)[glyphCount];
+ for (var i = 0; i < glyphCount; i++)
+ {
+ var start = Math.Min(offsets[i], glyfLength);
+ var end = Math.Min(offsets[i + 1], glyfLength);
+ result[i] = ((int)start, (int)Math.Max(0, end - start));
+ }
+ return result;
+ }
+
+ /// <summary>Parses every glyph of a TrueType font (null entries are empty glyphs).</summary>
+ public static TrueTypeGlyph?[] ReadAll(SfntFont font)
+ {
+ var glyf = font.Require("glyf");
+ var longLoca = FontTables.IndexToLocFormat(font.Require("head")) != 0;
+ var loca = ReadLoca(font.Require("loca"), font.GlyphCount, longLoca, glyf.Length);
+ return [.. loca.Select(l => TrueTypeGlyph.Parse(glyf, l.Offset, l.Length))];
+ }
+
+ /// <summary>
+ /// Concatenates serialized glyphs, each padded to <paramref name="alignment"/> bytes, and builds loca. A short loca
+ /// is used when asked for and when every offset fits; the returned flag says which format was written.
+ /// </summary>
+ public static (byte[] Glyf, byte[] Loca, bool LongFormat) Build(IReadOnlyList<byte[]> glyphs, bool longFormat, int alignment = 4)
+ {
+ var total = glyphs.Sum(g => (long)Align(g.Length, alignment));
+ longFormat |= total > MaxShortLocaSize;
+ if (total > int.MaxValue)
+ throw new InvalidDataException("The glyph outlines are too large for a TrueType font.");
+
+ var glyf = new byte[total];
+ var loca = new BigEndianWriter((glyphs.Count + 1) * (longFormat ? 4 : 2));
+ var offset = 0;
+ foreach (var glyph in glyphs)
+ {
+ WriteLocaEntry(loca, offset, longFormat);
+ glyph.CopyTo(glyf, offset);
+ offset += Align(glyph.Length, alignment);
+ }
+ WriteLocaEntry(loca, offset, longFormat);
+ return (glyf, loca.ToArray(), longFormat);
+ }
+
+ private static int Align(int length, int alignment) => (length + alignment - 1) / alignment * alignment;
+
+ private static void WriteLocaEntry(BigEndianWriter loca, int offset, bool longFormat)
+ {
+ if (longFormat)
+ loca.U32((uint)offset);
+ else
+ loca.U16(offset / 2);
+ }
+}
+
+/// <summary>Field access for the small fixed-layout tables (head, hhea, maxp, OS/2, post).</summary>
+internal static class FontTables
+{
+ public static int UnitsPerEm(byte[] head) => BinaryPrimitives.ReadUInt16BigEndian(head.AsSpan(18));
+
+ public static int IndexToLocFormat(byte[] head) => BinaryPrimitives.ReadInt16BigEndian(head.AsSpan(50));
+
+ /// <summary>Returns a copy of head with indexToLocFormat set.</summary>
+ public static byte[] WithIndexToLocFormat(byte[] head, bool longFormat)
+ {
+ var copy = (byte[])head.Clone();
+ BinaryPrimitives.WriteInt16BigEndian(copy.AsSpan(50), (short)(longFormat ? 1 : 0));
+ return copy;
+ }
+
+ /// <summary>hhea.numberOfHMetrics (also vhea.numOfLongVerMetrics, same layout).</summary>
+ public static int NumberOfMetrics(byte[] hhea) => BinaryPrimitives.ReadUInt16BigEndian(hhea.AsSpan(34));
+}
diff --git a/src/Filee.Engines/Fonts/Woff.cs b/src/Filee.Engines/Fonts/Woff.cs
new file mode 100644
index 00000000..302080ab
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Woff.cs
@@ -0,0 +1,132 @@
+// WOFF 1.0 (W3C Recommendation, 2012): an SFNT whose tables are zlib-compressed one by one. Lossless both ways.
+
+using System.Buffers.Binary;
+using System.IO.Compression;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Encodes and decodes WOFF 1.0 files.</summary>
+internal static class Woff
+{
+ /// <summary>'wOFF'.</summary>
+ public const uint Signature = 0x774F4646;
+
+ private const int HeaderSize = 44;
+ private const int EntrySize = 20;
+
+ /// <summary>
+ /// Wraps the font: each table zlib-compressed, or stored as-is when compressing doesn't make it smaller (as the
+ /// spec requires). Extended metadata and private data are not written.
+ /// </summary>
+ public static byte[] Encode(SfntFont font, CancellationToken cancellationToken = default)
+ {
+ // Normalize through the SFNT writer so head.checkSumAdjustment matches the font a decoder rebuilds.
+ var sfnt = SfntFont.Read(font.Write());
+ var tags = sfnt.Tables.Keys.Order(StringComparer.Ordinal).ToList();
+
+ var compressed = new byte[tags.Count][];
+ long sfntSize = 12 + 16 * tags.Count;
+ for (var i = 0; i < tags.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var data = sfnt.Tables[tags[i]];
+ var packed = Compress(data);
+ compressed[i] = packed.Length < data.Length ? packed : data;
+ sfntSize += (data.Length + 3) & ~3;
+ }
+
+ var w = new BigEndianWriter(HeaderSize + EntrySize * tags.Count + compressed.Sum(c => c.Length + 3));
+ w.U32(Signature);
+ w.U32(sfnt.Flavor);
+ w.U32(0); // length, patched below
+ w.U16(tags.Count);
+ w.U16(0); // reserved
+ w.U32((uint)sfntSize);
+ var (major, minor) = FontVersion(sfnt);
+ w.U16(major);
+ w.U16(minor);
+ w.Zeros(20); // metaOffset, metaLength, metaOrigLength, privOffset, privLength
+
+ var offset = HeaderSize + EntrySize * tags.Count;
+ for (var i = 0; i < tags.Count; i++)
+ {
+ var data = sfnt.Tables[tags[i]];
+ w.U32(SfntFont.TagValue(tags[i]));
+ w.U32((uint)offset);
+ w.U32((uint)compressed[i].Length);
+ w.U32((uint)data.Length);
+ w.U32(SfntFont.TableChecksum(tags[i], data));
+ offset += (compressed[i].Length + 3) & ~3;
+ }
+ foreach (var data in compressed)
+ {
+ w.Bytes(data);
+ w.Pad4();
+ }
+ w.SetU32(8, (uint)w.Length);
+ return w.ToArray();
+ }
+
+ /// <summary>Unpacks a WOFF file into its font. Extended metadata and private data are dropped.</summary>
+ public static SfntFont Decode(byte[] data)
+ {
+ var r = new BigEndianReader(data);
+ if (r.U32() != Signature)
+ throw new InvalidDataException("This is not a WOFF file.");
+ var font = new SfntFont(r.U32());
+ if (font.Flavor is not (SfntFont.TrueTypeFlavor or SfntFont.CffFlavor or SfntFont.AppleTrueTypeFlavor))
+ throw new InvalidDataException("The WOFF file contains an unknown kind of font.");
+ if (font.Flavor == SfntFont.AppleTrueTypeFlavor)
+ font.Flavor = SfntFont.TrueTypeFlavor;
+ r.Skip(4); // length
+ int count = r.U16();
+ r.Position = HeaderSize;
+
+ for (var i = 0; i < count; i++)
+ {
+ var tag = SfntFont.TagName(r.U32());
+ var offset = r.U32();
+ var compLength = r.U32();
+ var origLength = r.U32();
+ r.Skip(4); // origChecksum
+ if (offset > data.Length || compLength > data.Length - offset || compLength > origLength)
+ throw new InvalidDataException($"The WOFF table '{tag.Trim()}' is damaged.");
+ var stored = data.AsSpan((int)offset, (int)compLength);
+ font.Tables[tag] = compLength == origLength ? stored.ToArray() : Decompress(stored, (int)origLength, tag);
+ }
+ return font;
+ }
+
+ private static byte[] Compress(byte[] data)
+ {
+ using var output = new MemoryStream(data.Length / 2 + 16);
+ using (var zlib = new ZLibStream(output, CompressionLevel.SmallestSize, leaveOpen: true))
+ zlib.Write(data);
+ return output.ToArray();
+ }
+
+ private static byte[] Decompress(ReadOnlySpan<byte> data, int length, string tag)
+ {
+ var result = new byte[length];
+ using var zlib = new ZLibStream(new MemoryStream(data.ToArray()), CompressionMode.Decompress);
+ try
+ {
+ zlib.ReadExactly(result);
+ }
+ catch (Exception e) when (e is EndOfStreamException or InvalidDataException)
+ {
+ throw new InvalidDataException($"The WOFF table '{tag.Trim()}' can't be decompressed.", e);
+ }
+ return result;
+ }
+
+ /// <summary>WOFF's informational version: head.fontRevision as major.minor (e.g. 2.015 → 2, 15).</summary>
+ internal static (int Major, int Minor) FontVersion(SfntFont font)
+ {
+ if (font["head"] is not { Length: >= 8 } head)
+ return (0, 0);
+ var revision = BinaryPrimitives.ReadInt32BigEndian(head.AsSpan(4)) / 65536.0;
+ var major = (int)Math.Floor(revision);
+ return (Math.Clamp(major, 0, 0xFFFF), Math.Clamp((int)Math.Round((revision - major) * 1000), 0, 0xFFFF));
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Woff2.cs b/src/Filee.Engines/Fonts/Woff2.cs
new file mode 100644
index 00000000..bb24e4af
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Woff2.cs
@@ -0,0 +1,259 @@
+// WOFF 2.0 (W3C Recommendation): all tables in one Brotli stream, glyf/loca and hmtx transformed for better
+// compression. Writes single fonts; reads single fonts and the first font of a WOFF2 collection.
+
+using System.Buffers;
+using System.Buffers.Binary;
+using System.IO.Compression;
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Encodes and decodes WOFF 2.0 files.</summary>
+internal static class Woff2
+{
+ /// <summary>'wOF2'.</summary>
+ public const uint Signature = 0x774F4632;
+
+ private const int HeaderSize = 48;
+ private const int BrotliQuality = 11;
+ private const int BrotliWindow = 22;
+ private const int ArbitraryTag = 63;
+
+ /// <summary>Tags with a 6-bit code in the table directory (section 4.1 of the spec); others are spelled out.</summary>
+ private static readonly string[] KnownTags =
+ [
+ "cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ",
+ "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS",
+ "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc",
+ "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop",
+ "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill",
+ ];
+
+ /// <summary>One table directory entry.</summary>
+ private sealed record Entry(string Tag, int Version, uint OrigLength, uint StoredLength, bool Transformed)
+ {
+ public int Offset { get; set; }
+ }
+
+ /// <summary>
+ /// Encodes the font. TrueType glyphs get the glyf/loca transform (and hmtx when possible), which is what makes
+ /// WOFF2 smaller than WOFF; like other encoders, the DSIG signature is dropped because the rebuilt tables no
+ /// longer match it, and head.flags bit 11 marks the font as losslessly transformed.
+ /// </summary>
+ public static byte[] Encode(SfntFont source, CancellationToken cancellationToken = default, IProgress<double>? progress = null)
+ {
+ var font = source.Clone();
+ font.Tables.Remove("DSIG");
+
+ TransformedGlyf? glyf = null;
+ byte[]? hmtx = null;
+ if (!font.HasCffOutlines && font["glyf"] is not null && font["loca"] is not null && font["head"] is not null)
+ glyf = Woff2Transforms.TryTransformGlyf(font, cancellationToken);
+ if (glyf is not null)
+ {
+ var head = FontTables.WithIndexToLocFormat(font.Require("head"), glyf.LongLoca);
+ BinaryPrimitives.WriteUInt16BigEndian(head.AsSpan(16), (ushort)(BinaryPrimitives.ReadUInt16BigEndian(head.AsSpan(16)) | 1 << 11));
+ font.Tables["head"] = head;
+ if (font["hmtx"] is { } metrics && font["hhea"] is { Length: >= 36 } hhea)
+ hmtx = Woff2Transforms.TryTransformHmtx(metrics, font.GlyphCount, FontTables.NumberOfMetrics(hhea), glyf.XMins);
+ }
+
+ var entries = new List<Entry>();
+ var stream = new BigEndianWriter();
+ long sfntSize = 12 + 16 * font.Tables.Count;
+ foreach (var tag in font.Tables.Keys.Order(StringComparer.Ordinal))
+ {
+ var data = font.Tables[tag];
+ Entry entry;
+ switch (tag)
+ {
+ case "glyf" when glyf is not null:
+ entry = new Entry(tag, 0, (uint)glyf.GlyfLength, (uint)glyf.Data.Length, true);
+ data = glyf.Data;
+ break;
+ case "loca" when glyf is not null:
+ entry = new Entry(tag, 0, (uint)glyf.LocaLength, 0, true);
+ data = [];
+ break;
+ case "glyf" or "loca":
+ entry = new Entry(tag, 3, (uint)data.Length, (uint)data.Length, false);
+ break;
+ case "hmtx" when hmtx is not null:
+ entry = new Entry(tag, 1, (uint)data.Length, (uint)hmtx.Length, true);
+ data = hmtx;
+ break;
+ default:
+ entry = new Entry(tag, 0, (uint)data.Length, (uint)data.Length, false);
+ break;
+ }
+ entries.Add(entry);
+ stream.Bytes(data);
+ sfntSize += (entry.OrigLength + 3) & ~3u;
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ var compressed = Compress(stream.Written, cancellationToken, progress);
+
+ var w = new BigEndianWriter(HeaderSize + entries.Count * 10 + compressed.Length + 4);
+ w.U32(Signature);
+ w.U32(font.Flavor);
+ w.U32(0); // length, patched below
+ w.U16(entries.Count);
+ w.U16(0); // reserved
+ w.U32((uint)Math.Min(sfntSize, uint.MaxValue));
+ w.U32((uint)compressed.Length);
+ var (major, minor) = Woff.FontVersion(font);
+ w.U16(major);
+ w.U16(minor);
+ w.Zeros(20); // no extended metadata, no private data
+ foreach (var entry in entries)
+ {
+ var index = Array.IndexOf(KnownTags, entry.Tag);
+ w.U8((index >= 0 ? index : ArbitraryTag) | entry.Version << 6);
+ if (index < 0)
+ w.U32(SfntFont.TagValue(entry.Tag));
+ w.UIntBase128(entry.OrigLength);
+ if (entry.Transformed)
+ w.UIntBase128(entry.StoredLength);
+ }
+ w.Bytes(compressed);
+ w.Pad4();
+ w.SetU32(8, (uint)w.Length);
+ return w.ToArray();
+ }
+
+ /// <summary>Decodes a WOFF2 file (the first font of a collection) into an SFNT font.</summary>
+ public static SfntFont Decode(byte[] data, CancellationToken cancellationToken = default)
+ {
+ var r = new BigEndianReader(data);
+ if (r.U32() != Signature)
+ throw new InvalidDataException("This is not a WOFF2 file.");
+ var flavor = r.U32();
+ r.Skip(4); // length
+ int tableCount = r.U16();
+ r.Skip(6); // reserved, totalSfntSize
+ var compressedLength = r.U32();
+ r.Position = HeaderSize;
+
+ var entries = new List<Entry>(tableCount);
+ long streamLength = 0;
+ for (var i = 0; i < tableCount; i++)
+ {
+ var flags = r.U8();
+ var tag = (flags & 0x3F) == ArbitraryTag ? SfntFont.TagName(r.U32()) : KnownTags[flags & 0x3F];
+ var version = flags >> 6;
+ var origLength = r.UIntBase128();
+ // glyf and loca use version 3 for "not transformed"; every other table uses version 0.
+ var transformed = tag is "glyf" or "loca" ? version != 3 : version != 0;
+ if (transformed && !(tag is "glyf" or "loca" && version == 0) && !(tag == "hmtx" && version == 1))
+ throw new InvalidDataException($"The WOFF2 table '{tag.Trim()}' uses an unknown transform.");
+ var storedLength = transformed ? r.UIntBase128() : origLength;
+ if (tag == "loca" && transformed && storedLength != 0)
+ throw new InvalidDataException("The WOFF2 'loca' table is damaged.");
+ entries.Add(new Entry(tag, version, origLength, storedLength, transformed) { Offset = (int)Math.Min(streamLength, int.MaxValue) });
+ streamLength += storedLength;
+ }
+ if (streamLength > int.MaxValue)
+ throw new InvalidDataException("The WOFF2 file is too large.");
+
+ // A collection lists which tables belong to each font; only the first font is converted.
+ var selected = entries;
+ if (flavor == SfntFont.CollectionTag)
+ {
+ r.U32(); // collection version
+ int fonts = r.Read255UInt16();
+ if (fonts == 0)
+ throw new InvalidDataException("The WOFF2 font collection is empty.");
+ for (var member = 0; member < fonts; member++)
+ {
+ int count = r.Read255UInt16();
+ var fontFlavor = r.U32();
+ var indices = Enumerable.Range(0, count).Select(_ => (int)r.Read255UInt16()).ToList();
+ if (indices.Any(i => i >= entries.Count))
+ throw new InvalidDataException("The WOFF2 font collection is damaged.");
+ if (member == 0)
+ {
+ flavor = fontFlavor;
+ selected = [.. indices.Select(i => entries[i])];
+ }
+ }
+ }
+ if (flavor is not (SfntFont.TrueTypeFlavor or SfntFont.CffFlavor or SfntFont.AppleTrueTypeFlavor))
+ throw new InvalidDataException("The WOFF2 file contains an unknown kind of font.");
+
+ if (compressedLength > data.Length - r.Position)
+ throw new InvalidDataException("The WOFF2 file is truncated.");
+ var stream = Decompress(data.AsSpan(r.Position, (int)compressedLength), (int)streamLength);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var font = new SfntFont(flavor == SfntFont.AppleTrueTypeFlavor ? SfntFont.TrueTypeFlavor : flavor);
+ foreach (var entry in selected.Where(e => !e.Transformed))
+ font.Tables[entry.Tag] = stream.AsSpan(entry.Offset, (int)entry.StoredLength).ToArray();
+
+ var glyfEntry = selected.FirstOrDefault(e => e.Tag == "glyf");
+ var locaEntry = selected.FirstOrDefault(e => e.Tag == "loca");
+ if ((glyfEntry is null) != (locaEntry is null) || glyfEntry?.Transformed != locaEntry?.Transformed)
+ throw new InvalidDataException("The WOFF2 'glyf' and 'loca' tables don't match.");
+
+ short[]? xMins = null;
+ if (glyfEntry is { Transformed: true })
+ {
+ var (glyf, loca, longLoca, mins) = Woff2Transforms.ReconstructGlyf(stream, glyfEntry.Offset, (int)glyfEntry.StoredLength, cancellationToken);
+ font.Tables["glyf"] = glyf;
+ font.Tables["loca"] = loca;
+ font.Tables["head"] = FontTables.WithIndexToLocFormat(font.Require("head"), longLoca);
+ xMins = mins;
+ }
+ if (selected.FirstOrDefault(e => e is { Tag: "hmtx", Transformed: true }) is { } hmtx)
+ {
+ if (xMins is null)
+ throw new InvalidDataException("The WOFF2 'hmtx' table is transformed without 'glyf'.");
+ font.Tables["hmtx"] = Woff2Transforms.ReconstructHmtx(stream, hmtx.Offset, (int)hmtx.StoredLength,
+ font.GlyphCount, FontTables.NumberOfMetrics(font.Require("hhea")), xMins);
+ }
+ return font;
+ }
+
+ /// <summary>
+ /// Brotli at the highest quality, like Google's encoder. That takes about 10 s per MB, so the data is fed in
+ /// chunks to report progress and honour cancellation (the result is the same as compressing in one call).
+ /// </summary>
+ private static byte[] Compress(ReadOnlySpan<byte> data, CancellationToken cancellationToken, IProgress<double>? progress)
+ {
+ const int Chunk = 256 * 1024;
+ using var encoder = new BrotliEncoder(BrotliQuality, BrotliWindow);
+ using var output = new MemoryStream(data.Length / 2 + 64);
+ var buffer = new byte[Chunk];
+ var remaining = data;
+ while (true)
+ {
+ var take = Math.Min(Chunk, remaining.Length);
+ var final = take == remaining.Length;
+ var input = remaining[..take];
+ OperationStatus status;
+ do
+ {
+ status = encoder.Compress(input, buffer, out var consumed, out var written, final);
+ if (status == OperationStatus.InvalidData)
+ throw new InvalidOperationException("Brotli compression failed.");
+ output.Write(buffer, 0, written);
+ input = input[consumed..];
+ }
+ while (status == OperationStatus.DestinationTooSmall || (final && status != OperationStatus.Done));
+ remaining = remaining[take..];
+ if (final)
+ return output.ToArray();
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(1 - (double)remaining.Length / data.Length);
+ }
+ }
+
+ private static byte[] Decompress(ReadOnlySpan<byte> data, int length)
+ {
+ var result = new byte[length];
+ using var decoder = new BrotliDecoder();
+ var status = decoder.Decompress(data, result, out _, out var written);
+ if (status != OperationStatus.Done || written != length)
+ throw new InvalidDataException("The WOFF2 font data can't be decompressed (the file is damaged).");
+ return result;
+ }
+}
diff --git a/src/Filee.Engines/Fonts/Woff2Transforms.cs b/src/Filee.Engines/Fonts/Woff2Transforms.cs
new file mode 100644
index 00000000..36da47f0
--- /dev/null
+++ b/src/Filee.Engines/Fonts/Woff2Transforms.cs
@@ -0,0 +1,418 @@
+// The WOFF2 table transforms (W3C WOFF 2.0, section 5): glyf/loca split into streams with a compact triplet encoding
+// for points (version 0), and hmtx without the left side bearings that equal the glyph's xMin (version 1).
+
+namespace Filee.Engines.Fonts;
+
+/// <summary>Result of transforming glyf/loca: the transformed data plus what the decoder will rebuild.</summary>
+/// <param name="Data">The transformed glyf table.</param>
+/// <param name="GlyfLength">Length of the glyf table a decoder reconstructs.</param>
+/// <param name="LocaLength">Length of the loca table a decoder reconstructs.</param>
+/// <param name="LongLoca">Loca format of the reconstructed font (head.indexToLocFormat must match).</param>
+/// <param name="XMins">xMin of every glyph (0 for empty glyphs), needed by the hmtx transform.</param>
+internal sealed record TransformedGlyf(byte[] Data, int GlyfLength, int LocaLength, bool LongLoca, short[] XMins);
+
+/// <summary>Forward and reverse WOFF2 transforms of glyf/loca and hmtx.</summary>
+internal static class Woff2Transforms
+{
+ private const int OverlapOption = 1;
+
+ /// <summary>
+ /// Transforms glyf/loca. Returns null when the glyphs can't be carried losslessly (damaged data, cubic glyf
+ /// extension); the caller then stores glyf and loca untransformed.
+ /// </summary>
+ public static TransformedGlyf? TryTransformGlyf(SfntFont font, CancellationToken cancellationToken)
+ {
+ TrueTypeGlyph?[] glyphs;
+ try
+ {
+ glyphs = GlyfTable.ReadAll(font);
+ }
+ catch (InvalidDataException)
+ {
+ return null;
+ }
+ if (glyphs.Any(g => g is { HasCubicPoints: true }))
+ return null;
+
+ var count = glyphs.Length;
+ var nContours = new BigEndianWriter(count * 2);
+ var nPoints = new BigEndianWriter(count * 4);
+ var flags = new BigEndianWriter(count * 32);
+ var glyphStream = new BigEndianWriter(count * 64);
+ var composites = new BigEndianWriter();
+ var bboxBitmap = new byte[4 * ((count + 31) / 32)];
+ var bboxes = new BigEndianWriter();
+ var instructions = new BigEndianWriter();
+ var overlap = new byte[(count + 7) / 8];
+ var hasOverlap = false;
+ var xMins = new short[count];
+ long glyfLength = 0;
+
+ for (var i = 0; i < count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var glyph = glyphs[i];
+ if (glyph is null || glyph.NumberOfContours == 0)
+ {
+ nContours.I16(0);
+ continue;
+ }
+ xMins[i] = glyph.XMin;
+ glyfLength += (glyph.Serialize().Length + 3) & ~3;
+
+ if (glyph.IsComposite)
+ {
+ nContours.I16(-1);
+ composites.Bytes(glyph.Components);
+ if (glyph.ComponentsHaveInstructions())
+ {
+ glyphStream.Write255UInt16(glyph.Instructions.Length);
+ instructions.Bytes(glyph.Instructions);
+ }
+ WriteBbox(glyph, i, bboxBitmap, bboxes); // composites always carry their box
+ continue;
+ }
+
+ nContours.I16(glyph.NumberOfContours);
+ var previous = -1;
+ foreach (var end in glyph.EndPoints)
+ {
+ nPoints.Write255UInt16(end - previous);
+ previous = end;
+ }
+ int lastX = 0, lastY = 0;
+ foreach (var p in glyph.Points)
+ {
+ WriteTriplet(flags, glyphStream, p.OnCurve, p.X - lastX, p.Y - lastY);
+ lastX = p.X;
+ lastY = p.Y;
+ }
+ glyphStream.Write255UInt16(glyph.Instructions.Length);
+ instructions.Bytes(glyph.Instructions);
+ if (glyph.ComputeBounds() != (glyph.XMin, glyph.YMin, glyph.XMax, glyph.YMax))
+ WriteBbox(glyph, i, bboxBitmap, bboxes);
+ if (glyph.OverlapSimple)
+ {
+ overlap[i >> 3] |= (byte)(0x80 >> (i & 7));
+ hasOverlap = true;
+ }
+ }
+
+ var longLoca = FontTables.IndexToLocFormat(font.Require("head")) != 0 || glyfLength > GlyfTable.MaxShortLocaSize;
+ var w = new BigEndianWriter();
+ w.U16(0); // reserved
+ w.U16(hasOverlap ? OverlapOption : 0);
+ w.U16(count);
+ w.U16(longLoca ? 1 : 0);
+ w.U32((uint)nContours.Length);
+ w.U32((uint)nPoints.Length);
+ w.U32((uint)flags.Length);
+ w.U32((uint)glyphStream.Length);
+ w.U32((uint)composites.Length);
+ w.U32((uint)(bboxBitmap.Length + bboxes.Length));
+ w.U32((uint)instructions.Length);
+ w.Bytes(nContours.Written);
+ w.Bytes(nPoints.Written);
+ w.Bytes(flags.Written);
+ w.Bytes(glyphStream.Written);
+ w.Bytes(composites.Written);
+ w.Bytes(bboxBitmap);
+ w.Bytes(bboxes.Written);
+ w.Bytes(instructions.Written);
+ if (hasOverlap)
+ w.Bytes(overlap);
+ return new TransformedGlyf(w.ToArray(), (int)glyfLength, (count + 1) * (longLoca ? 4 : 2), longLoca, xMins);
+ }
+
+ private static void WriteBbox(TrueTypeGlyph glyph, int index, byte[] bitmap, BigEndianWriter bboxes)
+ {
+ bitmap[index >> 3] |= (byte)(0x80 >> (index & 7));
+ bboxes.I16(glyph.XMin);
+ bboxes.I16(glyph.YMin);
+ bboxes.I16(glyph.XMax);
+ bboxes.I16(glyph.YMax);
+ }
+
+ /// <summary>
+ /// Encodes one point delta as a flag byte (on-curve bit + one of 128 shapes) and 1–4 data bytes, choosing the
+ /// smallest shape that fits (the table in section 5.2 of the spec).
+ /// </summary>
+ private static void WriteTriplet(BigEndianWriter flags, BigEndianWriter data, bool onCurve, int dx, int dy)
+ {
+ var absX = Math.Abs(dx);
+ var absY = Math.Abs(dy);
+ var onCurveBit = onCurve ? 0 : 128;
+ var xSign = dx < 0 ? 0 : 1;
+ var ySign = dy < 0 ? 0 : 1;
+ var signs = xSign + 2 * ySign;
+
+ if (dx == 0 && absY < 1280)
+ {
+ flags.U8(onCurveBit + ((absY & 0xF00) >> 7) + ySign);
+ data.U8(absY & 0xFF);
+ }
+ else if (dy == 0 && absX < 1280)
+ {
+ flags.U8(onCurveBit + 10 + ((absX & 0xF00) >> 7) + xSign);
+ data.U8(absX & 0xFF);
+ }
+ else if (absX < 65 && absY < 65)
+ {
+ flags.U8(onCurveBit + 20 + ((absX - 1) & 0x30) + (((absY - 1) & 0x30) >> 2) + signs);
+ data.U8((((absX - 1) & 0xF) << 4) | ((absY - 1) & 0xF));
+ }
+ else if (absX < 769 && absY < 769)
+ {
+ flags.U8(onCurveBit + 84 + 12 * (((absX - 1) & 0x300) >> 8) + (((absY - 1) & 0x300) >> 6) + signs);
+ data.U8((absX - 1) & 0xFF);
+ data.U8((absY - 1) & 0xFF);
+ }
+ else if (absX < 4096 && absY < 4096)
+ {
+ flags.U8(onCurveBit + 120 + signs);
+ data.U8(absX >> 4);
+ data.U8(((absX & 0xF) << 4) | (absY >> 8));
+ data.U8(absY & 0xFF);
+ }
+ else
+ {
+ flags.U8(onCurveBit + 124 + signs);
+ data.U16(absX);
+ data.U16(absY);
+ }
+ }
+
+ /// <summary>Rebuilds glyf and loca from a transformed glyf table (section 5.1 of the spec).</summary>
+ public static (byte[] Glyf, byte[] Loca, bool LongLoca, short[] XMins) ReconstructGlyf(
+ byte[] data, int offset, int length, CancellationToken cancellationToken)
+ {
+ var end = offset + length;
+ var header = new BigEndianReader(data, offset, end);
+ header.U16(); // reserved
+ var options = header.U16();
+ int count = header.U16();
+ var longLoca = header.U16() != 0;
+ var sizes = new uint[7];
+ for (var i = 0; i < sizes.Length; i++)
+ sizes[i] = header.U32();
+
+ var position = (long)header.Position;
+ BigEndianReader NextStream(long size)
+ {
+ if (size > end - position)
+ throw new InvalidDataException("The WOFF2 glyph data is damaged.");
+ var stream = new BigEndianReader(data, (int)position, (int)(position + size));
+ position += size;
+ return stream;
+ }
+
+ var nContours = NextStream(sizes[0]);
+ var nPoints = NextStream(sizes[1]);
+ var flagStream = NextStream(sizes[2]);
+ var glyphStream = NextStream(sizes[3]);
+ var composites = NextStream(sizes[4]);
+ var bboxStream = NextStream(sizes[5]);
+ var instructions = NextStream(sizes[6]);
+ var bboxBitmap = bboxStream.Span(4 * ((count + 31) / 32)).ToArray();
+ var overlap = (options & OverlapOption) != 0 ? NextStream((count + 7) / 8).Span((count + 7) / 8).ToArray() : null;
+
+ var glyphs = new byte[count][];
+ var xMins = new short[count];
+ for (var i = 0; i < count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ int contours = nContours.I16();
+ var hasBbox = (bboxBitmap[i >> 3] & (0x80 >> (i & 7))) != 0;
+ TrueTypeGlyph glyph;
+ if (contours == 0)
+ {
+ if (hasBbox)
+ throw new InvalidDataException("The WOFF2 glyph data is damaged (bounding box on an empty glyph).");
+ glyphs[i] = [];
+ continue;
+ }
+ if (contours == -1)
+ {
+ if (!hasBbox)
+ throw new InvalidDataException("The WOFF2 glyph data is damaged (composite glyph without bounding box).");
+ var start = composites.Position;
+ var hasInstructions = TrueTypeGlyph.SkipComponents(composites);
+ glyph = new TrueTypeGlyph
+ {
+ NumberOfContours = -1,
+ Components = data.AsSpan(start, composites.Position - start).ToArray(),
+ };
+ if (hasInstructions)
+ glyph.Instructions = instructions.Bytes(glyphStream.Read255UInt16());
+ }
+ else if (contours > 0)
+ {
+ glyph = new TrueTypeGlyph { NumberOfContours = (short)contours, EndPoints = new ushort[contours] };
+ var total = 0;
+ for (var c = 0; c < contours; c++)
+ {
+ total += nPoints.Read255UInt16();
+ if (total > 0xFFFF)
+ throw new InvalidDataException("The WOFF2 glyph data is damaged (too many points).");
+ glyph.EndPoints[c] = (ushort)(total - 1);
+ }
+ glyph.Points = ReadPoints(flagStream, glyphStream, total);
+ glyph.Instructions = instructions.Bytes(glyphStream.Read255UInt16());
+ glyph.OverlapSimple = overlap is not null && (overlap[i >> 3] & (0x80 >> (i & 7))) != 0;
+ }
+ else
+ {
+ throw new InvalidDataException("The WOFF2 glyph data is damaged (invalid contour count).");
+ }
+
+ if (hasBbox)
+ {
+ glyph.XMin = bboxStream.I16();
+ glyph.YMin = bboxStream.I16();
+ glyph.XMax = bboxStream.I16();
+ glyph.YMax = bboxStream.I16();
+ }
+ else
+ {
+ (glyph.XMin, glyph.YMin, glyph.XMax, glyph.YMax) = glyph.ComputeBounds();
+ }
+ xMins[i] = glyph.XMin;
+ glyphs[i] = glyph.Serialize();
+ }
+
+ var (glyf, loca, actualLong) = GlyfTable.Build(glyphs, longLoca);
+ return (glyf, loca, actualLong, xMins);
+ }
+
+ private static GlyphPoint[] ReadPoints(BigEndianReader flags, BigEndianReader data, int count)
+ {
+ var points = new GlyphPoint[count];
+ int x = 0, y = 0;
+ for (var i = 0; i < count; i++)
+ {
+ int flag = flags.U8();
+ var onCurve = (flag & 0x80) == 0;
+ flag &= 0x7F;
+ int dx, dy;
+ if (flag < 10)
+ {
+ dx = 0;
+ dy = WithSign(flag, ((flag & 14) << 7) + data.U8());
+ }
+ else if (flag < 20)
+ {
+ dx = WithSign(flag, (((flag - 10) & 14) << 7) + data.U8());
+ dy = 0;
+ }
+ else if (flag < 84)
+ {
+ var b0 = flag - 20;
+ int b1 = data.U8();
+ dx = WithSign(flag, 1 + (b0 & 0x30) + (b1 >> 4));
+ dy = WithSign(flag >> 1, 1 + ((b0 & 0x0C) << 2) + (b1 & 0x0F));
+ }
+ else if (flag < 120)
+ {
+ var b0 = flag - 84;
+ int b1 = data.U8();
+ int b2 = data.U8();
+ dx = WithSign(flag, 1 + ((b0 / 12) << 8) + b1);
+ dy = WithSign(flag >> 1, 1 + (((b0 % 12) >> 2) << 8) + b2);
+ }
+ else if (flag < 124)
+ {
+ int b1 = data.U8();
+ int b2 = data.U8();
+ int b3 = data.U8();
+ dx = WithSign(flag, (b1 << 4) + (b2 >> 4));
+ dy = WithSign(flag >> 1, ((b2 & 0x0F) << 8) + b3);
+ }
+ else
+ {
+ dx = WithSign(flag, data.U16());
+ dy = WithSign(flag >> 1, data.U16());
+ }
+ x += dx;
+ y += dy;
+ points[i] = new GlyphPoint(x, y, onCurve);
+ }
+ return points;
+ }
+
+ private static int WithSign(int flag, int value) => (flag & 1) != 0 ? value : -value;
+
+ /// <summary>
+ /// Transforms hmtx by dropping the left side bearings that equal the glyph's xMin. Returns null when neither
+ /// array can be dropped (the table is then stored as-is).
+ /// </summary>
+ public static byte[]? TryTransformHmtx(byte[] hmtx, int glyphCount, int metricsCount, short[] xMins)
+ {
+ if (metricsCount < 1 || metricsCount > glyphCount || hmtx.Length != 4 * metricsCount + 2 * (glyphCount - metricsCount))
+ return null;
+ var r = new BigEndianReader(hmtx);
+ var advances = new ushort[metricsCount];
+ var lsbs = new short[glyphCount];
+ for (var i = 0; i < metricsCount; i++)
+ {
+ advances[i] = r.U16();
+ lsbs[i] = r.I16();
+ }
+ for (var i = metricsCount; i < glyphCount; i++)
+ lsbs[i] = r.I16();
+
+ var proportional = Enumerable.Range(0, metricsCount).All(i => lsbs[i] == xMins[i]);
+ var monospaced = Enumerable.Range(metricsCount, glyphCount - metricsCount).All(i => lsbs[i] == xMins[i]);
+ if (!proportional && !monospaced)
+ return null;
+
+ var w = new BigEndianWriter(hmtx.Length);
+ w.U8((proportional ? 1 : 0) | (monospaced ? 2 : 0));
+ foreach (var advance in advances)
+ w.U16(advance);
+ if (!proportional)
+ {
+ for (var i = 0; i < metricsCount; i++)
+ w.I16(lsbs[i]);
+ }
+ if (!monospaced)
+ {
+ for (var i = metricsCount; i < glyphCount; i++)
+ w.I16(lsbs[i]);
+ }
+ return w.ToArray();
+ }
+
+ /// <summary>Rebuilds hmtx from its transformed form, filling missing side bearings with each glyph's xMin.</summary>
+ public static byte[] ReconstructHmtx(byte[] data, int offset, int length, int glyphCount, int metricsCount, short[] xMins)
+ {
+ if (metricsCount < 1 || metricsCount > glyphCount || xMins.Length < glyphCount)
+ throw new InvalidDataException("The WOFF2 metrics are damaged.");
+ var r = new BigEndianReader(data, offset, offset + length);
+ var flags = r.U8();
+ if ((flags & 0xFC) != 0)
+ throw new InvalidDataException("The WOFF2 metrics use unknown flags.");
+ var advances = new ushort[metricsCount];
+ for (var i = 0; i < metricsCount; i++)
+ advances[i] = r.U16();
+ var lsbs = xMins[..glyphCount];
+ if ((flags & 1) == 0)
+ {
+ for (var i = 0; i < metricsCount; i++)
+ lsbs[i] = r.I16();
+ }
+ if ((flags & 2) == 0)
+ {
+ for (var i = metricsCount; i < glyphCount; i++)
+ lsbs[i] = r.I16();
+ }
+
+ var w = new BigEndianWriter(4 * metricsCount + 2 * (glyphCount - metricsCount));
+ for (var i = 0; i < glyphCount; i++)
+ {
+ if (i < metricsCount)
+ w.U16(advances[i]);
+ w.I16(lsbs[i]);
+ }
+ return w.ToArray();
+ }
+}
diff --git a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
index 348333fd..9ee74988 100644
--- a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
+++ b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
@@ -18,4 +18,9 @@
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
+
+ <ItemGroup>
+ <!-- Small OFL test fonts for FontTests (see Fonts/OFL.txt and Fonts/make-test-fonts.py). -->
+ <None Update="Fonts\*.ttf;Fonts\*.otf;Fonts\*.woff2" CopyToOutputDirectory="PreserveNewest" />
+ </ItemGroup>
</Project>
diff --git a/tests/Filee.Engines.Tests/FontTests.cs b/tests/Filee.Engines.Tests/FontTests.cs
new file mode 100644
index 00000000..c55e8130
--- /dev/null
+++ b/tests/Filee.Engines.Tests/FontTests.cs
@@ -0,0 +1,539 @@
+// Font conversion (TTF, OTF, WOFF, WOFF2, EOT) with the built-in font engine. The test fonts in Fonts/ are small
+// subsets of Noto Sans and Noto Sans KR (SIL OFL 1.1, see Fonts/OFL.txt) made by Fonts/make-test-fonts.py:
+// hinted TrueType with composite glyphs, CID-keyed CFF with subroutines and VORG, and a name-keyed CFF font with a
+// seac accent, flex and subroutines; plus the TrueType one compressed by Google's reference WOFF2 encoder.
+
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Fonts;
+using SkiaSharp;
+
+namespace Filee.Engines.Tests;
+
+public class FontTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string TrueType = "FileeTest-TrueType.ttf";
+ private const string CidKeyed = "FileeTest-CID.otf";
+ private const string NameKeyed = "FileeTest-NameKeyed.otf";
+ private const string GoogleWoff2 = "FileeTest-TrueType.google.woff2";
+
+ private static readonly string[] Formats = ["ttf", "otf", "woff", "woff2", "eot"];
+
+ private static string Sample(string name) => Path.Combine(AppContext.BaseDirectory, "Fonts", name);
+
+ private static SfntFont Load(string path) => FontFile.Load(File.ReadAllBytes(path));
+
+ /// <summary>Converts a copy of a sample (so outputs land in a scratch folder) through the job queue.</summary>
+ private async Task<string> ConvertAsync(string input, string target)
+ {
+ var folder = fx.NewFolder();
+ var copy = Path.Combine(folder, Path.GetFileName(input));
+ File.Copy(input, copy);
+ var job = await fx.ConvertAsync([copy], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = job.Outputs.Single();
+ Assert.Equal("." + target, Path.GetExtension(output));
+ return output;
+ }
+
+ private async Task<string> RoundTripAsync(string sample, string via)
+ {
+ var middle = await ConvertAsync(Sample(sample), via);
+ return await ConvertAsync(middle, Path.GetExtension(sample)[1..]);
+ }
+
+ // ───────────────────────── Routes and every conversion ─────────────────────────
+
+ [Fact]
+ public void Every_font_format_converts_to_every_other_in_one_step()
+ {
+ var planner = fx.Catalog.CreatePlanner();
+ foreach (var from in Formats)
+ {
+ foreach (var to in Formats.Where(t => t != from))
+ {
+ var route = planner.Plan(from, to);
+ Assert.True(route is not null, $"{from} → {to}");
+ Assert.Equal("font", Assert.Single(route.Steps).Converter.Id);
+ }
+ }
+ }
+
+ public static TheoryData<string, string> AllConversions()
+ {
+ var data = new TheoryData<string, string>();
+ foreach (var sample in new[] { TrueType, CidKeyed, NameKeyed })
+ {
+ foreach (var target in Formats.Where(t => t != Path.GetExtension(sample)[1..]))
+ data.Add(sample, target);
+ }
+ return data;
+ }
+
+ [Theory]
+ [MemberData(nameof(AllConversions))]
+ public async Task Font_converts_and_the_result_loads_in_skia(string sample, string target)
+ {
+ var source = Load(Sample(sample));
+ var output = await ConvertAsync(Sample(sample), target);
+ var bytes = File.ReadAllBytes(output);
+
+ var result = FontFile.Load(bytes, TestContext.Current.CancellationToken);
+ Assert.Equal(source.GlyphCount, result.GlyphCount);
+ Assert.Equal(target is "ttf" or "eot" || !source.HasCffOutlines, !result.HasCffOutlines);
+
+ // Skia on Windows loads SFNT data only (DirectWrite); the web formats are checked after decoding.
+ using var typeface = SKTypeface.FromStream(new MemoryStream(target is "ttf" or "otf" ? bytes : result.Write()));
+ Assert.NotNull(typeface);
+ Assert.Equal(source.GlyphCount, typeface.GlyphCount);
+ using var font = new SKFont(typeface, 48);
+ var text = sample == NameKeyed ? "Aae" : "Filee";
+ Assert.All(font.GetGlyphs(text), g => Assert.NotEqual(0, g));
+ Assert.True(font.MeasureText(text) > 48);
+ using var path = font.GetGlyphPath(font.GetGlyphs(text)[0]);
+ Assert.False(path.IsEmpty);
+ }
+
+ // ───────────────────────── Lossless round trips ─────────────────────────
+
+ [Theory]
+ [InlineData(TrueType, "woff")]
+ [InlineData(TrueType, "eot")]
+ [InlineData(TrueType, "otf")]
+ [InlineData(CidKeyed, "woff")]
+ [InlineData(CidKeyed, "woff2")]
+ [InlineData(NameKeyed, "woff2")]
+ public async Task Round_trip_keeps_every_table(string sample, string via)
+ {
+ var back = Load(await RoundTripAsync(sample, via));
+
+ AssertSameTables(Load(Sample(sample)), back);
+ }
+
+ [Fact]
+ public async Task Ttf_to_woff2_and_back_keeps_glyph_outlines_and_tables()
+ {
+ var source = Load(Sample(TrueType));
+ var back = Load(await RoundTripAsync(TrueType, "woff2"));
+
+ // glyf and loca are rebuilt from the transformed streams, so they are compared glyph by glyph.
+ AssertSameTables(source, back, "glyf", "loca");
+ AssertSameGlyphs(source, back);
+ Assert.Equal(1 << 11, HeadFlags(back) & 1 << 11); // "lossless transform applied"
+ }
+
+ [Fact]
+ public async Task Woff2_uses_the_glyf_and_hmtx_transforms_and_beats_woff()
+ {
+ var woff2 = File.ReadAllBytes(await ConvertAsync(Sample(TrueType), "woff2"));
+ var woff = File.ReadAllBytes(await ConvertAsync(Sample(TrueType), "woff"));
+ var google = File.ReadAllBytes(Sample(GoogleWoff2));
+
+ var directory = Woff2Directory(woff2);
+ Assert.Equal((0, true), directory["glyf"]);
+ Assert.Equal((0, true), directory["loca"]);
+ Assert.Equal((1, true), directory["hmtx"]);
+ Assert.Equal((0, false), directory["cmap"]);
+ Assert.Equal(0, woff2.Length % 4);
+ Assert.Equal(woff2.Length, (int)BinaryPrimitives.ReadUInt32BigEndian(woff2.AsSpan(8)));
+ Assert.True(woff2.Length < woff.Length * 0.8, $"WOFF2 {woff2.Length} vs WOFF {woff.Length}");
+ Assert.True(woff2.Length < google.Length * 1.05, $"Filee {woff2.Length} vs Google {google.Length}");
+ }
+
+ [Fact]
+ public async Task Woff2_from_googles_reference_encoder_decodes_to_the_source()
+ {
+ var source = Load(Sample(TrueType));
+ var google = File.ReadAllBytes(Sample(GoogleWoff2));
+ Assert.Equal((0, true), Woff2Directory(google)["glyf"]);
+
+ // The encoder build used (wawoff2 2.0.1) doesn't write the overlap bitmap, a later addition to the spec, so
+ // OVERLAP_SIMPLE is lost in that file.
+ var decoded = FontFile.Load(google, TestContext.Current.CancellationToken);
+ AssertSameTables(source, decoded, "glyf", "loca");
+ AssertSameGlyphs(source, decoded, overlapBitmap: false);
+
+ // Through the engine as well.
+ var ttf = Load(await ConvertAsync(Sample(GoogleWoff2), "ttf"));
+ AssertSameGlyphs(source, ttf, overlapBitmap: false);
+ }
+
+ [Fact]
+ public void Woff2_collection_yields_its_first_font()
+ {
+ var source = Load(Sample(TrueType));
+ var decoded = FontFile.Load(Woff2Collection(source, Load(Sample(NameKeyed))), TestContext.Current.CancellationToken);
+
+ Assert.Equal(SfntFont.TrueTypeFlavor, decoded.Flavor);
+ AssertSameTables(source, decoded);
+ }
+
+ // ───────────────────────── CFF → TrueType ─────────────────────────
+
+ [Theory]
+ [InlineData(CidKeyed)]
+ [InlineData(NameKeyed)]
+ public async Task Cff_to_ttf_keeps_glyphs_metrics_and_outlines(string sample)
+ {
+ var source = Load(Sample(sample));
+ var output = await ConvertAsync(Sample(sample), "ttf");
+ var ttf = Load(output);
+
+ Assert.Equal(SfntFont.TrueTypeFlavor, ttf.Flavor);
+ Assert.Null(ttf["CFF "]);
+ Assert.Null(ttf["VORG"]);
+ Assert.Equal(source.GlyphCount, ttf.GlyphCount);
+ Assert.Equal(32, ttf.Require("maxp").Length); // maxp 1.0
+ foreach (var tag in new[] { "cmap", "name", "OS/2", "GSUB", "GPOS", "BASE" }.Where(t => source[t] is not null))
+ Assert.Equal(source[tag], ttf[tag]);
+
+ var glyphs = GlyfTable.ReadAll(ttf);
+ var (advances, lsbs) = Metrics(ttf, "hhea", "hmtx");
+ Assert.Equal(Metrics(source, "hhea", "hmtx").Advances, advances);
+ for (var i = 0; i < glyphs.Length; i++)
+ {
+ Assert.Equal(glyphs[i]?.XMin ?? 0, lsbs[i]);
+ if (glyphs[i] is not { } glyph)
+ continue;
+ Assert.Equal((glyph.XMin, glyph.YMin, glyph.XMax, glyph.YMax), glyph.ComputeBounds());
+ // TrueType fills clockwise outer contours: the largest contour must have a negative (clockwise) area.
+ var areas = Contours(glyph).Select(SignedArea).ToList();
+ Assert.True(areas.MaxBy(Math.Abs) < 0, $"glyph {i} is counter-clockwise");
+ }
+
+ // Compare the drawn outlines with the CFF originals (Skia reads both), 1 unit per 1000 plus rounding.
+ using var cffFace = SKTypeface.FromFile(Sample(sample));
+ using var ttfFace = SKTypeface.FromFile(output);
+ using var cffFont = new SKFont(cffFace, 1000) { Hinting = SKFontHinting.None };
+ using var ttfFont = new SKFont(ttfFace, 1000) { Hinting = SKFontHinting.None };
+ for (ushort gid = 0; gid < glyphs.Length; gid++)
+ {
+ using var expected = cffFont.GetGlyphPath(gid);
+ using var actual = ttfFont.GetGlyphPath(gid);
+ Assert.Equal(expected.IsEmpty, actual.IsEmpty);
+ if (expected.IsEmpty)
+ continue;
+ var e = expected.TightBounds;
+ var a = actual.TightBounds;
+ foreach (var (x, y) in new[] { (e.Left, a.Left), (e.Top, a.Top), (e.Right, a.Right), (e.Bottom, a.Bottom) })
+ Assert.True(Math.Abs(x - y) <= 1.6, $"glyph {gid}: bounds {e} vs {a}");
+ var (different, covered) = CompareCoverage(expected, actual);
+ Assert.True(different <= Math.Max(8, covered / 100), $"glyph {gid}: {different} of {covered} pixels differ");
+ }
+ }
+
+ [Fact]
+ public async Task Cff_glyph_names_become_post_format_2()
+ {
+ var ttf = Load(await ConvertAsync(Sample(NameKeyed), "ttf"));
+ Assert.Equal([".notdef", "space", "A", "a", "e", "acute", "Aacute", "flexbar", "box"], PostNames(ttf));
+
+ var cid = Load(await ConvertAsync(Sample(CidKeyed), "ttf"));
+ Assert.Equal(0x00030000u, BinaryPrimitives.ReadUInt32BigEndian(cid.Require("post")));
+ Assert.Equal(Load(Sample(CidKeyed)).Require("post").AsSpan(4, 28).ToArray(), cid.Require("post").AsSpan(4, 28).ToArray());
+ }
+
+ [Fact]
+ public async Task Seac_accent_flex_and_subroutines_are_drawn()
+ {
+ var glyphs = GlyfTable.ReadAll(Load(await ConvertAsync(Sample(NameKeyed), "ttf")));
+ var (a, acute, aacute, flexbar, box) = (glyphs[2]!, glyphs[5]!, glyphs[6]!, glyphs[7]!, glyphs[8]!);
+
+ // Aacute = endchar seac: the contours of A, then those of acute moved by (170, 190).
+ Assert.Equal(a.NumberOfContours + acute.NumberOfContours, aacute.NumberOfContours);
+ Assert.Equal(
+ [.. a.Points, .. acute.Points.Select(p => p with { X = p.X + 170, Y = p.Y + 190 })],
+ aacute.Points);
+
+ // flexbar: a rectangle whose top is a flex through (350, 530).
+ Assert.Equal((100, 0, 600, 530), ((int)flexbar.XMin, (int)flexbar.YMin, (int)flexbar.XMax, (int)flexbar.YMax));
+ Assert.Contains(new GlyphPoint(350, 530, true), flexbar.Points);
+
+ // box: outer square from a local subroutine, hole from a global one, in opposite directions.
+ Assert.Equal(2, box.NumberOfContours);
+ Assert.Equal((50, 0, 550, 500), ((int)box.XMin, (int)box.YMin, (int)box.XMax, (int)box.YMax));
+ var areas = Contours(box).Select(SignedArea).ToList();
+ Assert.Equal(-500 * 500, areas[0]);
+ Assert.Equal(300 * 300, areas[1]);
+ }
+
+ [Fact]
+ public async Task Cff_to_ttf_moves_vorg_origins_into_vmtx()
+ {
+ var source = Load(Sample(CidKeyed));
+ var ttf = Load(await ConvertAsync(Sample(CidKeyed), "ttf"));
+ var defaultOrigin = BinaryPrimitives.ReadInt16BigEndian(source.Require("VORG").AsSpan(4));
+
+ var glyphs = GlyfTable.ReadAll(ttf);
+ var (heights, tsbs) = Metrics(ttf, "vhea", "vmtx");
+ Assert.Equal(Metrics(source, "vhea", "vmtx").Advances, heights);
+ for (var i = 0; i < glyphs.Length; i++)
+ {
+ if (glyphs[i] is { } glyph)
+ Assert.Equal(defaultOrigin - glyph.YMax, tsbs[i]);
+ }
+ }
+
+ [Fact]
+ public async Task Cff_font_to_eot_carries_truetype_outlines_and_names()
+ {
+ var eot = File.ReadAllBytes(await ConvertAsync(Sample(NameKeyed), "eot"));
+
+ Assert.Equal(eot.Length, (int)BinaryPrimitives.ReadUInt32LittleEndian(eot));
+ Assert.Equal(0x00020001u, BinaryPrimitives.ReadUInt32LittleEndian(eot.AsSpan(8)));
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(eot.AsSpan(12))); // not compressed, not obfuscated
+ Assert.Equal(0x504C, BinaryPrimitives.ReadUInt16LittleEndian(eot.AsSpan(34)));
+ var familySize = BinaryPrimitives.ReadUInt16LittleEndian(eot.AsSpan(82));
+ Assert.Equal("Filee Test NameKeyed", System.Text.Encoding.Unicode.GetString(eot, 84, familySize));
+ var font = FontFile.Load(eot, TestContext.Current.CancellationToken);
+ Assert.NotNull(font["glyf"]);
+ Assert.Null(font["CFF "]);
+ }
+
+ // ───────────────────────── Errors ─────────────────────────
+
+ [Fact]
+ public async Task Compressed_eot_fails_with_a_clear_message()
+ {
+ var eot = File.ReadAllBytes(await ConvertAsync(Sample(TrueType), "eot"));
+ eot[12] |= 0x04; // TTEMBED_TTCOMPRESSED
+ var path = Path.Combine(fx.NewFolder(), "compressed.eot");
+ File.WriteAllBytes(path, eot);
+
+ var error = await FailingConversionAsync(path, "ttf");
+ Assert.Contains("MicroType Express", error);
+ }
+
+ [Fact]
+ public async Task Cff2_font_to_ttf_fails_with_a_clear_message()
+ {
+ var font = Load(Sample(CidKeyed));
+ font.Tables["CFF2"] = font.Tables["CFF "];
+ font.Tables.Remove("CFF ");
+ var path = Path.Combine(fx.NewFolder(), "variable.otf");
+ File.WriteAllBytes(path, font.Write());
+
+ var error = await FailingConversionAsync(path, "ttf");
+ Assert.Contains("CFF2", error);
+ }
+
+ [Fact]
+ public async Task Something_that_is_not_a_font_fails_with_a_clear_message()
+ {
+ var path = Path.Combine(fx.NewFolder(), "fake.woff2");
+ File.WriteAllText(path, "this is not a font");
+
+ var error = await FailingConversionAsync(path, "ttf");
+ Assert.Contains("not a font", error);
+ }
+
+ private async Task<string> FailingConversionAsync(string path, string target)
+ {
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = target });
+ var file = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, file.State);
+ return file.ErrorDetail ?? "";
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ /// <summary>
+ /// Same tables with the same bytes, except head.checkSumAdjustment and head.flags bit 11 (both depend on the
+ /// container) and the tables named in <paramref name="except"/>.
+ /// </summary>
+ private static void AssertSameTables(SfntFont expected, SfntFont actual, params string[] except)
+ {
+ Assert.Equal(expected.Flavor, actual.Flavor);
+ Assert.Equal(
+ expected.Tables.Keys.Where(t => !except.Contains(t) && t != "DSIG").Order(StringComparer.Ordinal),
+ actual.Tables.Keys.Where(t => !except.Contains(t)).Order(StringComparer.Ordinal));
+ foreach (var tag in expected.Tables.Keys.Where(t => !except.Contains(t) && t != "DSIG"))
+ {
+ var (e, a) = (expected.Tables[tag], actual.Tables[tag]);
+ if (tag == "head")
+ (e, a) = (NormalizeHead(e), NormalizeHead(a));
+ Assert.True(e.AsSpan().SequenceEqual(a), $"table '{tag}' differs");
+ }
+ }
+
+ private static byte[] NormalizeHead(byte[] head)
+ {
+ var copy = (byte[])head.Clone();
+ copy.AsSpan(8, 4).Clear();
+ copy[16] &= 0xF7; // flags bit 11
+ return copy;
+ }
+
+ private static int HeadFlags(SfntFont font) => BinaryPrimitives.ReadUInt16BigEndian(font.Require("head").AsSpan(16));
+
+ private static void AssertSameGlyphs(SfntFont expected, SfntFont actual, bool overlapBitmap = true)
+ {
+ var a = GlyfTable.ReadAll(expected);
+ var b = GlyfTable.ReadAll(actual);
+ Assert.Equal(a.Length, b.Length);
+ Assert.Contains(a, g => g is { IsComposite: true });
+ Assert.Contains(a, g => g is { OverlapSimple: true });
+ for (var i = 0; i < a.Length; i++)
+ {
+ if (a[i] is not { NumberOfContours: not 0 } e)
+ {
+ Assert.True(b[i] is null or { NumberOfContours: 0 }, $"glyph {i} should be empty");
+ continue;
+ }
+ var g = b[i];
+ Assert.NotNull(g);
+ Assert.Equal((e.NumberOfContours, e.XMin, e.YMin, e.XMax, e.YMax), (g.NumberOfContours, g.XMin, g.YMin, g.XMax, g.YMax));
+ Assert.Equal(e.EndPoints, g.EndPoints);
+ Assert.Equal(e.Points, g.Points);
+ Assert.Equal(e.Instructions, g.Instructions);
+ Assert.Equal(e.OverlapSimple && overlapBitmap, g.OverlapSimple);
+ Assert.Equal(e.Components, g.Components);
+ }
+ }
+
+ /// <summary>Transform version and "transformed" flag of every table in a WOFF2 directory.</summary>
+ private static Dictionary<string, (int Version, bool Transformed)> Woff2Directory(byte[] woff2)
+ {
+ string[] known = ["cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep"];
+ var r = new BigEndianReader(woff2, 12);
+ int count = r.U16();
+ r.Position = 48;
+ var result = new Dictionary<string, (int, bool)>();
+ for (var i = 0; i < count; i++)
+ {
+ var flags = r.U8();
+ var tag = (flags & 63) == 63 ? SfntFont.TagName(r.U32()) : (flags & 63) < known.Length ? known[flags & 63] : $"#{flags & 63}";
+ var version = flags >> 6;
+ r.UIntBase128();
+ var transformed = tag is "glyf" or "loca" ? version != 3 : version != 0;
+ if (transformed)
+ r.UIntBase128();
+ result[tag] = (version, transformed);
+ }
+ return result;
+ }
+
+ /// <summary>A WOFF2 collection of two fonts with untransformed tables (written by hand: Filee writes no collections).</summary>
+ private static byte[] Woff2Collection(SfntFont first, SfntFont second)
+ {
+ var tables = new List<(string Tag, byte[] Data)>();
+ var directories = new List<(uint Flavor, List<int> Indices)>();
+ foreach (var font in new[] { first, second })
+ {
+ var indices = new List<int>();
+ foreach (var tag in font.Tables.Keys.Order(StringComparer.Ordinal))
+ {
+ indices.Add(tables.Count);
+ tables.Add((tag, font.Tables[tag]));
+ }
+ directories.Add((font.Flavor, indices));
+ }
+
+ var stream = new BigEndianWriter();
+ foreach (var (_, data) in tables)
+ stream.Bytes(data);
+ var compressed = new byte[BrotliEncoder.GetMaxCompressedLength(stream.Length)];
+ Assert.True(BrotliEncoder.TryCompress(stream.Written, compressed, out var written, 5, 22));
+
+ var w = new BigEndianWriter();
+ w.U32(0x774F4632);
+ w.U32(SfntFont.CollectionTag);
+ w.U32(0); // length (not checked)
+ w.U16(tables.Count);
+ w.U16(0);
+ w.U32(0);
+ w.U32((uint)written);
+ w.Zeros(24);
+ foreach (var (tag, data) in tables)
+ {
+ w.U8(tag is "glyf" or "loca" ? 63 | 3 << 6 : 63); // arbitrary tag, null transform
+ w.U32(SfntFont.TagValue(tag));
+ w.UIntBase128((uint)data.Length);
+ }
+ w.U32(0x00010000);
+ w.Write255UInt16(directories.Count);
+ foreach (var (flavor, indices) in directories)
+ {
+ w.Write255UInt16(indices.Count);
+ w.U32(flavor);
+ foreach (var index in indices)
+ w.Write255UInt16(index);
+ }
+ w.Bytes(compressed.AsSpan(0, written));
+ return w.ToArray();
+ }
+
+ /// <summary>Advances (repeating the last long metric) and side bearings of hmtx or vmtx.</summary>
+ private static (int[] Advances, int[] Bearings) Metrics(SfntFont font, string header, string table)
+ {
+ var count = BinaryPrimitives.ReadUInt16BigEndian(font.Require(header).AsSpan(34));
+ var r = new BigEndianReader(font.Require(table));
+ var advances = new int[font.GlyphCount];
+ var bearings = new int[font.GlyphCount];
+ for (var i = 0; i < advances.Length; i++)
+ {
+ advances[i] = i < count ? r.U16() : advances[i - 1];
+ bearings[i] = r.I16();
+ }
+ return (advances, bearings);
+ }
+
+ private static List<string> PostNames(SfntFont font)
+ {
+ var r = new BigEndianReader(font.Require("post"));
+ Assert.Equal(0x00020000u, r.U32());
+ r.Position = 32;
+ var indices = Enumerable.Range(0, r.U16()).Select(_ => (int)r.U16()).ToList();
+ var extra = new List<string>();
+ while (r.Remaining > 0)
+ extra.Add(System.Text.Encoding.ASCII.GetString(r.Span(r.U8())));
+ return [.. indices.Select(i => i < 258 ? Fonts.Cff.CffStandardData.MacGlyphNames[i] : extra[i - 258])];
+ }
+
+ private static IEnumerable<GlyphPoint[]> Contours(TrueTypeGlyph glyph)
+ {
+ var start = 0;
+ foreach (var end in glyph.EndPoints)
+ {
+ yield return glyph.Points[start..(end + 1)];
+ start = end + 1;
+ }
+ }
+
+ /// <summary>Shoelace area of the control polygon: negative for clockwise contours (y up).</summary>
+ private static long SignedArea(GlyphPoint[] points)
+ {
+ long twice = 0;
+ for (var i = 0; i < points.Length; i++)
+ {
+ var (p, q) = (points[i], points[(i + 1) % points.Length]);
+ twice += (long)p.X * q.Y - (long)q.X * p.Y;
+ }
+ return twice / 2;
+ }
+
+ /// <summary>Renders two glyph paths at 0.25 px per unit and counts pixels whose coverage clearly differs.</summary>
+ private static (int Different, int Covered) CompareCoverage(SKPath expected, SKPath actual)
+ {
+ var bounds = SKRect.Union(expected.TightBounds, actual.TightBounds);
+ var width = (int)Math.Ceiling(bounds.Width / 4) + 4;
+ var height = (int)Math.Ceiling(bounds.Height / 4) + 4;
+ byte[] Render(SKPath path)
+ {
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Alpha8));
+ using var canvas = new SKCanvas(bitmap);
+ canvas.Clear(SKColors.Transparent);
+ canvas.Scale(0.25f);
+ canvas.Translate(-bounds.Left + 8, -bounds.Top + 8);
+ using var paint = new SKPaint { IsAntialias = true, Color = SKColors.Black };
+ canvas.DrawPath(path, paint);
+ return bitmap.Bytes;
+ }
+ var e = Render(expected);
+ var a = Render(actual);
+ var different = e.Zip(a).Count(p => Math.Abs(p.First - p.Second) > 128);
+ return (different, e.Count(v => v > 128));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/Fonts/FileeTest-CID.otf b/tests/Filee.Engines.Tests/Fonts/FileeTest-CID.otf
new file mode 100644
index 00000000..6a3989a7
Binary files /dev/null and b/tests/Filee.Engines.Tests/Fonts/FileeTest-CID.otf differ
diff --git a/tests/Filee.Engines.Tests/Fonts/FileeTest-NameKeyed.otf b/tests/Filee.Engines.Tests/Fonts/FileeTest-NameKeyed.otf
new file mode 100644
index 00000000..4dd98260
Binary files /dev/null and b/tests/Filee.Engines.Tests/Fonts/FileeTest-NameKeyed.otf differ
diff --git a/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.google.woff2 b/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.google.woff2
new file mode 100644
index 00000000..aef24a07
Binary files /dev/null and b/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.google.woff2 differ
diff --git a/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.ttf b/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.ttf
new file mode 100644
index 00000000..144e304a
Binary files /dev/null and b/tests/Filee.Engines.Tests/Fonts/FileeTest-TrueType.ttf differ
diff --git a/tests/Filee.Engines.Tests/Fonts/OFL.txt b/tests/Filee.Engines.Tests/Fonts/OFL.txt
new file mode 100644
index 00000000..89858fa4
--- /dev/null
+++ b/tests/Filee.Engines.Tests/Fonts/OFL.txt
@@ -0,0 +1,103 @@
+Test fonts for tests/Filee.Engines.Tests/FontTests.cs, made by make-test-fonts.py from the Noto fonts downloaded
+by build/fetch-fonts.ps1 and renamed "Filee Test ..." so these modified versions don't carry the original names:
+
+- FileeTest-TrueType.ttf: a subset of Noto Sans Regular 2.015 (hinted TrueType).
+ Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
+- FileeTest-TrueType.google.woff2: FileeTest-TrueType.ttf compressed with Google's reference WOFF2 encoder
+ (https://github.com/google/woff2, through the npm package wawoff2 2.0.1).
+- FileeTest-CID.otf: a subset of Noto Sans KR Regular 2.004 (CID-keyed CFF).
+- FileeTest-NameKeyed.otf: a few glyphs of Noto Sans KR Regular 2.004 rebuilt as a name-keyed CFF font, plus three
+ small glyphs drawn for the tests.
+ Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/tests/Filee.Engines.Tests/Fonts/make-test-fonts.py b/tests/Filee.Engines.Tests/Fonts/make-test-fonts.py
new file mode 100644
index 00000000..0686884a
--- /dev/null
+++ b/tests/Filee.Engines.Tests/Fonts/make-test-fonts.py
@@ -0,0 +1,155 @@
+# Rebuilds the small test fonts in this folder from the Noto fonts that build/fetch-fonts.ps1 downloads (SIL OFL 1.1).
+# Only needed when the test fonts change: the tests use the committed files and never run this script.
+#
+# pip install fonttools==4.66.1
+# npm install [email protected] (optional)
+# python make-test-fonts.py <folder with NotoSans-Regular.ttf and NotoSansKR-Regular.otf> [woff2_compress.js]
+#
+# The optional second argument is node_modules/wawoff2/bin/woff2_compress.js (Google's reference WOFF2 encoder,
+# github.com/google/woff2, compiled to WebAssembly); with it the script also writes FileeTest-TrueType.google.woff2.
+
+import os
+import subprocess
+import sys
+
+from fontTools import subset
+from fontTools.cffLib import SubrsIndex
+from fontTools.fontBuilder import FontBuilder
+from fontTools.misc.psCharStrings import T2CharString
+from fontTools.pens.boundsPen import BoundsPen
+from fontTools.pens.t2CharStringPen import T2CharStringPen
+from fontTools.ttLib import TTFont
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+
+def rename(font, family, ps_name):
+ """Gives the subset its own name, so a modified font doesn't pass for the original (see OFL.txt)."""
+ name = font["name"]
+ name.names = [n for n in name.names if n.nameID in (0, 13, 14)]
+ for name_id, value in {1: family, 2: "Regular", 3: ps_name + ";Filee test font", 4: family + " Regular",
+ 5: "Version 1.000", 6: ps_name}.items():
+ name.setName(value, name_id, 3, 1, 0x409)
+ name.setName(value, name_id, 1, 0, 0)
+ if "CFF " in font:
+ cff = font["CFF "].cff
+ old = cff.fontNames[0]
+ cff.fontNames = [ps_name]
+ top = cff.topDictIndex[0]
+ top.FullName = family + " Regular"
+ top.FamilyName = family
+ for fd in getattr(top, "FDArray", []):
+ fd.FontName = fd.FontName.replace(old, ps_name)
+
+
+def subset_font(source, text, **options):
+ opts = subset.Options() # default layout features: kern, liga, mark, vert, ...
+ opts.name_IDs = ["*"]
+ opts.name_languages = ["*"]
+ opts.notdef_outline = True
+ opts.glyph_names = True
+ opts.drop_tables += ["DSIG"]
+ for key, value in options.items():
+ setattr(opts, key, value)
+ font = TTFont(source)
+ subsetter = subset.Subsetter(opts)
+ subsetter.populate(text=text)
+ subsetter.subset(font)
+ return font
+
+
+def truetype(fonts):
+ """Hinted TrueType glyphs with composites (accented letters), kerning, and overlap flags set on purpose."""
+ font = subset_font(os.path.join(fonts, "NotoSans-Regular.ttf"),
+ "Filee Hamburgefonstiv ÁáéÅçÑü 0123 .,!-")
+ glyf = font["glyf"]
+ glyf["A"].flags[0] |= 0x40 # OVERLAP_SIMPLE
+ glyf["Aacute"].components[0].flags |= 0x400 # OVERLAP_COMPOUND
+ rename(font, "Filee Test TrueType", "FileeTest-TrueType")
+ path = os.path.join(HERE, "FileeTest-TrueType.ttf")
+ font.save(path)
+ return path
+
+
+def cid_keyed(fonts):
+ """CID-keyed CFF with local and global subroutines, hints, hint masks, VORG and vertical metrics."""
+ font = subset_font(os.path.join(fonts, "NotoSansKR-Regular.otf"), "Filee 한글 변환 Hamburg 0123 ,.")
+ rename(font, "Filee Test CID", "FileeTest-CID")
+ path = os.path.join(HERE, "FileeTest-CID.otf")
+ font.save(path)
+
+
+def name_keyed(fonts):
+ """Name-keyed CFF: glyph names, an `endchar` accent (seac), flex, and local and global subroutines."""
+ source = subset_font(os.path.join(fonts, "NotoSansKR-Regular.otf"), " Aae´", desubroutinize=True)
+ cmap = source.getBestCmap()
+ glyph_set = source.getGlyphSet()
+ names = {"space": 0x20, "A": ord("A"), "a": ord("a"), "e": ord("e"), "acute": 0xB4}
+
+ order = [".notdef", "space", "A", "a", "e", "acute", "Aacute", "flexbar", "box"]
+ char_strings, metrics = {}, {}
+
+ def add(name, source_name):
+ width = source["hmtx"][source_name][0]
+ pen = T2CharStringPen(width, glyph_set)
+ glyph_set[source_name].draw(pen)
+ char_strings[name] = pen.getCharString()
+ bounds = BoundsPen(glyph_set)
+ glyph_set[source_name].draw(bounds)
+ metrics[name] = (width, bounds.bounds[0] if bounds.bounds else 0)
+
+ add(".notdef", ".notdef")
+ for name, code in names.items():
+ add(name, cmap[code])
+
+ # Aacute = A + acute moved up: StandardEncoding codes 65 (A) and 194 (acute).
+ a_width = metrics["A"][0]
+ char_strings["Aacute"] = T2CharString(program=[a_width, 170, 190, 65, 194, "endchar"])
+ metrics["Aacute"] = (a_width, metrics["A"][1])
+ # A bar whose top edge is a flex (12 35), drawn counter-clockwise like every CFF outer contour.
+ char_strings["flexbar"] = T2CharString(program=[
+ 700, 100, 0, "rmoveto", 500, 0, "rlineto", 0, 500, "rlineto",
+ -100, 20, -50, 10, -100, 0, -100, 0, -50, -10, -100, -20, 50, "flex", "endchar"])
+ metrics["flexbar"] = (700, 100)
+ # A square with a hole: the outer contour comes from a local subroutine, the inner one from a global one.
+ char_strings["box"] = T2CharString(program=[600, -107, "callsubr", -107, "callgsubr", "endchar"])
+ metrics["box"] = (600, 50)
+
+ builder = FontBuilder(1000, isTTF=False)
+ builder.setupGlyphOrder(order)
+ builder.setupCharacterMap({**{code: name for name, code in names.items()}, 0xC1: "Aacute",
+ 0xE000: "flexbar", 0xE001: "box"})
+ builder.setupCFF("FileeTest-NameKeyed", {"FullName": "Filee Test NameKeyed Regular"}, char_strings, {})
+ cff = builder.font["CFF "].cff
+ top = cff.topDictIndex[0]
+ subrs = SubrsIndex()
+ subrs.append(T2CharString(program=[50, 0, "rmoveto", 500, "hlineto", 500, "vlineto", -500, "hlineto", "return"]))
+ top.Private.Subrs = subrs
+ cff.GlobalSubrs.append(T2CharString(program=[100, -400, "rmoveto", 0, 300, "rlineto", 300, 0, "rlineto",
+ 0, -300, "rlineto", "return"]))
+ for cs in char_strings.values():
+ cs.private = top.Private
+ cs.globalSubrs = cff.GlobalSubrs
+ builder.setupHorizontalMetrics(metrics)
+ builder.setupHorizontalHeader(ascent=880, descent=-120)
+ builder.setupNameTable({"familyName": "Filee Test NameKeyed", "styleName": "Regular",
+ "copyright": source["name"].getDebugName(0),
+ "licenseDescription": "This Font Software is licensed under the SIL Open Font License, Version 1.1.",
+ "licenseInfoURL": "https://openfontlicense.org"})
+ builder.setupOS2(sTypoAscender=880, sTypoDescender=-120, usWinAscent=1160, usWinDescent=288,
+ achVendID="FILE", usWeightClass=400)
+ builder.setupPost(keepGlyphNames=False)
+ builder.save(os.path.join(HERE, "FileeTest-NameKeyed.otf"))
+
+
+def main():
+ fonts = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "..", "..", "..", "src", "Filee.App", "Assets", "Fonts")
+ ttf = truetype(fonts)
+ cid_keyed(fonts)
+ name_keyed(fonts)
+ if len(sys.argv) > 2:
+ subprocess.run(["node", sys.argv[2], ttf, os.path.join(HERE, "FileeTest-TrueType.google.woff2")], check=True)
+
+
+if __name__ == "__main__":
+ main()