-
Notifications
You must be signed in to change notification settings - Fork 467
/
sfnt.js
413 lines (353 loc) · 14.4 KB
/
sfnt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// The `sfnt` wrapper provides organization for the tables in the font.
// It is the top-level data structure in a font.
// https://www.microsoft.com/typography/OTSPEC/otff.htm
// Recommendations for creating OpenType Fonts:
// http://www.microsoft.com/typography/otspec140/recom.htm
import check from '../check.js';
import table from '../table.js';
import cmap from './cmap.js';
import cff from './cff.js';
import head from './head.js';
import hhea from './hhea.js';
import hmtx from './hmtx.js';
import ltag from './ltag.js';
import maxp from './maxp.js';
import _name from './name.js';
import os2 from './os2.js';
import post from './post.js';
import gsub from './gsub.js';
import meta from './meta.js';
import colr from './colr.js';
import cpal from './cpal.js';
import fvar from './fvar.js';
import stat from './stat.js';
import avar from './avar.js';
import gasp from './gasp.js';
function log2(v) {
return Math.log(v) / Math.log(2) | 0;
}
function computeCheckSum(bytes) {
while (bytes.length % 4 !== 0) {
bytes.push(0);
}
let sum = 0;
for (let i = 0; i < bytes.length; i += 4) {
sum += (bytes[i] << 24) +
(bytes[i + 1] << 16) +
(bytes[i + 2] << 8) +
(bytes[i + 3]);
}
sum %= Math.pow(2, 32);
return sum;
}
function makeTableRecord(tag, checkSum, offset, length) {
return new table.Record('Table Record', [
{name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''},
{name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0},
{name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0},
{name: 'length', type: 'ULONG', value: length !== undefined ? length : 0}
]);
}
function makeSfntTable(tables) {
const sfnt = new table.Table('sfnt', [
{name: 'version', type: 'TAG', value: 'OTTO'},
{name: 'numTables', type: 'USHORT', value: 0},
{name: 'searchRange', type: 'USHORT', value: 0},
{name: 'entrySelector', type: 'USHORT', value: 0},
{name: 'rangeShift', type: 'USHORT', value: 0}
]);
sfnt.tables = tables;
sfnt.numTables = tables.length;
const highestPowerOf2 = Math.pow(2, log2(sfnt.numTables));
sfnt.searchRange = 16 * highestPowerOf2;
sfnt.entrySelector = log2(highestPowerOf2);
sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange;
const recordFields = [];
const tableFields = [];
let offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables);
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({name: 'padding', type: 'BYTE', value: 0});
}
for (let i = 0; i < tables.length; i += 1) {
const t = tables[i];
check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.');
const tableLength = t.sizeOf();
const tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength);
recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord});
tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t});
offset += tableLength;
check.argument(!isNaN(offset), 'Something went wrong calculating the offset.');
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({name: 'padding', type: 'BYTE', value: 0});
}
}
// Table records need to be sorted alphabetically.
recordFields.sort(function(r1, r2) {
if (r1.value.tag > r2.value.tag) {
return 1;
} else {
return -1;
}
});
sfnt.fields = sfnt.fields.concat(recordFields);
sfnt.fields = sfnt.fields.concat(tableFields);
return sfnt;
}
// Get the metrics for a character. If the string has more than one character
// this function returns metrics for the first available character.
// You can provide optional fallback metrics if no characters are available.
function metricsForChar(font, chars, notFoundMetrics) {
for (let i = 0; i < chars.length; i += 1) {
const glyphIndex = font.charToGlyphIndex(chars[i]);
if (glyphIndex > 0) {
const glyph = font.glyphs.get(glyphIndex);
return glyph.getMetrics();
}
}
return notFoundMetrics;
}
function average(vs) {
let sum = 0;
for (let i = 0; i < vs.length; i += 1) {
sum += vs[i];
}
return sum / vs.length;
}
// Convert the font object to a SFNT data structure.
// This structure contains all the necessary tables and metadata to create a binary OTF file.
function fontToSfntTable(font) {
const xMins = [];
const yMins = [];
const xMaxs = [];
const yMaxs = [];
const advanceWidths = [];
const leftSideBearings = [];
const rightSideBearings = [];
let firstCharIndex;
let lastCharIndex = 0;
let ulUnicodeRange1 = 0;
let ulUnicodeRange2 = 0;
let ulUnicodeRange3 = 0;
let ulUnicodeRange4 = 0;
for (let i = 0; i < font.glyphs.length; i += 1) {
const glyph = font.glyphs.get(i);
const unicode = glyph.unicode | 0;
if (isNaN(glyph.advanceWidth)) {
throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.');
}
if (firstCharIndex > unicode || firstCharIndex === undefined) {
// ignore .notdef char
if (unicode > 0) {
firstCharIndex = unicode;
}
}
if (lastCharIndex < unicode) {
lastCharIndex = unicode;
}
const position = os2.getUnicodeRange(unicode);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << position - 32;
} else if (position < 96) {
ulUnicodeRange3 |= 1 << position - 64;
} else if (position < 123) {
ulUnicodeRange4 |= 1 << position - 96;
} else {
throw new Error('Unicode ranges bits > 123 are reserved for internal usage');
}
// Skip non-important characters.
if (glyph.name === '.notdef') continue;
const metrics = glyph.getMetrics();
xMins.push(metrics.xMin);
yMins.push(metrics.yMin);
xMaxs.push(metrics.xMax);
yMaxs.push(metrics.yMax);
leftSideBearings.push(metrics.leftSideBearing);
rightSideBearings.push(metrics.rightSideBearing);
advanceWidths.push(glyph.advanceWidth);
}
const globals = {
xMin: Math.min.apply(null, xMins),
yMin: Math.min.apply(null, yMins),
xMax: Math.max.apply(null, xMaxs),
yMax: Math.max.apply(null, yMaxs),
advanceWidthMax: Math.max.apply(null, advanceWidths),
advanceWidthAvg: average(advanceWidths),
minLeftSideBearing: Math.min.apply(null, leftSideBearings),
maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
minRightSideBearing: Math.min.apply(null, rightSideBearings)
};
globals.ascender = font.ascender;
globals.descender = font.descender;
// macStyle bits must agree with the fsSelection bits
let macStyle = 0;
if (font.weightClass >= 600) {
macStyle |= font.macStyleValues.BOLD;
}
if (font.italicAngle < 0) {
macStyle |= font.macStyleValues.ITALIC;
}
const headTable = head.make({
flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
unitsPerEm: font.unitsPerEm,
xMin: globals.xMin,
yMin: globals.yMin,
xMax: globals.xMax,
yMax: globals.yMax,
lowestRecPPEM: 3,
macStyle: macStyle,
createdTimestamp: font.createdTimestamp
});
const hheaTable = hhea.make({
ascender: globals.ascender,
descender: globals.descender,
advanceWidthMax: globals.advanceWidthMax,
minLeftSideBearing: globals.minLeftSideBearing,
minRightSideBearing: globals.minRightSideBearing,
xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
numberOfHMetrics: font.glyphs.length,
});
const maxpTable = maxp.make(font.glyphs.length);
const os2Table = os2.make(Object.assign({
xAvgCharWidth: Math.round(globals.advanceWidthAvg),
usFirstCharIndex: firstCharIndex,
usLastCharIndex: lastCharIndex,
ulUnicodeRange1: ulUnicodeRange1,
ulUnicodeRange2: ulUnicodeRange2,
ulUnicodeRange3: ulUnicodeRange3,
ulUnicodeRange4: ulUnicodeRange4,
// See http://typophile.com/node/13081 for more info on vertical metrics.
// We get metrics for typical characters (such as "x" for xHeight).
// We provide some fallback characters if characters are unavailable: their
// ordering was chosen experimentally.
sTypoAscender: globals.ascender,
sTypoDescender: globals.descender,
sTypoLineGap: 0,
usWinAscent: globals.yMax,
usWinDescent: Math.abs(globals.yMin),
ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now
sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax,
sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax,
usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.
usBreakChar: font.hasChar(' ') ? 32 : 0, // Use space as the break character, if available.
}, font.tables.os2));
const hmtxTable = hmtx.make(font.glyphs);
const cmapTable = cmap.make(font.glyphs);
const englishFamilyName = font.getEnglishName('fontFamily');
const englishStyleName = font.getEnglishName('fontSubfamily');
const englishFullName = englishFamilyName + ' ' + englishStyleName;
let postScriptName = font.getEnglishName('postScriptName');
if (!postScriptName) {
postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName;
}
const names = {};
for (let n in font.names) {
names[n] = font.names[n];
}
names.unicode = names.unicode || {};
names.macintosh = names.macintosh || {};
names.windows = names.windows || {};
const fontNamesUnicode = font.names.unicode || {};
const fontNamesMacintosh = font.names.macintosh || {};
const fontNamesWindows = font.names.windows || {};
// do this as a loop to reduce redundant code
for (const platform in ['unicode', 'macintosh', 'windows']) {
names[platform] = names[platform] || {};
if (!names[platform].uniqueID) {
names.unicode.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName};
}
if (!names[platform].postScriptName) {
names.unicode.postScriptName = {en: postScriptName};
}
}
// this cannot be done as a loop as each one is unique.
if (!names.unicode.preferredFamily) {
names.unicode.preferredFamily = fontNamesUnicode.fontFamily || fontNamesMacintosh.fontFamily || fontNamesWindows.fontFamily;
}
if (!names.macintosh.preferredFamily) {
names.macintosh.preferredFamily = fontNamesMacintosh.fontFamily || fontNamesUnicode.fontFamily || fontNamesWindows.fontFamily;
}
if (!names.windows.preferredFamily) {
names.windows.preferredFamily = fontNamesWindows.fontFamily || fontNamesUnicode.fontFamily || fontNamesMacintosh.fontFamily;
}
if (!names.unicode.preferredSubfamily) {
names.unicode.preferredSubfamily = fontNamesUnicode.fontSubfamily || fontNamesMacintosh.fontSubfamily || fontNamesWindows.fontSubfamily;
}
if (!names.macintosh.preferredSubfamily) {
names.macintosh.preferredSubfamily = fontNamesMacintosh.fontSubfamily || fontNamesUnicode.fontSubfamily || fontNamesWindows.fontSubfamily;
}
if (!names.windows.preferredSubfamily) {
names.windows.preferredSubfamily = fontNamesWindows.fontSubfamily || fontNamesUnicode.fontSubfamily || fontNamesMacintosh.fontSubfamily;
}
// we have to handle fvar before name, because it may modify name IDs
const fvarTable = font.tables.fvar ? fvar.make(font.tables.fvar, font.names) : undefined;
const gaspTable = font.tables.gasp ? gasp.make(font.tables.gasp) : undefined;
const languageTags = [];
const nameTable = _name.make(names, languageTags);
const ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined);
const postTable = post.make(font);
const cffTable = cff.make(font.glyphs, {
version: font.getEnglishName('version'),
fullName: englishFullName,
familyName: englishFamilyName,
weightName: englishStyleName,
postScriptName: postScriptName,
unitsPerEm: font.unitsPerEm,
fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax],
topDict: font.tables.cff && font.tables.cff.topDict || {}
});
const metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined;
// The order does not matter because makeSfntTable() will sort them.
const tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable];
if (ltagTable) {
tables.push(ltagTable);
}
// Optional tables
const optionalTables = {
gsub,
cpal,
colr,
stat,
avar
};
const optionalTableArgs = {
avar: [font.tables.fvar]
};
// fvar table is already handled above
if (fvarTable) {
tables.push(fvarTable);
}
for (let tableName in optionalTables) {
const table = font.tables[tableName];
if (table) {
tables.push(optionalTables[tableName].make.call(font, table, ...(optionalTableArgs[tableName] || [])));
}
}
if (metaTable) {
tables.push(metaTable);
}
if (gaspTable) {
tables.push(gaspTable);
}
const sfntTable = makeSfntTable(tables);
// Compute the font's checkSum and store it in head.checkSumAdjustment.
const bytes = sfntTable.encode();
const checkSum = computeCheckSum(bytes);
const tableFields = sfntTable.fields;
let checkSumAdjusted = false;
for (let i = 0; i < tableFields.length; i += 1) {
if (tableFields[i].name === 'head table') {
tableFields[i].value.checkSumAdjustment = 0xB1B0AFBA - checkSum;
checkSumAdjusted = true;
break;
}
}
if (!checkSumAdjusted) {
throw new Error('Could not find head table with checkSum to adjust.');
}
return sfntTable;
}
export default { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum };