Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

### Unreleased

- Reconstruct transformed WOFF2 TrueType glyphs when subsetting, preserving point indices, glyph instructions and component records
- Use decoded variation coordinates and phantom-derived horizontal bearings for transformed WOFF2 subsets
- Reject WOFF2 subsetting with transformed hmtx instead of emitting incorrect horizontal metrics
- Reject truncated WOFF2 glyph instruction data while decoding transformed glyphs
- End the second curve of CFF hflex and hflex1 operators at the starting y, so later points are no longer shifted (#437)

### [3.0.0] - 11-11-2026
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,12 @@ Includes the given glyph object or glyph ID in the subset.

Returns a `Uint8Array` containing the encoded font file.

Transformed WOFF2 TrueType glyphs are reconstructed when subsetting. Subsetting
these fonts with WOFF2-transformed `hmtx` tables throws an unsupported-format
error. Non-default variation subsets can differ from a reference instancer in
coordinates, bounding boxes, advance/bearing metrics and component offsets;
`cvar` adjustments are not instantiated.

## License

MIT
33 changes: 28 additions & 5 deletions src/WOFF2Font.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ export class WOFF2Font extends TTFFont {
this.stream.pos = this.directory.tables.glyf.offset;
let table = GlyfTable.decode(this.stream);
let glyphs = [];
let overlapBitmap =
table.optionFlags & 1
? this.stream.readBuffer((table.numGlyphs + 7) >> 3)
: null;

// The bounding boxes stream starts with a bit for each glyph, set for
// the ones whose box is stored. The rest are computed from the points.
Expand All @@ -120,6 +124,7 @@ export class WOFF2Font extends TTFFont {
let glyph = { xMin: 0, yMin: 0, xMax: 0, yMax: 0 };
let nContours = table.nContours.readInt16BE();
glyph.numberOfContours = nContours;
let instructionSize = 0;

if (nContours > 0) {
// simple glyph
Expand All @@ -133,25 +138,42 @@ export class WOFF2Font extends TTFFont {
}

glyph.points = decodeTriplet(table.flags, table.glyphs, totalPoints);
glyph.endPtsOfContours = nPoints.map((count) => count - 1);
glyph.overlapSimple = !!(
overlapBitmap && overlapBitmap[index >> 3] & (0x80 >> (index & 7))
);
for (let i = 0; i < nContours; i++) {
glyph.points[nPoints[i] - 1].endContour = true;
}

var instructionSize = read255UInt16(table.glyphs);
instructionSize = read255UInt16(table.glyphs);
} else if (nContours < 0) {
// composite glyph
// Decoded as the file has it, whatever this font's coordinates:
// the glyphs are shared with its variations.
let haveInstructions = TTFGlyph.prototype._decodeComposite.call(
glyph.compositeOffset = table.composites.pos;
glyph.haveInstructions = TTFGlyph.prototype._decodeComposite.call(
{ _font: {} },
glyph,
table.composites,
);
if (haveInstructions) {
var instructionSize = read255UInt16(table.glyphs);
glyph.compositeData = table.composites.buffer.subarray(
glyph.compositeOffset,
table.composites.pos,
);
if (glyph.haveInstructions) {
instructionSize = read255UInt16(table.glyphs);
}
}

if (
table.instructions.pos + instructionSize >
table.instructions.buffer.length
) {
throw new Error('Invalid WOFF2 glyph instruction length');
}
glyph.instructions = table.instructions.readBuffer(instructionSize);

if (bboxBitmap[index >> 3] & (0x80 >> (index & 7))) {
glyph.xMin = table.bboxes.readInt16BE();
glyph.yMin = table.bboxes.readInt16BE();
Expand Down Expand Up @@ -182,7 +204,8 @@ class Substream {

// This struct represents the entire glyf table
let GlyfTable = new r.Struct({
version: r.uint32,
reserved: r.uint16,
optionFlags: r.uint16,
numGlyphs: r.uint16,
indexFormat: r.uint16,
nContourStreamSize: r.uint32,
Expand Down
104 changes: 104 additions & 0 deletions src/glyph/TTFGlyphEncoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,110 @@ let Glyf = new r.Struct({
* Encodes TrueType glyph outlines
*/
export default class TTFGlyphEncoder {
// Reconstruct a WOFF2 glyph without changing point indices used by hints.
encodeGlyph(glyph, includeGlyph) {
if (glyph.numberOfContours === 0) return new Uint8Array(0);

if (glyph.numberOfContours < 0) {
let records = glyph.components.map((component, index) => {
let start = component.pos - 2 - glyph.compositeOffset;
let end =
index + 1 < glyph.components.length
? glyph.components[index + 1].pos - 2 - glyph.compositeOffset
: glyph.compositeData.length;
let record = glyph.compositeData.subarray(start, end);
let flags = (record[0] << 8) | record[1];
let oldArgs = flags & 1 ? 4 : 2;
if (
flags & 2 &&
(component.dx < -128 ||
component.dx > 127 ||
component.dy < -128 ||
component.dy > 127)
) {
flags |= 1;
}
let args = flags & 1 ? 4 : 2;
let stream = new r.EncodeStream(
new Uint8Array(record.length + args - oldArgs),
);
stream.writeUInt16BE(flags);
stream.writeUInt16BE(includeGlyph(component.glyphID));
if (flags & 2) {
if (flags & 1) {
stream.writeInt16BE(component.dx);
stream.writeInt16BE(component.dy);
} else {
stream.writeInt8(component.dx);
stream.writeInt8(component.dy);
}
} else {
stream.writeBuffer(record.subarray(4, 4 + oldArgs));
}
stream.writeBuffer(record.subarray(4 + oldArgs));
return stream.buffer;
});
let size = 10 + records.reduce((sum, record) => sum + record.length, 0);
if (glyph.haveInstructions) size += 2 + glyph.instructions.length;
let stream = new r.EncodeStream(new Uint8Array((size + 3) & ~3));
for (let field of ['numberOfContours', 'xMin', 'yMin', 'xMax', 'yMax']) {
stream.writeInt16BE(glyph[field]);
}
for (let record of records) stream.writeBuffer(record);
if (glyph.haveInstructions) {
stream.writeUInt16BE(glyph.instructions.length);
stream.writeBuffer(glyph.instructions);
}
return stream.buffer;
}

let flags = [],
xPoints = [],
yPoints = [];
let lastX = 0,
lastY = 0;
for (let point of glyph.points) {
let flag = point.onCurve ? ON_CURVE : 0;
flag = this._encodePoint(
point.x,
lastX,
xPoints,
flag,
X_SHORT_VECTOR,
SAME_X,
);
flag = this._encodePoint(
point.y,
lastY,
yPoints,
flag,
Y_SHORT_VECTOR,
SAME_Y,
);
flags.push(flag);
lastX = point.x;
lastY = point.y;
}
if (glyph.overlapSimple) flags[0] |= 0x40;
let runs = [];
for (let i = 0; i < flags.length;) {
let repeats = 0;
while (repeats < 255 && flags[i + repeats + 1] === flags[i]) repeats++;
runs.push(flags[i] | (repeats ? REPEAT : 0));
if (repeats) runs.push(repeats);
i += repeats + 1;
}
let data = Glyf.toBuffer({
...glyph,
flags: runs,
xPoints,
yPoints,
});
let buffer = new Uint8Array((data.length + 3) & ~3);
buffer.set(data);
return buffer;
}

encodeSimple(path, instructions = []) {
let endPtsOfContours = [];
let xPoints = [];
Expand Down
113 changes: 87 additions & 26 deletions src/subset/TTFSubset.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,89 @@ export default class TTFSubset extends Subset {
_addGlyph(gid) {
let glyph = this.font.getGlyph(gid);
let glyf = glyph._decode();

// get the offset to the glyph from the loca table
let curOffset = this.font.loca.offsets[gid];
let nextOffset = this.font.loca.offsets[gid + 1];

let stream = this.font._getTableStream('glyf');
stream.pos += curOffset;

let buffer = stream.readBuffer(nextOffset - curOffset);

let bearing = glyph._getMetrics().leftBearing;
if (glyf && this.font._variationProcessor) {
// If this is a TrueType variation glyph, re-encode the path and take the
// left side bearing from it. Compound glyphs are flattened too, as the
// offsets of their components vary.
buffer = this.glyphEncoder.encodeSimple(glyph.path, glyf.instructions);
bearing = glyph.path.cbox.minX;
} else if (glyf && glyf.numberOfContours < 0) {
// if it is a compound glyph, include its components
buffer = new Uint8Array(buffer);
let view = new DataView(buffer.buffer);
for (let component of glyf.components) {
gid = this.includeGlyph(component.glyphID);
view.setUint16(component.pos, gid);
let transformed = this.font.directory.tables.glyf.transformed;
let buffer;
let bearing;

if (transformed) {
if (glyf.numberOfContours && this.font._variationProcessor) {
// Resolving the path also updates varied phantom-point metrics.
let box = glyph.path.cbox;
if (glyf.numberOfContours > 0) {
box = {
minX: Infinity,
minY: Infinity,
maxX: -Infinity,
maxY: -Infinity,
};
for (let point of glyf.points) {
box.minX = Math.min(box.minX, point.x);
box.minY = Math.min(box.minY, point.y);
box.maxX = Math.max(box.maxX, point.x);
box.maxY = Math.max(box.maxY, point.y);
}
}
if (
!Number.isFinite(box.minX) ||
(glyf.numberOfContours < 0 && glyph.path.commands.length === 0)
) {
// Empty composites have no contour box; preserve their stored bounds.
box = {
minX: glyf.xMin,
minY: glyf.yMin,
maxX: glyf.xMax,
maxY: glyf.yMax,
};
}
glyf = {
...glyf,
xMin: Math.floor(box.minX),
yMin: Math.floor(box.minY),
xMax: Math.ceil(box.maxX),
yMax: Math.ceil(box.maxY),
};
}
buffer = this.glyphEncoder.encodeGlyph(glyf, (id) =>
this.includeGlyph(id),
);
bearing = glyf.phantomPoints
? glyf.xMin - glyf.phantomPoints[0].x
: glyph._getMetrics().leftBearing;
} else {
// get the offset to the glyph from the loca table
let curOffset = this.font.loca.offsets[gid];
let nextOffset = this.font.loca.offsets[gid + 1];

let stream = this.font._getTableStream('glyf');
stream.pos += curOffset;

buffer = stream.readBuffer(nextOffset - curOffset);

bearing = glyph._getMetrics().leftBearing;
if (glyf && this.font._variationProcessor) {
// If this is a TrueType variation glyph, re-encode the path and take the
// left side bearing from it. Compound glyphs are flattened too, as the
// offsets of their components vary.
buffer = this.glyphEncoder.encodeSimple(glyph.path, glyf.instructions);
bearing = glyph.path.cbox.minX;
} else if (glyf && glyf.numberOfContours < 0) {
// if it is a compound glyph, include its components
buffer = new Uint8Array(buffer);
let view = new DataView(buffer.buffer);
for (let component of glyf.components) {
gid = this.includeGlyph(component.glyphID);
view.setUint16(component.pos, gid);
}
}
}

this.glyf.push(buffer);
this.loca.offsets.push(this.offset);

this.hmtx.metrics.push({
advance: glyph.advanceWidth,
advance: transformed
? Math.round(glyph.advanceWidth)
: glyph.advanceWidth,
bearing,
});

Expand All @@ -51,6 +102,14 @@ export default class TTFSubset extends Subset {
}

encode() {
if (
this.font.directory.tables.glyf.transformed &&
this.font.directory.tables.hmtx.transformed
) {
throw new Error(
'Subsetting WOFF2 fonts with transformed hmtx is not supported',
);
}
// tables required by PDF spec:
// head, hhea, loca, maxp, cvt , prep, glyf, hmtx, fpgm
//
Expand All @@ -61,7 +120,9 @@ export default class TTFSubset extends Subset {
this.offset = 0;
this.loca = {
offsets: [],
version: this.font.loca.version,
version: this.font.directory.tables.glyf.transformed
? 1
: this.font.loca.version,
};

this.hmtx = {
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added test/data/FontkitSubsetTest/FontkitSubsetTest.ttf
Binary file not shown.
Binary file not shown.
Binary file added test/data/FontkitSubsetTest/FontkitSubsetTest.woff2
Binary file not shown.
26 changes: 26 additions & 0 deletions test/data/FontkitSubsetTest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Fontkit subset test font

Original geometric test outlines for this repository, distributed under the
repository's MIT license. No glyphs are derived from another font.

Regenerate with Python and `fonttools[woff]==4.60.1` and `brotli==1.2.1`:

```sh
python generate.py
```

The six glyphs cover instructions on simple and composite glyphs, an empty
glyph, an uninstructed glyph after instructed glyphs, an off-curve first point,
a 300-point repeated flag run, OVERLAP_SIMPLE, and mixed XY/point-index
component arguments. The WOFF2 variants transform glyf/loca, with the `.hmtx`
variant additionally transforming horizontal metrics.

The `.empty-composite` variant has a varied composite containing only an empty
component, with a nonzero horizontal bearing.

The variable variant moves the first composite component beyond signed-byte
range at weight 900, exercising argument widening and shared overlap state.

`FontkitSubsetTest.nonzero-empty-composite.woff2` retains an explicit nonzero
header box on a varied composite whose component has no outline points. It
checks that subsetting preserves the stored bounds and phantom-derived bearing.
Loading