@zumer/snapdom-pdf 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +17 -5
- package/index.d.ts +14 -5
- package/package.json +4 -3
- package/src/index.js +178 -17
- package/src/mega/fonts.js +118 -11
- package/src/page-image.js +147 -0
- package/src/text-layer.js +105 -9
- package/src/writer/brotli-dictionary.js +676 -0
- package/src/writer/brotli.js +589 -0
- package/src/writer/font.js +12 -5
- package/src/writer/index.js +5 -5
- package/src/writer/woff2.js +455 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WOFF2 -> a plain sfnt (TrueType or OpenType/CFF), so the font the page is drawn
|
|
3
|
+
* with can travel in the exported file.
|
|
4
|
+
*
|
|
5
|
+
* WOFF2 is not a wrapper round the original tables the way WOFF 1 is. Every table
|
|
6
|
+
* sits behind ONE Brotli stream (`brotli.js`), and two of them are stored
|
|
7
|
+
* TRANSFORMED: `glyf` is taken apart into seven parallel streams — contour counts,
|
|
8
|
+
* point counts, flags, coordinates packed as "triplets", composites, bounding
|
|
9
|
+
* boxes, instructions — with `loca` dropped altogether, and `hmtx` may have lost
|
|
10
|
+
* the side bearings that can be read back off the outlines. A viewer cannot use
|
|
11
|
+
* any of that; the tables have to be put back together the way the font compiler
|
|
12
|
+
* wrote them. That is what this file does, to the letter of the W3C
|
|
13
|
+
* recommendation (WOFF File Format 2.0, sections 4 and 5).
|
|
14
|
+
*
|
|
15
|
+
* What it does NOT do, and says so instead:
|
|
16
|
+
*
|
|
17
|
+
* - **Font collections** (`ttcf` flavour): several faces behind shared tables;
|
|
18
|
+
* the caller would have to pick one and this exporter never knows which.
|
|
19
|
+
* - **Byte-for-byte identity with the original .ttf.** The transform is lossless
|
|
20
|
+
* for what a renderer reads — every point, flag meaning, instruction and
|
|
21
|
+
* metric — but not for how the compiler happened to pack them: flag runs are
|
|
22
|
+
* written unrepeated here and glyphs are padded to four bytes. The outlines are
|
|
23
|
+
* the same outlines (`test/verify-woff2.mjs` draws both and compares pixels).
|
|
24
|
+
*
|
|
25
|
+
* Loaded with `import()` from `font.js`, and only when a WOFF2 arrives.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { brotliDecode } from './brotli.js'
|
|
29
|
+
|
|
30
|
+
/** The 63 tags a table directory entry names by number (section 4.1). */
|
|
31
|
+
const KNOWN_TAGS = [
|
|
32
|
+
'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep',
|
|
33
|
+
'CFF ', 'VORG', 'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT', 'VDMX', 'vhea', 'vmtx', 'BASE',
|
|
34
|
+
'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH', 'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt',
|
|
35
|
+
'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar',
|
|
36
|
+
'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill',
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
const fail = (message) => { throw new Error(`woff2: ${message}`) }
|
|
40
|
+
|
|
41
|
+
/** A forward-only reader over one stream of the transformed data. */
|
|
42
|
+
class Reader {
|
|
43
|
+
constructor (bytes, start = 0, end = bytes.length) {
|
|
44
|
+
this.b = bytes
|
|
45
|
+
this.at = start
|
|
46
|
+
this.end = end
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
need (n) { if (this.at + n > this.end) fail('a stream ends before its data does') }
|
|
50
|
+
u8 () { this.need(1); return this.b[this.at++] }
|
|
51
|
+
u16 () { this.need(2); const v = (this.b[this.at] << 8) | this.b[this.at + 1]; this.at += 2; return v }
|
|
52
|
+
i16 () { const v = this.u16(); return v & 0x8000 ? v - 0x10000 : v }
|
|
53
|
+
u32 () { this.need(4); const b = this.b; const v = ((b[this.at] << 24) | (b[this.at + 1] << 16) | (b[this.at + 2] << 8) | b[this.at + 3]) >>> 0; this.at += 4; return v }
|
|
54
|
+
bytes (n) { this.need(n); const v = this.b.subarray(this.at, this.at + n); this.at += n; return v }
|
|
55
|
+
|
|
56
|
+
/** UIntBase128: up to five bytes, seven bits each, no leading zeros. */
|
|
57
|
+
base128 () {
|
|
58
|
+
let value = 0
|
|
59
|
+
for (let i = 0; i < 5; i++) {
|
|
60
|
+
const byte = this.u8()
|
|
61
|
+
if (i === 0 && byte === 0x80) fail('a UIntBase128 with a leading zero')
|
|
62
|
+
if (value > 0x1ffffff) fail('a UIntBase128 past 32 bits')
|
|
63
|
+
value = value * 128 + (byte & 0x7f)
|
|
64
|
+
if (!(byte & 0x80)) return value
|
|
65
|
+
}
|
|
66
|
+
fail('a UIntBase128 longer than five bytes')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 255UInt16: one to three bytes. */
|
|
70
|
+
u255 () {
|
|
71
|
+
const code = this.u8()
|
|
72
|
+
if (code === 253) return this.u16()
|
|
73
|
+
if (code === 255) return this.u8() + 253
|
|
74
|
+
if (code === 254) return this.u8() + 506
|
|
75
|
+
return code
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A byte sink that grows. */
|
|
80
|
+
class Sink {
|
|
81
|
+
constructor (size = 1024) { this.b = new Uint8Array(size); this.n = 0 }
|
|
82
|
+
room (k) {
|
|
83
|
+
if (this.n + k <= this.b.length) return
|
|
84
|
+
let size = this.b.length * 2
|
|
85
|
+
while (size < this.n + k) size *= 2
|
|
86
|
+
const grown = new Uint8Array(size)
|
|
87
|
+
grown.set(this.b.subarray(0, this.n))
|
|
88
|
+
this.b = grown
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
u8 (v) { this.room(1); this.b[this.n++] = v & 0xff }
|
|
92
|
+
u16 (v) { this.room(2); this.b[this.n++] = (v >> 8) & 0xff; this.b[this.n++] = v & 0xff }
|
|
93
|
+
u32 (v) { this.room(4); this.b[this.n++] = (v >>> 24) & 0xff; this.b[this.n++] = (v >>> 16) & 0xff; this.b[this.n++] = (v >>> 8) & 0xff; this.b[this.n++] = v & 0xff }
|
|
94
|
+
put (bytes) { this.room(bytes.length); this.b.set(bytes, this.n); this.n += bytes.length }
|
|
95
|
+
pad (to) { while (this.n % to) this.u8(0) }
|
|
96
|
+
done () { return this.b.subarray(0, this.n) }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const sign = (flag, value) => (flag & 1 ? value : -value)
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* `glyf` and `loca` back from the transformed table (section 5.1).
|
|
103
|
+
*
|
|
104
|
+
* @param {Uint8Array} data the transformed glyf table
|
|
105
|
+
* @returns {{glyf: Uint8Array, loca: Uint8Array, indexFormat: number, numGlyphs: number, xMins: Int16Array}}
|
|
106
|
+
*/
|
|
107
|
+
function rebuildGlyf (data) {
|
|
108
|
+
const head = new Reader(data)
|
|
109
|
+
head.u16() // reserved
|
|
110
|
+
const options = head.u16()
|
|
111
|
+
const numGlyphs = head.u16()
|
|
112
|
+
const indexFormat = head.u16()
|
|
113
|
+
const sizes = []
|
|
114
|
+
for (let i = 0; i < 7; i++) sizes.push(head.u32())
|
|
115
|
+
let at = head.at
|
|
116
|
+
const stream = (size) => { const r = new Reader(data, at, at + size); if (at + size > data.length) fail('a glyf stream runs past the table'); at += size; return r }
|
|
117
|
+
const contours = stream(sizes[0])
|
|
118
|
+
const points = stream(sizes[1])
|
|
119
|
+
const flags = stream(sizes[2])
|
|
120
|
+
const glyphs = stream(sizes[3])
|
|
121
|
+
const composites = stream(sizes[4])
|
|
122
|
+
const bboxes = stream(sizes[5])
|
|
123
|
+
const instructions = stream(sizes[6])
|
|
124
|
+
// The bbox stream opens with one bit per glyph: "this glyph's box is stored".
|
|
125
|
+
const bitmapSize = 4 * Math.floor((numGlyphs + 31) / 32)
|
|
126
|
+
const bboxBitmap = bboxes.bytes(bitmapSize)
|
|
127
|
+
// Optional: one bit per glyph for OVERLAP_SIMPLE, which the flag stream has no room for.
|
|
128
|
+
const overlapBitmap = options & 1 ? new Reader(data, at, data.length).bytes(Math.floor((numGlyphs + 7) / 8)) : null
|
|
129
|
+
|
|
130
|
+
const out = new Sink(Math.max(1024, data.length * 2))
|
|
131
|
+
const offsets = new Uint32Array(numGlyphs + 1)
|
|
132
|
+
const xMins = new Int16Array(numGlyphs)
|
|
133
|
+
|
|
134
|
+
for (let g = 0; g < numGlyphs; g++) {
|
|
135
|
+
offsets[g] = out.n
|
|
136
|
+
const nContours = contours.i16()
|
|
137
|
+
const hasBox = !!(bboxBitmap[g >> 3] & (0x80 >> (g & 7)))
|
|
138
|
+
|
|
139
|
+
if (nContours === 0) {
|
|
140
|
+
if (hasBox) fail('an empty glyph with a stored bounding box')
|
|
141
|
+
continue
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (nContours > 0) {
|
|
145
|
+
// a simple glyph
|
|
146
|
+
const ends = new Uint16Array(nContours)
|
|
147
|
+
let total = 0
|
|
148
|
+
for (let c = 0; c < nContours; c++) {
|
|
149
|
+
total += points.u255()
|
|
150
|
+
if (total > 0xffff + 1) fail('a glyph with more points than a glyph can have')
|
|
151
|
+
ends[c] = total - 1
|
|
152
|
+
}
|
|
153
|
+
const xs = new Int32Array(total)
|
|
154
|
+
const ys = new Int32Array(total)
|
|
155
|
+
const on = new Uint8Array(total)
|
|
156
|
+
let x = 0
|
|
157
|
+
let y = 0
|
|
158
|
+
let xMin = 0
|
|
159
|
+
let yMin = 0
|
|
160
|
+
let xMax = 0
|
|
161
|
+
let yMax = 0
|
|
162
|
+
for (let p = 0; p < total; p++) {
|
|
163
|
+
let flag = flags.u8()
|
|
164
|
+
on[p] = flag & 0x80 ? 0 : 1
|
|
165
|
+
flag &= 0x7f
|
|
166
|
+
let dx
|
|
167
|
+
let dy
|
|
168
|
+
if (flag < 10) {
|
|
169
|
+
dx = 0
|
|
170
|
+
dy = sign(flag, ((flag & 14) << 7) + glyphs.u8())
|
|
171
|
+
} else if (flag < 20) {
|
|
172
|
+
dx = sign(flag, (((flag - 10) & 14) << 7) + glyphs.u8())
|
|
173
|
+
dy = 0
|
|
174
|
+
} else if (flag < 84) {
|
|
175
|
+
const b0 = flag - 20
|
|
176
|
+
const b1 = glyphs.u8()
|
|
177
|
+
dx = sign(flag, 1 + (b0 & 0x30) + (b1 >> 4))
|
|
178
|
+
dy = sign(flag >> 1, 1 + ((b0 & 0x0c) << 2) + (b1 & 0x0f))
|
|
179
|
+
} else if (flag < 120) {
|
|
180
|
+
const b0 = flag - 84
|
|
181
|
+
dx = sign(flag, 1 + (Math.floor(b0 / 12) << 8) + glyphs.u8())
|
|
182
|
+
dy = sign(flag >> 1, 1 + (((b0 % 12) >> 2) << 8) + glyphs.u8())
|
|
183
|
+
} else if (flag < 124) {
|
|
184
|
+
const b0 = glyphs.u8()
|
|
185
|
+
const b1 = glyphs.u8()
|
|
186
|
+
const b2 = glyphs.u8()
|
|
187
|
+
dx = sign(flag, (b0 << 4) + (b1 >> 4))
|
|
188
|
+
dy = sign(flag >> 1, ((b1 & 0x0f) << 8) + b2)
|
|
189
|
+
} else {
|
|
190
|
+
dx = sign(flag, glyphs.u16())
|
|
191
|
+
dy = sign(flag >> 1, glyphs.u16())
|
|
192
|
+
}
|
|
193
|
+
x += dx
|
|
194
|
+
y += dy
|
|
195
|
+
xs[p] = x
|
|
196
|
+
ys[p] = y
|
|
197
|
+
if (p === 0) { xMin = xMax = x; yMin = yMax = y } else {
|
|
198
|
+
if (x < xMin) xMin = x
|
|
199
|
+
if (x > xMax) xMax = x
|
|
200
|
+
if (y < yMin) yMin = y
|
|
201
|
+
if (y > yMax) yMax = y
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const instructionLength = glyphs.u255()
|
|
205
|
+
const code = instructions.bytes(instructionLength)
|
|
206
|
+
if (hasBox) { xMin = bboxes.i16(); yMin = bboxes.i16(); xMax = bboxes.i16(); yMax = bboxes.i16() }
|
|
207
|
+
xMins[g] = xMin
|
|
208
|
+
|
|
209
|
+
out.u16(nContours)
|
|
210
|
+
out.u16(xMin); out.u16(yMin); out.u16(xMax); out.u16(yMax)
|
|
211
|
+
for (let c = 0; c < nContours; c++) out.u16(ends[c])
|
|
212
|
+
out.u16(instructionLength)
|
|
213
|
+
out.put(code)
|
|
214
|
+
// Flags, one per point and unrepeated: fewer ways to be wrong than a run-length
|
|
215
|
+
// pass, at a cost in bytes the file's own compression takes back.
|
|
216
|
+
const overlap = overlapBitmap && (overlapBitmap[g >> 3] & (0x80 >> (g & 7)))
|
|
217
|
+
const dxs = new Int32Array(total)
|
|
218
|
+
const dys = new Int32Array(total)
|
|
219
|
+
for (let p = 0; p < total; p++) {
|
|
220
|
+
dxs[p] = xs[p] - (p ? xs[p - 1] : 0)
|
|
221
|
+
dys[p] = ys[p] - (p ? ys[p - 1] : 0)
|
|
222
|
+
let f = on[p] ? 0x01 : 0
|
|
223
|
+
const ax = Math.abs(dxs[p])
|
|
224
|
+
const ay = Math.abs(dys[p])
|
|
225
|
+
if (dxs[p] === 0) f |= 0x10 // same x, no bytes
|
|
226
|
+
else if (ax < 256) f |= 0x02 | (dxs[p] > 0 ? 0x10 : 0) // one byte, bit 4 = positive
|
|
227
|
+
if (dys[p] === 0) f |= 0x20
|
|
228
|
+
else if (ay < 256) f |= 0x04 | (dys[p] > 0 ? 0x20 : 0)
|
|
229
|
+
if (p === 0 && overlap) f |= 0x40
|
|
230
|
+
out.u8(f)
|
|
231
|
+
}
|
|
232
|
+
for (let p = 0; p < total; p++) {
|
|
233
|
+
const d = dxs[p]
|
|
234
|
+
if (d === 0) continue
|
|
235
|
+
if (Math.abs(d) < 256) out.u8(Math.abs(d))
|
|
236
|
+
else out.u16(d)
|
|
237
|
+
}
|
|
238
|
+
for (let p = 0; p < total; p++) {
|
|
239
|
+
const d = dys[p]
|
|
240
|
+
if (d === 0) continue
|
|
241
|
+
if (Math.abs(d) < 256) out.u8(Math.abs(d))
|
|
242
|
+
else out.u16(d)
|
|
243
|
+
}
|
|
244
|
+
out.pad(4)
|
|
245
|
+
continue
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// a composite glyph: its component records are stored as they were
|
|
249
|
+
if (nContours !== -1) fail('a glyph with a negative contour count other than -1')
|
|
250
|
+
if (!hasBox) fail('a composite glyph without a stored bounding box')
|
|
251
|
+
const start = composites.at
|
|
252
|
+
let more = true
|
|
253
|
+
let withInstructions = false
|
|
254
|
+
while (more) {
|
|
255
|
+
const f = composites.u16()
|
|
256
|
+
composites.u16() // glyph index
|
|
257
|
+
let args = f & 0x0001 ? 4 : 2
|
|
258
|
+
if (f & 0x0008) args += 2
|
|
259
|
+
else if (f & 0x0040) args += 4
|
|
260
|
+
else if (f & 0x0080) args += 8
|
|
261
|
+
composites.bytes(args)
|
|
262
|
+
if (f & 0x0100) withInstructions = true
|
|
263
|
+
more = !!(f & 0x0020)
|
|
264
|
+
}
|
|
265
|
+
const records = data.subarray(start, composites.at)
|
|
266
|
+
const xMin = bboxes.i16()
|
|
267
|
+
const yMin = bboxes.i16()
|
|
268
|
+
const xMax = bboxes.i16()
|
|
269
|
+
const yMax = bboxes.i16()
|
|
270
|
+
xMins[g] = xMin
|
|
271
|
+
out.u16(0xffff)
|
|
272
|
+
out.u16(xMin); out.u16(yMin); out.u16(xMax); out.u16(yMax)
|
|
273
|
+
out.put(records)
|
|
274
|
+
if (withInstructions) {
|
|
275
|
+
const instructionLength = glyphs.u255()
|
|
276
|
+
out.u16(instructionLength)
|
|
277
|
+
out.put(instructions.bytes(instructionLength))
|
|
278
|
+
}
|
|
279
|
+
out.pad(4)
|
|
280
|
+
}
|
|
281
|
+
offsets[numGlyphs] = out.n
|
|
282
|
+
|
|
283
|
+
const glyf = out.done().slice()
|
|
284
|
+
const loca = new Sink((numGlyphs + 1) * (indexFormat ? 4 : 2))
|
|
285
|
+
for (let g = 0; g <= numGlyphs; g++) {
|
|
286
|
+
if (indexFormat) loca.u32(offsets[g])
|
|
287
|
+
else {
|
|
288
|
+
if (offsets[g] > 0x1fffe) fail('a short loca for a glyf table that is too large for it')
|
|
289
|
+
loca.u16(offsets[g] >> 1)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return { glyf, loca: loca.done().slice(), indexFormat, numGlyphs, xMins }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** `hmtx` back from the transformed table: the left side bearings it dropped are the glyphs' xMin (section 5.4). */
|
|
296
|
+
function rebuildHmtx (data, numGlyphs, numHMetrics, xMins) {
|
|
297
|
+
const r = new Reader(data)
|
|
298
|
+
const flags = r.u8()
|
|
299
|
+
if (flags & 0xfc) fail('an hmtx transform with reserved flag bits set')
|
|
300
|
+
const proportionalFromGlyf = !!(flags & 1)
|
|
301
|
+
const monospaceFromGlyf = !!(flags & 2)
|
|
302
|
+
if (!proportionalFromGlyf && !monospaceFromGlyf) fail('an hmtx transform that transforms nothing')
|
|
303
|
+
if (numHMetrics < 1 || numHMetrics > numGlyphs) fail('an hhea that counts more metrics than there are glyphs')
|
|
304
|
+
const advances = new Uint16Array(numHMetrics)
|
|
305
|
+
for (let i = 0; i < numHMetrics; i++) advances[i] = r.u16()
|
|
306
|
+
const out = new Sink(numHMetrics * 4 + (numGlyphs - numHMetrics) * 2)
|
|
307
|
+
const lsb = new Int16Array(numGlyphs)
|
|
308
|
+
for (let g = 0; g < numHMetrics; g++) lsb[g] = proportionalFromGlyf ? xMins[g] : r.i16()
|
|
309
|
+
for (let g = numHMetrics; g < numGlyphs; g++) lsb[g] = monospaceFromGlyf ? xMins[g] : r.i16()
|
|
310
|
+
for (let g = 0; g < numHMetrics; g++) { out.u16(advances[g]); out.u16(lsb[g]) }
|
|
311
|
+
for (let g = numHMetrics; g < numGlyphs; g++) out.u16(lsb[g])
|
|
312
|
+
return out.done().slice()
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** The table checksum of the OpenType spec: big-endian uint32 words, zero-padded, summed mod 2^32. */
|
|
316
|
+
function checksum (bytes) {
|
|
317
|
+
let sum = 0
|
|
318
|
+
const whole = bytes.length & ~3
|
|
319
|
+
for (let i = 0; i < whole; i += 4) {
|
|
320
|
+
sum = (sum + (((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]) >>> 0)) >>> 0
|
|
321
|
+
}
|
|
322
|
+
if (whole < bytes.length) {
|
|
323
|
+
let last = 0
|
|
324
|
+
for (let i = whole; i < bytes.length; i++) last |= bytes[i] << (24 - 8 * (i - whole))
|
|
325
|
+
sum = (sum + (last >>> 0)) >>> 0
|
|
326
|
+
}
|
|
327
|
+
return sum
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const tagBytes = (tag) => [tag.charCodeAt(0), tag.charCodeAt(1), tag.charCodeAt(2), tag.charCodeAt(3)]
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* @param {Uint8Array} bytes a WOFF2 file
|
|
334
|
+
* @param {object} [options]
|
|
335
|
+
* @param {(input: Uint8Array, options: object) => Promise<Uint8Array>} [options.decode]
|
|
336
|
+
* the Brotli decoder to use; `brotli.js`'s by default
|
|
337
|
+
* @returns {Promise<{sfnt: Uint8Array}|{error: string}>} the same shape `sfntFromBytes` answers with
|
|
338
|
+
*/
|
|
339
|
+
export async function woff2ToSfnt (bytes, { decode = brotliDecode } = {}) {
|
|
340
|
+
try {
|
|
341
|
+
const r = new Reader(bytes)
|
|
342
|
+
if (r.u32() !== 0x774f4632) return { error: 'not a WOFF2 file' }
|
|
343
|
+
const flavor = r.u32()
|
|
344
|
+
r.u32() // length
|
|
345
|
+
const numTables = r.u16()
|
|
346
|
+
r.u16() // reserved
|
|
347
|
+
r.u32() // totalSfntSize: a hint, and not one to allocate by
|
|
348
|
+
const compressedSize = r.u32()
|
|
349
|
+
r.bytes(24) // version, metadata and private blocks: nothing a renderer reads
|
|
350
|
+
if (flavor === 0x74746366) {
|
|
351
|
+
return { error: 'a WOFF2 font collection holds several faces behind shared tables; embedding it would leave the face choice to the viewer' }
|
|
352
|
+
}
|
|
353
|
+
if (!numTables || numTables > 512) return { error: 'a WOFF2 header that declares an implausible table count' }
|
|
354
|
+
|
|
355
|
+
const tables = []
|
|
356
|
+
let total = 0
|
|
357
|
+
for (let i = 0; i < numTables; i++) {
|
|
358
|
+
const flags = r.u8()
|
|
359
|
+
const index = flags & 0x3f
|
|
360
|
+
const tag = index === 63 ? String.fromCharCode(...r.bytes(4)) : KNOWN_TAGS[index]
|
|
361
|
+
const version = flags >> 6
|
|
362
|
+
const origLength = r.base128()
|
|
363
|
+
// glyf and loca are transformed at version 0 and left alone at 3; every other table the other way round.
|
|
364
|
+
const transformed = tag === 'glyf' || tag === 'loca' ? version === 0 : version !== 0
|
|
365
|
+
const length = transformed ? r.base128() : origLength
|
|
366
|
+
if (tag === 'loca' && transformed && length !== 0) fail('a transformed loca that carries data')
|
|
367
|
+
tables.push({ tag, transformed, origLength, length, offset: total, data: null })
|
|
368
|
+
total += length
|
|
369
|
+
}
|
|
370
|
+
if (r.at + compressedSize > bytes.length) return { error: 'a WOFF2 whose compressed data runs past the file' }
|
|
371
|
+
const data = await decode(bytes.subarray(r.at, r.at + compressedSize), { sizeHint: total })
|
|
372
|
+
if (data.length !== total) return { error: `a WOFF2 that decompressed to ${data.length} bytes where its directory promises ${total}` }
|
|
373
|
+
|
|
374
|
+
const by = new Map()
|
|
375
|
+
for (const t of tables) {
|
|
376
|
+
if (by.has(t.tag)) return { error: `a WOFF2 that declares the table "${t.tag}" twice` }
|
|
377
|
+
t.data = data.subarray(t.offset, t.offset + t.length)
|
|
378
|
+
by.set(t.tag, t)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const glyf = by.get('glyf')
|
|
382
|
+
const loca = by.get('loca')
|
|
383
|
+
let rebuilt = null
|
|
384
|
+
if (glyf && glyf.transformed) {
|
|
385
|
+
if (!loca || !loca.transformed) return { error: 'a WOFF2 with a transformed glyf and no transformed loca' }
|
|
386
|
+
rebuilt = rebuildGlyf(glyf.data)
|
|
387
|
+
glyf.data = rebuilt.glyf
|
|
388
|
+
loca.data = rebuilt.loca
|
|
389
|
+
// The format the offsets were just written in is the one `head` has to announce.
|
|
390
|
+
const head = by.get('head')
|
|
391
|
+
if (head && head.data.length >= 52) {
|
|
392
|
+
head.data = head.data.slice()
|
|
393
|
+
head.data[50] = 0
|
|
394
|
+
head.data[51] = rebuilt.indexFormat ? 1 : 0
|
|
395
|
+
}
|
|
396
|
+
} else if ((glyf && !loca) || (loca && !glyf)) {
|
|
397
|
+
return { error: 'a WOFF2 with only one of glyf and loca' }
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const hmtx = by.get('hmtx')
|
|
401
|
+
if (hmtx && hmtx.transformed) {
|
|
402
|
+
const hhea = by.get('hhea')
|
|
403
|
+
if (!rebuilt || !hhea || hhea.data.length < 36) return { error: 'a WOFF2 whose hmtx depends on outlines it does not carry' }
|
|
404
|
+
const numHMetrics = (hhea.data[34] << 8) | hhea.data[35]
|
|
405
|
+
hmtx.data = rebuildHmtx(hmtx.data, rebuilt.numGlyphs, numHMetrics, rebuilt.xMins)
|
|
406
|
+
}
|
|
407
|
+
for (const t of tables) {
|
|
408
|
+
if (t.transformed && t.tag !== 'glyf' && t.tag !== 'loca' && t.tag !== 'hmtx') {
|
|
409
|
+
return { error: `a WOFF2 that transforms the table "${t.tag}", which this reader has no inverse for` }
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ——— the sfnt: directory sorted by tag, tables on four-byte boundaries ———
|
|
414
|
+
const sorted = tables.slice().sort((a, b) => (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0))
|
|
415
|
+
const head = by.get('head')
|
|
416
|
+
if (head) {
|
|
417
|
+
// checkSumAdjustment is computed over a file in which it is zero.
|
|
418
|
+
if (head.data.length < 12) return { error: 'a WOFF2 whose head table is too short to be one' }
|
|
419
|
+
head.data = head.data.slice()
|
|
420
|
+
head.data[8] = head.data[9] = head.data[10] = head.data[11] = 0
|
|
421
|
+
}
|
|
422
|
+
let entropy = 0
|
|
423
|
+
while ((1 << (entropy + 1)) <= numTables) entropy++
|
|
424
|
+
const searchRange = (1 << entropy) * 16
|
|
425
|
+
const out = new Sink(12 + numTables * 16 + sorted.reduce((n, t) => n + t.data.length + 4, 0))
|
|
426
|
+
out.u32(flavor)
|
|
427
|
+
out.u16(numTables)
|
|
428
|
+
out.u16(searchRange)
|
|
429
|
+
out.u16(entropy)
|
|
430
|
+
out.u16(numTables * 16 - searchRange)
|
|
431
|
+
let offset = 12 + numTables * 16
|
|
432
|
+
for (const t of sorted) {
|
|
433
|
+
out.put(tagBytes(t.tag))
|
|
434
|
+
out.u32(checksum(t.data))
|
|
435
|
+
out.u32(offset)
|
|
436
|
+
out.u32(t.data.length)
|
|
437
|
+
t.at = offset
|
|
438
|
+
offset += (t.data.length + 3) & ~3
|
|
439
|
+
}
|
|
440
|
+
for (const t of sorted) { out.put(t.data); out.pad(4) }
|
|
441
|
+
const sfnt = out.done().slice()
|
|
442
|
+
if (head) {
|
|
443
|
+
const adjust = (0xb1b0afba - checksum(sfnt)) >>> 0
|
|
444
|
+
sfnt[head.at + 8] = (adjust >>> 24) & 0xff
|
|
445
|
+
sfnt[head.at + 9] = (adjust >>> 16) & 0xff
|
|
446
|
+
sfnt[head.at + 10] = (adjust >>> 8) & 0xff
|
|
447
|
+
sfnt[head.at + 11] = adjust & 0xff
|
|
448
|
+
}
|
|
449
|
+
return { sfnt }
|
|
450
|
+
} catch (error) {
|
|
451
|
+
return { error: `the WOFF2 could not be rebuilt: ${error && error.message ? error.message : String(error)}` }
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export default woff2ToSfnt
|