From 89e0912fa41174e3daf515136c200163c6bc96dc Mon Sep 17 00:00:00 2001 From: snowyukitty <270071858+snowyukitty@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:00:13 +0900 Subject: [PATCH 1/2] Reconstruct transformed WOFF2 glyphs when subsetting --- CHANGELOG.md | 4 + README.md | 5 + src/WOFF2Font.js | 33 ++- src/glyph/TTFGlyphEncoder.js | 104 +++++++++ src/subset/TTFSubset.js | 102 +++++++-- .../FontkitSubsetTest.empty-composite.woff2 | Bin 0 -> 520 bytes .../FontkitSubsetTest.hmtx.woff2 | Bin 0 -> 484 bytes .../FontkitSubsetTest/FontkitSubsetTest.ttf | Bin 0 -> 1652 bytes .../FontkitSubsetTest.variable.woff2 | Bin 0 -> 532 bytes .../FontkitSubsetTest/FontkitSubsetTest.woff2 | Bin 0 -> 488 bytes test/data/FontkitSubsetTest/README.md | 22 ++ test/data/FontkitSubsetTest/generate.py | 77 +++++++ test/subset.js | 206 ++++++++++++++++++ 13 files changed, 525 insertions(+), 28 deletions(-) create mode 100644 test/data/FontkitSubsetTest/FontkitSubsetTest.empty-composite.woff2 create mode 100644 test/data/FontkitSubsetTest/FontkitSubsetTest.hmtx.woff2 create mode 100644 test/data/FontkitSubsetTest/FontkitSubsetTest.ttf create mode 100644 test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 create mode 100644 test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 create mode 100644 test/data/FontkitSubsetTest/README.md create mode 100644 test/data/FontkitSubsetTest/generate.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a19d58a..713b8476 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 - Ignore the advances of marks zeroed after GPOS when positioning attached marks - Position marks like HarfBuzz in fonts without GPOS (#409) - Fix canonical composition fallback, Arabic mark ordering, and positioning in fonts without GSUB diff --git a/README.md b/README.md index 027b61ce..086d206b 100644 --- a/README.md +++ b/README.md @@ -261,6 +261,11 @@ 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 use Fontkit's existing variation engine; +`cvar` adjustments are not instantiated. + ## License MIT diff --git a/src/WOFF2Font.js b/src/WOFF2Font.js index e3577928..f8959ff4 100644 --- a/src/WOFF2Font.js +++ b/src/WOFF2Font.js @@ -109,6 +109,10 @@ export default 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 default 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 default 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 bbf9f0f1..e4d7d22a 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 ae8a4803..065e1926 100644 --- a/src/subset/TTFSubset.js +++ b/src/subset/TTFSubset.js @@ -13,35 +13,81 @@ 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); - - // if it is a compound glyph, include its components - if (glyf && glyf.numberOfContours < 0) { - 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; + + 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)) { + 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), + ); + } 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); + + // if it is a compound glyph, include its components + if (glyf && glyf.numberOfContours < 0) { + 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); + } + } else if (glyf && this.font._variationProcessor) { + // If this is a TrueType variation glyph, re-encode the path + buffer = this.glyphEncoder.encodeSimple(glyph.path, glyf.instructions); } - } else if (glyf && this.font._variationProcessor) { - // If this is a TrueType variation glyph, re-encode the path - buffer = this.glyphEncoder.encodeSimple(glyph.path, glyf.instructions); } this.glyf.push(buffer); this.loca.offsets.push(this.offset); this.hmtx.metrics.push({ - advance: glyph.advanceWidth, - bearing: glyph._getMetrics().leftBearing, + advance: transformed + ? Math.round(glyph.advanceWidth) + : glyph.advanceWidth, + bearing: + transformed && glyf.phantomPoints + ? glyf.xMin - glyf.phantomPoints[0].x + : glyph._getMetrics().leftBearing, }); this.offset += buffer.length; @@ -49,6 +95,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 // @@ -59,7 +113,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 0000000000000000000000000000000000000000..99557be8a4fb407cfe75d9d7432f87c075232a41 GIT binary patch literal 520 zcmXT-cQayOWB>vt4h9|&%`U>gz_$G6Gk&86=pteJ_Z&A z)@C7ge`yW21i98;V@+-MQZp^PYZdd#-+tbwQeU>6V-07|Y86(E)d45v&bw`Lnelu7 z&+u+0+xM(u{&#jf|JxF*vx41kxix=5h1~@QcB@POwYlHe*u}rh{L#>*)1z{^#o)GD zW#B!5#^61{J6iTGjyiYwyhHLUhVSx6nB29#SZ8pZXRKh1c+sWlsF82B;I+%mMYq2* zSX3;l?_Izdae(nG%hUXm!3H&j5)-$0ybH{CQm`^$W8O6PjcdE1gqYxx_tCGfU++1$ z!aVu)3?Fl?#r~6~rCfVuy1z*Ayq=kFNLFBaUKWGE#0UkBh$V-4;%tjd-7>>v9V{R0 z_Y#n^=RGdE?6a@`UxxL^_WW)AQm?w{7t<=HLtEc!KIc3smBDKG)JE~LFza2HJvMxT zJ%#ZOK5cI%ocvT_dRd3@Y|d=f66Wn3a~JQ}BDnF)OTPG?;@0(MJ5QV6w#l@T;7G2i z`B|AXQ^4=!ua_UVE3}PfyBfdN+_W*nm*r^Bwr`>xuQxb%b22UW*y_&Sc-e|yxjCk$L5nymuJo&^yD@lgR=0)q=zYe=gXqZyNmGaoNE9|Ma5Yf}ch zzw~NWhI!3}kMHnpjX2`^_u-vJ*Ox0(KiX`u-&dUej5(@-^ORHOxt>aAX73j5KWlDn zV~@M#``lag*O%}R>6BJ>p_~JZX;vC}8(u81F9?2XbN0|@10ItL9`Cp7{9BNJJ^f#< z#RUg;v&l30MAC0N`Fpi;bj?`*vGbS9)|kbDSw6B4Hf~Pny*$-VKs1iwK=y${AwKMZ zn{G0Hn-=J{au;)h@apn>21jQRU;ahnJd4|9)Z7i`82?pj`2S>Gw&V8O=L6X8_g#5- zM$*?={DH>#w>Q_nSy-;|&3D0+(oGxsGfe*Eizgnm6YMl?`tY?d(eu90D*49ihu_x~ z?qX58J%53g!kW#FJK0j$w>0T!UT?5^k*oDp^VF{ZmgaX#0>K;_zkE1Xi0RC_pmS6H z%Qf3om)MS|rJr&#eAO55_H#f6U*(hUPWvZTrp}DZv;SQ3{`#A1-I>#7`91eYSQmZd zpR{86jlE)%#dp6*wz1ML^L+j>tAuU-RJY`fPgfjxW-Oa*dvNleTi#x)W=)&-?{#hd V{@?E(B`>HrG}*-O|B4Icxd3WV(~tlF literal 0 HcmV?d00001 diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.ttf b/test/data/FontkitSubsetTest/FontkitSubsetTest.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4b8ff411ec04c492433a2b8133101927af02b68a GIT binary patch literal 1652 zcmeHHKWGzC9RA+B%cYf25xcZquC}PyRP6 zvj`(bs3hqdIwMt5)nrLLMgsb%?EtLu+;2HH5)=6-2hGHXeK7)Nl-Wd7<)CrQa#lOe z^6c|m4X%P2a>pPbH*qBhg0DpCE0v#8b><4Bupq9nUl+Al2OM@)8?lzTu;e%nzgJbG z9@R`>@z^4(m=0?h*GkotRi*1zF36n`hwZQe|Gfgy4F)WB-u|`BDa*2gVDKw2Fb7MX zfS9v*$<-Z~>az3Yx*Ohl9Gw@@q zF^>l^){({Q7#k|S-fsCjb>A%ZwmsK3w_MNPbgR9F-HnwS(DwPIobSFHcj^X#K|8yL5iaFsLe+^aL$D6^zOQAs%x=2j5 fE0uDud)rNR-HvPfUZT^m>#gZ>yU7Q=?z{L4p)IOE literal 0 HcmV?d00001 diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.variable.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..9591a2c451c7076ba22471b486e4f48b469513e1 GIT binary patch literal 532 zcmXT-cQayOWB>vt5e6O*%`U^hz<3lQ2I8Xvwgd(jeHE_OkXA1P6Gk&86=pteJ_Z&A z)@C7ge`!6o1UdG;*8%fet`rM%trM($>;7%eU2dUlrpHR2jHiNEYRE1;;W3Tl{`>7e z56a;K<{=VRx-v%u?f!q1#_?6E)*Y=!|uVley&iTcs9(_J=F1$)gEJKW4#BEZh zlf)6TlikM^nU+^9FX*gtU%Rd=P}wS&t>TNuG|Q{gcz>@jI?q@k8R2tyje=L%?E{8) zSEyDUW;pPX`*1c(>;WcsiDfJItDZl!}eKBCbecvH|B~7Z%C3 zd+lp=g^eGcePX6r+0VJH5`F1-BlzrnE@YZsMioJ?U7 zhh_TZ>aEpYY?oEGc(&hHU|w8$Pal6R_hq{St3C7UC;kiX$l24h%)w%haH;4CwJS|# zrJ^s`li9qIr&jT598~ca5HJ=DI5taj!OZ-|hP;JynU0m*QSK?6rChrw;&GC*M(`b> zS+a86cjeB{GMvFVxn|G*%CxyN^=>?S`%}5%b*-8A*%j>`8*}_zPSzB^)mA99+HkdJ zBKMkOtB;>>-7D_>)$Q7{ZzpQDeRe$h>$Z&2-v+OIvsnfw^JJa1e7(<~*pYqs!ma18 TnaxA?%v0}QY;RPu9+(yY(?Q+K literal 0 HcmV?d00001 diff --git a/test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 b/test/data/FontkitSubsetTest/FontkitSubsetTest.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..46e258d121657e3949933a56eaea5a24d103201b GIT binary patch literal 488 zcmXT-cQayOWB>xj7Ytk=nymuJo&ymB@lgR=0)q=zYe=gXqZyM5Gaok}1B(J{QwF=g z^cq$MJ@yKtp6SXgVY#ye59kRY>mN z_S^S1PXFc{xzc67o#7ejlveg2zBN;>Gw1x<&tk$?x_f`)?5yXRV)NJ~G8RN0`W`J- zf8o}?^M7s^EMTrmFrN9+p>Uh-mn9(`3p##E&0pbv<&~E7%5zf~y!T< z_oRL~+wxJz$SV1H;>r`bx9guey$|?yZbg)~_qR5`BO&tdbCAjZ2! zzgc*$#b#Y{KjOChwA0Lz=!|bw3MK5eU)UGMpS0QJqt83P?#^%X-Ct8?EnRlm^3jZ| zx=R0h11#Ufb)W2x`EXJ0TzAY9n>btbA8SOUx^<&1#pY*9zvP?vghh+xp7< YeZR|pS_as>43wHaKjg)2Ghh?~0A 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 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), From 8c1ba091faa742158f681d4acddc815e92033469 Mon Sep 17 00:00:00 2001 From: snowyukitty <270071858+snowyukitty@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:13:27 +0900 Subject: [PATCH 2/2] Keep unmerged WOFF2 fixes in the Unreleased changelog --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6c092ea..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 @@ -18,10 +22,6 @@ - Round HVAR advance deltas to whole units like HarfBuzz, so subsets of fonts with set variations no longer truncate advances such as 851.9999 to 851 - Fix glyphs in subsets of fonts with set variations: write the count of repeated flags at the end of a glyph, flatten composite glyphs, and take the left side bearings from the varied outlines - Take the ascent, descent and line gap from the typo metrics when the font sets useTypoMetrics, like HarfBuzz, and fix the vhea structure, 16.16 table versions, and boxes of empty glyphs (#305, #306) -- 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 - Use non-default variation sequences when the variation selector also has default ones - Add `fontkit/core` and `fontkit/formats/{format}` entry points with named format exports for explicit format registration, sharing state with the default entries - Remove the fast-deep-equal runtime dependency