diff --git a/CHANGELOG.md b/CHANGELOG.md index 175e3382..dc6033fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 898ed971..6544be0c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/WOFF2Font.js b/src/WOFF2Font.js index cc5c99a6..28a237f2 100644 --- a/src/WOFF2Font.js +++ b/src/WOFF2Font.js @@ -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. @@ -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 @@ -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(); @@ -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, diff --git a/src/glyph/TTFGlyphEncoder.js b/src/glyph/TTFGlyphEncoder.js index 5707fcfc..063e503d 100644 --- a/src/glyph/TTFGlyphEncoder.js +++ b/src/glyph/TTFGlyphEncoder.js @@ -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 = []; diff --git a/src/subset/TTFSubset.js b/src/subset/TTFSubset.js index a69f3a42..50be1136 100644 --- a/src/subset/TTFSubset.js +++ b/src/subset/TTFSubset.js @@ -11,30 +11,79 @@ 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); + } } } @@ -42,7 +91,9 @@ export default class TTFSubset extends Subset { this.loca.offsets.push(this.offset); this.hmtx.metrics.push({ - advance: glyph.advanceWidth, + advance: transformed + ? Math.round(glyph.advanceWidth) + : glyph.advanceWidth, bearing, }); @@ -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 // @@ -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 = { diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.empty-composite.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.empty-composite.woff2 new file mode 100644 index 00000000..99557be8 Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.empty-composite.woff2 differ diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.hmtx.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.hmtx.woff2 new file mode 100644 index 00000000..fd85ee1d Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.hmtx.woff2 differ diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.nonzero-empty-composite.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.nonzero-empty-composite.woff2 new file mode 100644 index 00000000..b4a7ab29 Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.nonzero-empty-composite.woff2 differ diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.ttf b/test/data/FontkitSubsetTest/FontkitSubsetTest.ttf new file mode 100644 index 00000000..4b8ff411 Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.ttf differ diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 new file mode 100644 index 00000000..9591a2c4 Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 differ diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 new file mode 100644 index 00000000..46e258d1 Binary files /dev/null and b/test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 differ diff --git a/test/data/FontkitSubsetTest/README.md b/test/data/FontkitSubsetTest/README.md new file mode 100644 index 00000000..6ccf795c --- /dev/null +++ b/test/data/FontkitSubsetTest/README.md @@ -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. diff --git a/test/data/FontkitSubsetTest/generate.py b/test/data/FontkitSubsetTest/generate.py new file mode 100644 index 00000000..6c92a0f9 --- /dev/null +++ b/test/data/FontkitSubsetTest/generate.py @@ -0,0 +1,88 @@ +"""Create original geometric glyphs for exact WOFF2 subset regressions.""" +from array import array +from pathlib import Path +from fontTools.fontBuilder import FontBuilder +from fontTools.ttLib import TTFont +from fontTools.ttLib.tables._g_l_y_f import Glyph, GlyphCoordinates, GlyphComponent +from fontTools.ttLib.tables.ttProgram import Program +from fontTools.ttLib.woff2 import WOFF2FlavorData +from fontTools.ttLib.tables.TupleVariation import TupleVariation + +def simple(points, flags, hinted=True): + glyph = Glyph() + glyph.numberOfContours = 1 + glyph.coordinates = GlyphCoordinates(points) + glyph.flags = array('B', flags) + glyph.endPtsOfContours = [len(points)-1] + glyph.program = Program() + glyph.program.fromBytecode([0, 1] if hinted else []) + return glyph + +glyphs = { + '.notdef': simple([(0,0), (100,0), (100,100), (0,100)], [1]*4), + 'offcurve': simple([(-300,-300), (0,-300), (0,0), (-300,0)], [0,1,1,1]), + 'repeats': simple([(i,i) for i in range(300)], [0x41]+[1]*299), + 'space': Glyph(), + 'plain': simple([(0,0),(50,0),(0,50)], [1,1,1], False), +} +composite = Glyph() +composite.numberOfContours = -1 +component = GlyphComponent() +component.glyphName = 'offcurve' +component.x, component.y, component.flags = 25, 50, 0x200 +composite.components = [component] +attachment = GlyphComponent() +attachment.glyphName = 'plain' +attachment.firstPt, attachment.secondPt, attachment.flags = 0, 0, 0 +composite.components.append(attachment) +composite.program = Program() +composite.program.fromBytecode([1, 0]) +glyphs['composite'] = composite +order = ['.notdef', 'offcurve', 'repeats', 'space', 'plain', 'composite'] +builder = FontBuilder(1000, isTTF=True) +builder.setupGlyphOrder(order) +builder.setupCharacterMap({65:'offcurve', 66:'repeats', 32:'space', 67:'plain', 68:'composite'}) +builder.setupGlyf(glyphs) +builder.setupHorizontalMetrics({name:(600, 0) for name in order}) +builder.setupHorizontalHeader(ascent=800, descent=-200) +builder.setupNameTable({'familyName':'Fontkit Subset Test', 'styleName':'Regular', + 'uniqueFontIdentifier':'FontkitSubsetTest-Regular', + 'fullName':'Fontkit Subset Test Regular', 'psName':'FontkitSubsetTest-Regular'}) +builder.setupOS2(sTypoAscender=800, sTypoDescender=-200, usWinAscent=800, usWinDescent=200) +builder.setupPost() +builder.setupMaxp() +builder.font['head'].created = builder.font['head'].modified = 3406620153 +builder.font.recalcTimestamp = False +destination = Path(__file__).resolve().parent +builder.save(destination / 'FontkitSubsetTest.ttf') +builder.font.flavor = 'woff2' +builder.font.flavorData = WOFF2FlavorData(transformedTables={'glyf','loca'}) +builder.save(destination / 'FontkitSubsetTest.woff2') +builder.font.flavorData = WOFF2FlavorData(transformedTables={'glyf','loca','hmtx'}) +builder.save(destination / 'FontkitSubsetTest.hmtx.woff2') +builder.setupFvar([('wght', 100, 400, 900, 'Weight')], []) +builder.setupGvar({name: [] for name in order}) +builder.font['gvar'].variations['composite'] = [ + TupleVariation({'wght': (0, 1, 1)}, [(200, 0), None, None, None, None, None]) +] +builder.font.flavorData = WOFF2FlavorData(transformedTables={'glyf', 'loca'}) +builder.save(destination / 'FontkitSubsetTest.variable.woff2') +# A composite can have component records but no actual outline points. +composite.components = composite.components[:1] +composite.components[0].glyphName = 'space' +builder.font['hmtx'].metrics['composite'] = (600, 17) +builder.font['gvar'].variations['composite'] = [ + TupleVariation({'wght': (0, 1, 1)}, [(200, 0), None, None, None, None]) +] +builder.save(destination / 'FontkitSubsetTest.empty-composite.woff2') +print('generated original six-glyph fixture; hinted simple/composite, empty, off-curve first point, 300-point flag run, OVERLAP_SIMPLE') + +# Preserve an explicit nonzero header box on a composite with no outline points. +font = TTFont(destination / 'FontkitSubsetTest.empty-composite.woff2', recalcBBoxes=False) +font['glyf']['composite'].xMin = font['glyf']['composite'].xMax = 100 +font['glyf']['composite'].yMin = font['glyf']['composite'].yMax = 0 +font.recalcBBoxes = False +font.recalcTimestamp = False +font.flavor = 'woff2' +font.flavorData = WOFF2FlavorData(transformedTables={'glyf', 'loca'}) +font.save(destination / 'FontkitSubsetTest.nonzero-empty-composite.woff2') diff --git a/test/subset.js b/test/subset.js index a800e59f..29da869a 100644 --- a/test/subset.js +++ b/test/subset.js @@ -134,6 +134,237 @@ describe('font subsetting', function () { }); }); + describe('WOFF2 TrueType subsetting', function () { + function open(name) { + return fontkit.openSync(new URL(`data/${name}`, import.meta.url)); + } + + function checkSubset(font, reference, ids) { + let subset = font.createSubset(); + for (let id of ids) subset.includeGlyph(id); + let result = fontkit.create(subset.encode()); + assert.equal(result.numGlyphs, subset.glyphs.length); + for (let [index, id] of subset.glyphs.entries()) { + let actual = result.getGlyph(index); + let expected = reference.getGlyph(id); + assert.equal(actual.path.toSVG(), expected.path.toSVG()); + assert.equal(actual.advanceWidth, expected.advanceWidth); + assert.equal( + actual._getMetrics().leftBearing, + expected._getMetrics().leftBearing, + ); + let decoded = actual._decode(); + let original = expected._decode(); + if (original && original.numberOfContours > 0) { + assert.deepEqual(decoded.points, original.points); + assert.deepEqual(decoded.instructions, original.instructions); + for (let field of ['xMin', 'yMin', 'xMax', 'yMax']) { + assert.equal(decoded[field], original[field]); + } + } else if (original && original.numberOfContours < 0) { + // Components and their instructions are already in TrueType format. + let source = reference._getTableStream('glyf'); + source.pos += reference.loca.offsets[id]; + let bytes = new Uint8Array( + source.readBuffer( + reference.loca.offsets[id + 1] - reference.loca.offsets[id], + ), + ); + let view = new DataView(bytes.buffer); + let hasInstructions = false; + for (let component of original.components) { + hasInstructions ||= !!(view.getUint16(component.pos - 2) & 0x100); + view.setUint16(component.pos, subset.mapping[component.glyphID]); + } + let last = original.components[original.components.length - 1]; + let flags = view.getUint16(last.pos - 2); + let end = last.pos + 2 + (flags & 1 ? 4 : 2); + end += flags & 8 ? 2 : flags & 64 ? 4 : flags & 128 ? 8 : 0; + if (hasInstructions) end += 2 + view.getUint16(end); + bytes = bytes.subarray(0, end); + let output = result._getTableStream('glyf'); + output.pos += result.loca.offsets[index]; + assert.deepEqual(output.readBuffer(bytes.length), bytes); + } else { + assert.equal( + result.loca.offsets[index], + result.loca.offsets[index + 1], + ); + } + } + assert.deepEqual(subset.encode(), result.stream.buffer); + return result; + } + + it('preserves hinted glyphs, component arguments and overlapping contours', function () { + let font = open('FontkitSubsetTest/FontkitSubsetTest.woff2'); + let reference = open('FontkitSubsetTest/FontkitSubsetTest.ttf'); + assert.deepEqual(reference.getGlyph(1)._decode().instructions, [0, 1]); + assert.equal(reference.getGlyph(1)._decode().points[0].onCurve, false); + assert.equal(reference.getGlyph(2)._decode().points.length, 300); + let result = checkSubset(font, reference, [5, 2, 1, 4, 3]); + let data = result._getTableStream('glyf'); + // Requested glyph 2 is subset index 2, after .notdef and the composite. + data.pos += result.loca.offsets[2] + 10 + 2 + 2 + 2; + assert.equal(data.readUInt8() & 0x40, 0x40); + assert.equal(result.head.indexToLocFormat, 1); + }); + + it('preserves the bearing of a varied composite with only empty components', function () { + let font = open( + 'FontkitSubsetTest/FontkitSubsetTest.empty-composite.woff2', + ).getVariation({ wght: 900 }); + let glyph = font.glyphForCodePoint(68); + assert.equal(glyph.path.commands.length, 0); + let subset = font.createSubset(); + let id = subset.includeGlyph(glyph); + let output = fontkit.create(subset.encode()).getGlyph(id); + assert.equal(output.path.commands.length, 0); + assert.equal(output._decode().numberOfContours, -1); + assert.deepEqual( + ['xMin', 'yMin', 'xMax', 'yMax'].map((key) => output._decode()[key]), + [0, 0, 0, 0], + ); + assert.equal(output.advanceWidth, 600); + assert.equal(output._getMetrics().leftBearing, 17); + }); + + it('preserves stored bounds and bearing for a varied empty composite', function () { + let font = open( + 'FontkitSubsetTest/FontkitSubsetTest.nonzero-empty-composite.woff2', + ).getVariation({ wght: 900 }); + let glyph = font.glyphForCodePoint(68); + let fields = ['xMin', 'yMin', 'xMax', 'yMax']; + let bounds = fields.map((key) => glyph._decode()[key]); + assert.deepEqual(bounds, [100, 0, 100, 0]); + assert.equal(glyph.path.commands.length, 0); + assert.equal(glyph._getMetrics().leftBearing, 17); + let subset = font.createSubset(); + let id = subset.includeGlyph(glyph); + let output = fontkit.create(subset.encode()).getGlyph(id); + assert.equal(output.path.commands.length, 0); + assert.deepEqual( + fields.map((key) => output._decode()[key]), + bounds, + ); + assert.equal(output.advanceWidth, glyph.advanceWidth); + assert.equal( + output._getMetrics().leftBearing, + glyph._getMetrics().leftBearing, + ); + }); + + it('preserves overlap flags and widens varied component arguments', function () { + let font = open('FontkitSubsetTest/FontkitSubsetTest.variable.woff2'); + let variation = font.getVariation({ wght: 900 }); + let subset = variation.createSubset(); + let compositeId = subset.includeGlyph(5); + let repeatedId = subset.includeGlyph(2); + let result = fontkit.create(subset.encode()); + let composite = result.getGlyph(compositeId)._decode(); + assert.equal(composite.components[0].dx, 225); + assert.equal(composite.components[0].dy, 50); + assert.equal(composite.components[1].dx, 0); + assert.equal(composite.components[1].dy, 0); + let stream = result._getTableStream('glyf'); + stream.pos += result.loca.offsets[compositeId] + 10; + assert.equal(stream.readUInt16BE() & 1, 1); + stream = result._getTableStream('glyf'); + stream.pos += result.loca.offsets[repeatedId] + 16; + assert.equal(stream.readUInt8() & 0x40, 0x40); + assert.equal(font.getGlyph(5)._decode().components[0].dx, 25); + }); + + it('does not read transformed source loca offsets', function () { + let font = open('FontkitSubsetTest/FontkitSubsetTest.woff2'); + let decode = font._decodeTable; + font._decodeTable = function (table) { + assert.notEqual(table.tag, 'loca'); + return decode.call(this, table); + }; + let subset = font.createSubset(); + subset.includeGlyph(5); + assert.equal(fontkit.create(subset.encode()).head.indexToLocFormat, 1); + }); + + it('refuses unsupported transformed horizontal metrics', function () { + let font = open('FontkitSubsetTest/FontkitSubsetTest.hmtx.woff2'); + assert.equal(font.directory.tables.hmtx.transformed, true); + let subset = font.createSubset(); + subset.includeGlyph(1); + assert.throws(() => subset.encode(), /transformed hmtx/); + }); + + for (let text of ['Abcd', 'é', ' A ']) { + it(`preserves points, instructions and metrics for ${JSON.stringify(text)}`, function () { + let font = open('SourceSansPro/SourceSansPro-Regular.ttf.woff2'); + let reference = open('SourceSansPro/SourceSansPro-Regular.ttf.woff'); + assert.ok(font.glyphsForString('A')[0].path.commands.length > 0); + checkSubset( + font, + reference, + font.glyphsForString(text).map((g) => g.id), + ); + }); + } + + it('preserves every glyph of a transformed font', function () { + let font = open('SourceSansPro/SourceSansPro-Regular.ttf.woff2'); + let reference = open('SourceSansPro/SourceSansPro-Regular.ttf.woff'); + checkSubset( + font, + reference, + Array.from({ length: font.numGlyphs }, (_, id) => id).reverse(), + ); + }); + + for (let name of ['TestGVAROne', 'TestGVAROne.untransformed']) { + it(`subsets ${name} without changing its source`, function () { + let font = open(`fonttest/${name}.woff2`); + let reference = open('fonttest/TestGVAROne.ttf'); + checkSubset( + font, + reference, + Array.from({ length: font.numGlyphs }, (_, id) => id), + ); + assert.equal( + font.getGlyph(0).path.toSVG(), + reference.getGlyph(0).path.toSVG(), + ); + }); + } + + it('subsets simple glyphs at non-default variation coordinates', function () { + let font = open('fonttest/TestGVAROne.woff2'); + let variation = font.getVariation({ wght: 300 }); + let glyph = variation.glyphsForString('彌')[0]; + let subset = variation.createSubset(); + let id = subset.includeGlyph(glyph); + let result = fontkit.create(subset.encode()).getGlyph(id); + assert.equal(result.path.toSVG(), glyph.path.toSVG()); + assert.equal(result.advanceWidth, glyph.advanceWidth); + assert.equal( + font.getGlyph(glyph.id).path.toSVG(), + open('fonttest/TestGVAROne.ttf').getGlyph(glyph.id).path.toSVG(), + ); + }); + + it('updates phantom-point advances before encoding a varied simple glyph', function () { + let font = open('fonttest/TestGVAROne.woff2').getVariation({ wght: 650 }); + let subset = font.createSubset(); + let result = fontkit.create(subset.encode()); + assert.equal(result.getGlyph(0).advanceWidth, 517); + }); + + it('leaves varied empty glyph records empty', function () { + let font = open('fonttest/TestGVAROne.woff2').getVariation({ wght: 333 }); + let subset = font.createSubset(); + let id = subset.includeGlyph(font.glyphsForString(' ')[0]); + let result = fontkit.create(subset.encode()); + assert.equal(result.loca.offsets[id], result.loca.offsets[id + 1]); + }); + }); + describe('CFF subsetting', function () { let font = fontkit.openSync( new URL('data/SourceSansPro/SourceSansPro-Regular.otf', import.meta.url),