harmonink 0.0.0-stage → 0.1.0
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/README.md +116 -2
- package/bin/cli.js +60 -0
- package/package.json +138 -4
- package/src/css.js +39 -0
- package/src/glyf.js +206 -0
- package/src/gvar.js +175 -0
- package/src/index.js +3 -0
- package/src/letters.js +12 -0
- package/src/live.js +137 -0
- package/src/measure.js +225 -0
- package/src/normalize.js +171 -0
- package/src/outline.js +74 -0
- package/src/sfnt.js +97 -0
package/src/gvar.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Reader } from './sfnt.js';
|
|
2
|
+
|
|
3
|
+
const clamp = (lo, v, hi) => Math.min(hi, Math.max(lo, v));
|
|
4
|
+
const tuple = (r, n) => Array.from({ length: n }, () => r.i16() / 16384);
|
|
5
|
+
|
|
6
|
+
function readAxes(fvar) {
|
|
7
|
+
const h = new Reader(fvar, 4);
|
|
8
|
+
const off = h.u16(); h.u16();
|
|
9
|
+
const count = h.u16(), size = h.u16();
|
|
10
|
+
const axes = [];
|
|
11
|
+
for (let i = 0; i < count; i++) {
|
|
12
|
+
const a = new Reader(fvar, off + i * size);
|
|
13
|
+
axes.push({ tag: a.tag(), min: (a.u32() | 0) / 65536, def: (a.u32() | 0) / 65536, max: (a.u32() | 0) / 65536 });
|
|
14
|
+
}
|
|
15
|
+
return axes;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// avar bends each axis's -1..1 position through a piecewise-linear map
|
|
19
|
+
function applyAvar(avar, coords) {
|
|
20
|
+
if (new Reader(avar, 0).u16() !== 1) return;
|
|
21
|
+
const r = new Reader(avar, 6);
|
|
22
|
+
const axisCount = r.u16();
|
|
23
|
+
for (let i = 0; i < axisCount && i < coords.length; i++) {
|
|
24
|
+
const pairs = Array.from({ length: r.u16() }, () => [r.i16() / 16384, r.i16() / 16384]);
|
|
25
|
+
const c = coords[i];
|
|
26
|
+
for (let k = 1; k < pairs.length; k++) {
|
|
27
|
+
const [f0, t0] = pairs[k - 1], [f1, t1] = pairs[k];
|
|
28
|
+
if (c > f1) continue;
|
|
29
|
+
coords[i] = f1 === f0 ? t1 : t0 + (t1 - t0) * (c - f0) / (f1 - f0);
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// how much of one tuple's deltas applies at this position; 0 when outside its region
|
|
36
|
+
function scalar(coords, peak, lo, hi) {
|
|
37
|
+
let s = 1;
|
|
38
|
+
for (let i = 0; i < peak.length; i++) {
|
|
39
|
+
const p = peak[i], c = coords[i];
|
|
40
|
+
if (p === 0) continue;
|
|
41
|
+
if (c === 0) return 0;
|
|
42
|
+
if (lo) {
|
|
43
|
+
if (c < lo[i] || c > hi[i]) return 0;
|
|
44
|
+
if (c !== p) s *= c < p ? (c - lo[i]) / (p - lo[i]) : (hi[i] - c) / (hi[i] - p);
|
|
45
|
+
} else {
|
|
46
|
+
if (c < Math.min(0, p) || c > Math.max(0, p)) return 0;
|
|
47
|
+
s *= c / p;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// null means every point, phantom points included
|
|
54
|
+
function packedPoints(r) {
|
|
55
|
+
let count = r.u8();
|
|
56
|
+
if (count === 0) return null;
|
|
57
|
+
if (count & 0x80) count = ((count & 0x7f) << 8) | r.u8();
|
|
58
|
+
const pts = [];
|
|
59
|
+
let p = 0;
|
|
60
|
+
while (pts.length < count) {
|
|
61
|
+
const c = r.u8(), run = (c & 0x7f) + 1;
|
|
62
|
+
for (let i = 0; i < run && pts.length < count; i++) { p += c & 0x80 ? r.u16() : r.u8(); pts.push(p); }
|
|
63
|
+
}
|
|
64
|
+
return pts;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function packedDeltas(r, count) {
|
|
68
|
+
const out = [];
|
|
69
|
+
while (out.length < count) {
|
|
70
|
+
const c = r.u8(), run = (c & 0x3f) + 1;
|
|
71
|
+
for (let i = 0; i < run; i++) out.push(c & 0x80 ? 0 : c & 0x40 ? r.i16() : r.i8());
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function infer(p, ca, cb, da, db) {
|
|
77
|
+
if (ca === cb) return da === db ? da : 0;
|
|
78
|
+
if (ca > cb) [ca, cb, da, db] = [cb, ca, db, da];
|
|
79
|
+
if (p <= ca) return da;
|
|
80
|
+
if (p >= cb) return db;
|
|
81
|
+
return da + (db - da) * (p - ca) / (cb - ca);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// points a tuple leaves out move with their nearest listed neighbours on the same contour
|
|
85
|
+
function inferUntouched(contours, tx, ty, touched) {
|
|
86
|
+
let base = 0;
|
|
87
|
+
for (const c of contours) {
|
|
88
|
+
const n = c.length, hit = [];
|
|
89
|
+
for (let i = 0; i < n; i++) if (touched[base + i]) hit.push(i);
|
|
90
|
+
if (hit.length && hit.length < n) {
|
|
91
|
+
for (let h = 0; h < hit.length; h++) {
|
|
92
|
+
const a = hit[h], b = hit[(h + 1) % hit.length];
|
|
93
|
+
for (let i = (a + 1) % n; i !== b; i = (i + 1) % n) {
|
|
94
|
+
tx[base + i] = infer(c[i].x, c[a].x, c[b].x, tx[base + a], tx[base + b]);
|
|
95
|
+
ty[base + i] = infer(c[i].y, c[a].y, c[b].y, ty[base + a], ty[base + b]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
base += n;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function glyphDeltas(gvar, start, axisCount, shared, coords, gl, n) {
|
|
104
|
+
const r = new Reader(gvar, start);
|
|
105
|
+
const tvc = r.u16(), dataOff = r.u16();
|
|
106
|
+
const total = n + 4;
|
|
107
|
+
const dx = new Float64Array(total), dy = new Float64Array(total);
|
|
108
|
+
const data = new Reader(gvar, start + dataOff);
|
|
109
|
+
const sharedPts = tvc & 0x8000 ? packedPoints(data) : null;
|
|
110
|
+
let pos = data.p;
|
|
111
|
+
for (let t = 0; t < (tvc & 0x0fff); t++) {
|
|
112
|
+
const size = r.u16(), idx = r.u16();
|
|
113
|
+
const peak = idx & 0x8000 ? tuple(r, axisCount) : shared[idx & 0x0fff];
|
|
114
|
+
const lo = idx & 0x4000 ? tuple(r, axisCount) : null;
|
|
115
|
+
const hi = idx & 0x4000 ? tuple(r, axisCount) : null;
|
|
116
|
+
const d = new Reader(gvar, pos);
|
|
117
|
+
pos += size;
|
|
118
|
+
const s = peak ? scalar(coords, peak, lo, hi) : 0;
|
|
119
|
+
if (!s) continue;
|
|
120
|
+
const pts = idx & 0x2000 ? packedPoints(d) : sharedPts;
|
|
121
|
+
const count = pts ? pts.length : total;
|
|
122
|
+
const xs = packedDeltas(d, count), ys = packedDeltas(d, count);
|
|
123
|
+
if (!pts) {
|
|
124
|
+
for (let i = 0; i < total; i++) { dx[i] += s * xs[i]; dy[i] += s * ys[i]; }
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const tx = new Float64Array(total), ty = new Float64Array(total), touched = new Uint8Array(total);
|
|
128
|
+
pts.forEach((p, i) => { if (p < total) { tx[p] = xs[i]; ty[p] = ys[i]; touched[p] = 1; } });
|
|
129
|
+
if (!gl.composite) inferUntouched(gl.contours, tx, ty, touched);
|
|
130
|
+
for (let i = 0; i < total; i++) { dx[i] += s * tx[i]; dy[i] += s * ty[i]; }
|
|
131
|
+
}
|
|
132
|
+
return { dx, dy };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// shortcut: every glyph is instanced, not only the letters measured; make it lazy if huge fonts get slow
|
|
136
|
+
function applyGvar(gvar, glyphs, coords) {
|
|
137
|
+
const h = new Reader(gvar, 4);
|
|
138
|
+
const axisCount = h.u16(), sharedCount = h.u16(), sharedOff = h.u32();
|
|
139
|
+
const glyphCount = h.u16(), flags = h.u16(), dataOff = h.u32();
|
|
140
|
+
const offs = Array.from({ length: glyphCount + 1 }, () => (flags & 1 ? h.u32() : h.u16() * 2));
|
|
141
|
+
const sr = new Reader(gvar, sharedOff);
|
|
142
|
+
const shared = Array.from({ length: sharedCount }, () => tuple(sr, axisCount));
|
|
143
|
+
const advDelta = new Array(glyphs.length).fill(0);
|
|
144
|
+
for (let g = 0; g < glyphCount && g < glyphs.length; g++) {
|
|
145
|
+
const gl = glyphs[g];
|
|
146
|
+
if (!gl || offs[g] === offs[g + 1]) continue;
|
|
147
|
+
// a composite's "points" are its components' offsets; either way four phantom points follow
|
|
148
|
+
const pts = gl.composite ? gl.comps : gl.contours.flat();
|
|
149
|
+
const n = pts.length;
|
|
150
|
+
const { dx, dy } = glyphDeltas(gvar, dataOff + offs[g], axisCount, shared, coords, gl, n);
|
|
151
|
+
// rounded per point, the way a static instance of the family is cut
|
|
152
|
+
for (let i = 0; i < n; i++) {
|
|
153
|
+
if (gl.composite) { pts[i].dx += Math.round(dx[i]); pts[i].dy += Math.round(dy[i]); }
|
|
154
|
+
else { pts[i].x += Math.round(dx[i]); pts[i].y += Math.round(dy[i]); }
|
|
155
|
+
}
|
|
156
|
+
advDelta[g] = Math.round(dx[n + 1]) - Math.round(dx[n]);
|
|
157
|
+
}
|
|
158
|
+
return advDelta;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Moves the glyphs of a variable font to the asked weight, other axes left at their default.
|
|
162
|
+
// Call before composites are resolved. Returns the weight actually measured and each advance's change.
|
|
163
|
+
export function instantiate(tables, glyphs, weight) {
|
|
164
|
+
const axes = readAxes(tables.fvar);
|
|
165
|
+
const wi = axes.findIndex(a => a.tag === 'wght');
|
|
166
|
+
if (wi < 0) return { weightAxis: null, weightMeasured: null, advDelta: null };
|
|
167
|
+
const ax = axes[wi];
|
|
168
|
+
const weightAxis = [Math.round(ax.min), Math.round(ax.max)];
|
|
169
|
+
if (!tables.gvar) return { weightAxis, weightMeasured: ax.def, advDelta: null };
|
|
170
|
+
const w = clamp(ax.min, weight, ax.max);
|
|
171
|
+
const coords = axes.map((a, i) => i !== wi || w === a.def ? 0
|
|
172
|
+
: w < a.def ? (w - a.def) / (a.def - a.min) : (w - a.def) / (a.max - a.def));
|
|
173
|
+
if (tables.avar) applyAvar(tables.avar, coords);
|
|
174
|
+
return { weightAxis, weightMeasured: w, advDelta: coords[wi] === 0 ? null : applyGvar(tables.gvar, glyphs, coords) };
|
|
175
|
+
}
|
package/src/index.js
ADDED
package/src/letters.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// one copy for measure.js and live.js so they cannot drift; no imports, this ships to the browser
|
|
2
|
+
export const LOWER = 'abcdefghijklmnopqrstuvwxyz';
|
|
3
|
+
export const ASC = 'bdfhklt';
|
|
4
|
+
export const DESC = 'gjpqy';
|
|
5
|
+
export const FREQ = { a:8.17,b:1.49,c:2.78,d:4.25,e:12.70,f:2.23,g:2.02,h:6.09,i:6.97,j:0.15,
|
|
6
|
+
k:0.77,l:4.03,m:2.41,n:6.75,o:7.51,p:1.93,q:0.10,r:5.99,s:6.33,t:9.06,
|
|
7
|
+
u:2.76,v:0.98,w:2.36,x:0.15,y:1.97,z:0.07 };
|
|
8
|
+
export const BAND = [0.40, 0.50, 0.60];
|
|
9
|
+
// letterform regularity — flat or pointed tops, flat feet, and the tallest true ascender
|
|
10
|
+
export const FLAT_TOP = 'vwxz';
|
|
11
|
+
export const FLAT_FOOT = 'imnruvwxz';
|
|
12
|
+
export const ASC_LETTER = 'bdhkl';
|
package/src/live.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { LOWER, ASC, DESC, FREQ, BAND, FLAT_TOP, FLAT_FOOT, ASC_LETTER } from './letters.js';
|
|
2
|
+
|
|
3
|
+
const INK = 128;
|
|
4
|
+
|
|
5
|
+
export function measureLive(family, { em = 512, size, canvas } = {}) {
|
|
6
|
+
const unit = size ?? em;
|
|
7
|
+
const cv = canvas ?? document.createElement('canvas');
|
|
8
|
+
let ctx = cv.getContext('2d', { willReadFrequently: true });
|
|
9
|
+
ctx.font = `${unit}px "${family}"`;
|
|
10
|
+
const probe = ctx.measureText('x');
|
|
11
|
+
const need = Math.ceil(Math.max(probe.width * 3, unit * 2.5));
|
|
12
|
+
if (cv.width < need || cv.height < need) {
|
|
13
|
+
cv.width = need; cv.height = need;
|
|
14
|
+
ctx = cv.getContext('2d', { willReadFrequently: true });
|
|
15
|
+
}
|
|
16
|
+
ctx.font = `${unit}px "${family}"`;
|
|
17
|
+
ctx.textBaseline = 'alphabetic';
|
|
18
|
+
ctx.fillStyle = '#000';
|
|
19
|
+
|
|
20
|
+
// the reported box is quantised but always rounds outward, so it safely bounds the read region
|
|
21
|
+
function scan(ch) {
|
|
22
|
+
const m = ctx.measureText(ch);
|
|
23
|
+
const l = Math.ceil(m.actualBoundingBoxLeft) + 2;
|
|
24
|
+
const r = Math.ceil(m.actualBoundingBoxRight) + 2;
|
|
25
|
+
const a = Math.ceil(m.actualBoundingBoxAscent) + 2;
|
|
26
|
+
const d = Math.ceil(m.actualBoundingBoxDescent) + 2;
|
|
27
|
+
const w = l + r, h = a + d;
|
|
28
|
+
if (!(w > 0) || !(h > 0) || w > cv.width || h > cv.height) return null;
|
|
29
|
+
ctx.clearRect(0, 0, w, h);
|
|
30
|
+
ctx.fillText(ch, l, a);
|
|
31
|
+
const px = ctx.getImageData(0, 0, w, h).data;
|
|
32
|
+
let top = -1, bottom = -1, left = w, right = -1;
|
|
33
|
+
const rows = new Map();
|
|
34
|
+
for (let y = 0; y < h; y++) {
|
|
35
|
+
const o = y * w * 4;
|
|
36
|
+
let rl = -1, rr = -1;
|
|
37
|
+
for (let x = 0; x < w; x++) {
|
|
38
|
+
if (px[o + x * 4 + 3] >= INK) { if (rl < 0) rl = x; rr = x; }
|
|
39
|
+
}
|
|
40
|
+
if (rl >= 0) {
|
|
41
|
+
if (top < 0) top = y;
|
|
42
|
+
bottom = y;
|
|
43
|
+
if (rl < left) left = rl;
|
|
44
|
+
if (rr > right) right = rr;
|
|
45
|
+
rows.set(y, [rl - l, rr + 1 - l]);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (top < 0) return null;
|
|
49
|
+
return {
|
|
50
|
+
advance: m.width,
|
|
51
|
+
xMin: left - l, xMax: right + 1 - l,
|
|
52
|
+
yMax: a - top, yMin: a - (bottom + 1),
|
|
53
|
+
rowAt: yy => rows.get(a - yy) ?? null,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const xg = scan('x');
|
|
58
|
+
if (!xg) throw new Error(`no measurable "x" for ${family} — is the font loaded?`);
|
|
59
|
+
const xHeight = xg.yMax;
|
|
60
|
+
if (!(xHeight > 0)) throw new Error(`measured x-height is not positive for ${family}`);
|
|
61
|
+
|
|
62
|
+
const Hg = scan('H');
|
|
63
|
+
const capHeight = Hg ? Hg.yMax : null;
|
|
64
|
+
|
|
65
|
+
const ys = BAND.map(t => Math.round(xHeight * t));
|
|
66
|
+
let w = 0, advSum = 0, lsbBox = 0, rsbBox = 0, lsbStem = 0, rsbStem = 0, inked = 0, seen = 0;
|
|
67
|
+
let inkTop = capHeight ?? xHeight, inkBottom = 0;
|
|
68
|
+
const advances = [];
|
|
69
|
+
|
|
70
|
+
for (const ch of LOWER) {
|
|
71
|
+
const s = scan(ch);
|
|
72
|
+
if (!s || !(s.advance > 0)) continue;
|
|
73
|
+
seen++;
|
|
74
|
+
advances.push(s.advance);
|
|
75
|
+
if (ASC.includes(ch) && s.yMax > inkTop) inkTop = s.yMax;
|
|
76
|
+
if (DESC.includes(ch) && s.yMin < inkBottom) inkBottom = s.yMin;
|
|
77
|
+
const k = FREQ[ch];
|
|
78
|
+
w += k;
|
|
79
|
+
advSum += s.advance * k;
|
|
80
|
+
lsbBox += s.xMin * k;
|
|
81
|
+
rsbBox += (s.advance - s.xMax) * k;
|
|
82
|
+
inked += (s.xMax - s.xMin) * k;
|
|
83
|
+
const l = [], r = [];
|
|
84
|
+
for (const y of ys) {
|
|
85
|
+
const hit = s.rowAt(y);
|
|
86
|
+
if (hit) { l.push(hit[0]); r.push(hit[1]); }
|
|
87
|
+
}
|
|
88
|
+
if (l.length) {
|
|
89
|
+
lsbStem += (l.reduce((a, b) => a + b, 0) / l.length) * k;
|
|
90
|
+
rsbStem += (s.advance - r.reduce((a, b) => a + b, 0) / r.length) * k;
|
|
91
|
+
} else { lsbStem += s.xMin * k; rsbStem += (s.advance - s.xMax) * k; }
|
|
92
|
+
}
|
|
93
|
+
if (seen < 20) throw new Error(`only ${seen} of 26 Latin lowercase glyphs rendered for ${family}`);
|
|
94
|
+
|
|
95
|
+
const flatTops = [], flatFeet = [], ascTops = [];
|
|
96
|
+
for (const ch of FLAT_TOP) { const g = scan(ch); if (g) flatTops.push(g.yMax / xHeight); }
|
|
97
|
+
for (const ch of FLAT_FOOT) { const g = scan(ch); if (g) flatFeet.push(g.yMin / xHeight); }
|
|
98
|
+
for (const ch of ASC_LETTER) { const g = scan(ch); if (g) ascTops.push(g.yMax / xHeight); }
|
|
99
|
+
const spreadOf = a => a.length < 2 ? 0 : Math.max(...a) - Math.min(...a);
|
|
100
|
+
|
|
101
|
+
const stem = scan('l') ?? scan('i');
|
|
102
|
+
let stemWidth = null;
|
|
103
|
+
if (stem) {
|
|
104
|
+
const ws = [];
|
|
105
|
+
for (const t of [0.35, 0.5, 0.65]) {
|
|
106
|
+
const hit = stem.rowAt(Math.round(xHeight * t));
|
|
107
|
+
if (hit) ws.push(hit[1] - hit[0]);
|
|
108
|
+
}
|
|
109
|
+
if (ws.length) stemWidth = ws.reduce((a, b) => a + b, 0) / ws.length;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const monospace = advances.length > 5 && advances.every(a => Math.abs(a - advances[0]) < unit * 1e-3);
|
|
113
|
+
const round = (v, n = 4) => v == null ? null : Number(v.toFixed(n));
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
family,
|
|
117
|
+
unitsPerEm: unit,
|
|
118
|
+
xHeightRatio: round(xHeight / unit),
|
|
119
|
+
capHeightRatio: round(capHeight == null ? null : capHeight / unit),
|
|
120
|
+
ascenderRatio: round(inkTop / unit),
|
|
121
|
+
descenderRatio: round(-inkBottom / unit),
|
|
122
|
+
inkRatio: round((inkTop - inkBottom) / unit),
|
|
123
|
+
advanceX: round((advSum / w) / xHeight),
|
|
124
|
+
gapBox: round(((lsbBox + rsbBox) / w) / xHeight),
|
|
125
|
+
gapStem: round(((lsbStem + rsbStem) / w) / xHeight),
|
|
126
|
+
inkedX: round((inked / w) / xHeight),
|
|
127
|
+
stemX: round(stemWidth == null ? null : stemWidth / xHeight),
|
|
128
|
+
topSpread: round(spreadOf(flatTops)),
|
|
129
|
+
footSpread: round(spreadOf(flatFeet)),
|
|
130
|
+
ascLetterRatio: ascTops.length ? round(Math.max(...ascTops), 3) : null,
|
|
131
|
+
weightAxis: null,
|
|
132
|
+
weightMeasured: null,
|
|
133
|
+
monospace,
|
|
134
|
+
glyphsMeasured: seen,
|
|
135
|
+
approximate: true,
|
|
136
|
+
};
|
|
137
|
+
}
|
package/src/measure.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { readTables, Reader } from './sfnt.js';
|
|
2
|
+
import { decodeWoff2Glyf, parseSfntGlyf, resolveComposites } from './glyf.js';
|
|
3
|
+
import { pathOf, bounds, crossingsAt } from './outline.js';
|
|
4
|
+
import { instantiate } from './gvar.js';
|
|
5
|
+
import { LOWER, ASC, DESC, FREQ, BAND, FLAT_TOP, FLAT_FOOT, ASC_LETTER } from './letters.js';
|
|
6
|
+
|
|
7
|
+
function parseCmap(t) {
|
|
8
|
+
const r = new Reader(t, 2);
|
|
9
|
+
const n = r.u16();
|
|
10
|
+
let best = -1, bestScore = -1;
|
|
11
|
+
for (let i = 0; i < n; i++) {
|
|
12
|
+
const pid = r.u16(), eid = r.u16(), off = r.u32();
|
|
13
|
+
const score = pid === 3 && eid === 10 ? 5 : pid === 3 && eid === 1 ? 4 : pid === 0 ? 3 : pid === 3 ? 2 : 1;
|
|
14
|
+
if (score > bestScore) { bestScore = score; best = off; }
|
|
15
|
+
}
|
|
16
|
+
if (best < 0) return null;
|
|
17
|
+
const s = new Reader(t, best);
|
|
18
|
+
const fmt = s.u16();
|
|
19
|
+
const map = new Map();
|
|
20
|
+
if (fmt === 4) {
|
|
21
|
+
s.u16(); s.u16();
|
|
22
|
+
const segX2 = s.u16();
|
|
23
|
+
const seg = segX2 >> 1;
|
|
24
|
+
s.p += 6;
|
|
25
|
+
const end = [], start = [], delta = [], rangeOffPos = [], rangeOff = [];
|
|
26
|
+
for (let i = 0; i < seg; i++) end.push(s.u16());
|
|
27
|
+
s.u16();
|
|
28
|
+
for (let i = 0; i < seg; i++) start.push(s.u16());
|
|
29
|
+
for (let i = 0; i < seg; i++) delta.push(s.i16());
|
|
30
|
+
for (let i = 0; i < seg; i++) { rangeOffPos.push(s.p); rangeOff.push(s.u16()); }
|
|
31
|
+
for (let i = 0; i < seg; i++) {
|
|
32
|
+
for (let c = start[i]; c <= end[i] && c !== 0xffff; c++) {
|
|
33
|
+
let g;
|
|
34
|
+
if (rangeOff[i] === 0) g = (c + delta[i]) & 0xffff;
|
|
35
|
+
else {
|
|
36
|
+
const gi = rangeOffPos[i] + rangeOff[i] + (c - start[i]) * 2;
|
|
37
|
+
g = (t[gi] << 8) | t[gi + 1];
|
|
38
|
+
if (g) g = (g + delta[i]) & 0xffff;
|
|
39
|
+
}
|
|
40
|
+
if (g) map.set(c, g);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
} else if (fmt === 12) {
|
|
44
|
+
s.u16(); s.u32(); s.u32();
|
|
45
|
+
const groups = s.u32();
|
|
46
|
+
for (let i = 0; i < groups; i++) {
|
|
47
|
+
const a = s.u32(), b = s.u32(), g = s.u32();
|
|
48
|
+
for (let c = a; c <= b; c++) map.set(c, g + (c - a));
|
|
49
|
+
}
|
|
50
|
+
} else if (fmt === 6) {
|
|
51
|
+
s.u16(); s.u16();
|
|
52
|
+
const first = s.u16(), cnt = s.u16();
|
|
53
|
+
for (let i = 0; i < cnt; i++) map.set(first + i, s.u16());
|
|
54
|
+
}
|
|
55
|
+
return map;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const STYLE = 'thin|extra\\s?light|ultra\\s?light|light|regular|book|normal|medium|semi\\s?bold|demi\\s?bold|bold|extra\\s?bold|ultra\\s?bold|black|heavy|italic|oblique';
|
|
59
|
+
const STYLE_ANY = new RegExp(`\\s+(?:${STYLE})(?=\\s|$)`, 'gi');
|
|
60
|
+
const OPTICAL_ANY = /\s+\d+(?:\.\d+)?\s?pt(?=\s|$)/gi;
|
|
61
|
+
// separate non-global copy — a /g regex carries lastIndex between .test() calls
|
|
62
|
+
const HAS_OPTICAL = /\s+\d+(?:\.\d+)?\s?pt(?=\s|$)/i;
|
|
63
|
+
|
|
64
|
+
function parseName(t) {
|
|
65
|
+
if (!t) return null;
|
|
66
|
+
const r = new Reader(t, 2);
|
|
67
|
+
const count = r.u16(), storage = r.u16();
|
|
68
|
+
let family = null, pref = null;
|
|
69
|
+
for (let i = 0; i < count; i++) {
|
|
70
|
+
const pid = r.u16(); r.p += 4; // encoding and language ids
|
|
71
|
+
const nid = r.u16(), len = r.u16(), off = r.u16();
|
|
72
|
+
if (nid !== 1 && nid !== 16) continue;
|
|
73
|
+
const raw = t.subarray(storage + off, storage + off + len);
|
|
74
|
+
const s = pid === 3 || pid === 0 ? Buffer.from(raw).swap16().toString('utf16le') : raw.toString('latin1');
|
|
75
|
+
if (nid === 16) pref = s; else if (!family) family = s;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const raw = pref || family;
|
|
79
|
+
return raw ? { family: cleanFamily(raw), familyRaw: raw } : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Subsetters bake the instance name into nameID 1, and sometimes into 16 as well, so
|
|
83
|
+
// "Nunito Sans 12pt ExtraLight 12pt" reaches font-family. An optical-size token is the only
|
|
84
|
+
// unambiguous tell: no real family is called "… 16pt", so a style word beside one is noise.
|
|
85
|
+
//
|
|
86
|
+
// A bare trailing style word is NOT strippable — "Shadows Into Light" and "Archivo Black"
|
|
87
|
+
// are real family names with the same shape as a mangled "Figtree Light". Distinguishing
|
|
88
|
+
// them needs the vendor's family list, which is the caller's to hold; familyRaw is kept so
|
|
89
|
+
// nothing is lost, and `family` can be overridden on normalize().
|
|
90
|
+
function cleanFamily(raw) {
|
|
91
|
+
if (!HAS_OPTICAL.test(raw)) return raw;
|
|
92
|
+
const name = raw.replace(OPTICAL_ANY, ' ').replace(STYLE_ANY, ' ').replace(/\s{2,}/g, ' ').trim();
|
|
93
|
+
return name || raw;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function bboxOf(glyph) {
|
|
97
|
+
if (glyph.contours.length) return bounds(pathOf(glyph)) ?? glyph.bbox ?? null;
|
|
98
|
+
return glyph.bbox ?? null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function measure(buf, opts = {}) {
|
|
102
|
+
const { tables, container } = readTables(buf);
|
|
103
|
+
if (tables['CFF '] || tables['CFF2']) throw new Error('CFF/OTF outlines are not supported yet — use a TrueType-flavoured file');
|
|
104
|
+
if (!tables.glyf) throw new Error('no glyf table — bitmap or CFF font');
|
|
105
|
+
if (tables.__t_hmtx) throw new Error('woff2 transformed hmtx is not supported');
|
|
106
|
+
|
|
107
|
+
const head = new Reader(tables.head, 18);
|
|
108
|
+
const unitsPerEm = head.u16();
|
|
109
|
+
const indexToLocFormat = new Reader(tables.head, 50).i16();
|
|
110
|
+
const numGlyphs = new Reader(tables.maxp, 4).u16();
|
|
111
|
+
const numHMetrics = new Reader(tables.hhea, 34).u16();
|
|
112
|
+
|
|
113
|
+
const raw = container === 'woff2' && tables.__t_glyf
|
|
114
|
+
? decodeWoff2Glyf(tables.glyf)
|
|
115
|
+
: parseSfntGlyf(tables.glyf, tables.loca, indexToLocFormat, numGlyphs);
|
|
116
|
+
// a variable font is measured at the asked weight, not at whatever its default happens to be
|
|
117
|
+
const vary = tables.fvar
|
|
118
|
+
? instantiate(tables, raw, opts.weight ?? 400)
|
|
119
|
+
: { weightAxis: null, weightMeasured: null, advDelta: null };
|
|
120
|
+
const glyphs = resolveComposites(raw);
|
|
121
|
+
|
|
122
|
+
const advance = g => {
|
|
123
|
+
const i = Math.min(g, numHMetrics - 1);
|
|
124
|
+
return ((tables.hmtx[i * 4] << 8) | tables.hmtx[i * 4 + 1]) + (vary.advDelta?.[g] ?? 0);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const cmap = parseCmap(tables.cmap);
|
|
128
|
+
if (!cmap) throw new Error('no usable cmap subtable');
|
|
129
|
+
const gid = ch => cmap.get(ch.codePointAt(0));
|
|
130
|
+
|
|
131
|
+
const xg = gid('x');
|
|
132
|
+
if (xg == null || !glyphs[xg] || !bboxOf(glyphs[xg]))
|
|
133
|
+
throw new Error('no outline for "x" — Latin lowercase is required to measure x-height');
|
|
134
|
+
const xHeight = bboxOf(glyphs[xg]).yMax;
|
|
135
|
+
if (!(xHeight > 0)) throw new Error('measured x-height is not positive');
|
|
136
|
+
|
|
137
|
+
const Hg = gid('H');
|
|
138
|
+
const capHeight = Hg != null && glyphs[Hg] && bboxOf(glyphs[Hg]) ? bboxOf(glyphs[Hg]).yMax : null;
|
|
139
|
+
|
|
140
|
+
const flatTops = [], flatFeet = [], ascTops = [];
|
|
141
|
+
for (const ch of FLAT_TOP) { const g = gid(ch); const bb = g != null && glyphs[g] ? bboxOf(glyphs[g]) : null; if (bb) flatTops.push(bb.yMax / xHeight); }
|
|
142
|
+
for (const ch of FLAT_FOOT) { const g = gid(ch); const bb = g != null && glyphs[g] ? bboxOf(glyphs[g]) : null; if (bb) flatFeet.push(bb.yMin / xHeight); }
|
|
143
|
+
for (const ch of ASC_LETTER) { const g = gid(ch); const bb = g != null && glyphs[g] ? bboxOf(glyphs[g]) : null; if (bb) ascTops.push(bb.yMax / xHeight); }
|
|
144
|
+
const spreadOf = a => a.length < 2 ? 0 : Math.max(...a) - Math.min(...a);
|
|
145
|
+
|
|
146
|
+
const ys = BAND.map(t => xHeight * t);
|
|
147
|
+
let w = 0, advSum = 0, lsbBox = 0, rsbBox = 0, lsbStem = 0, rsbStem = 0, inked = 0;
|
|
148
|
+
let inkTop = capHeight ?? xHeight, inkBottom = 0, seen = 0;
|
|
149
|
+
|
|
150
|
+
for (const ch of LOWER) {
|
|
151
|
+
const g = gid(ch);
|
|
152
|
+
if (g == null) continue;
|
|
153
|
+
const gl = glyphs[g];
|
|
154
|
+
if (!gl) continue;
|
|
155
|
+
const bb = bboxOf(gl);
|
|
156
|
+
const adv = advance(g);
|
|
157
|
+
if (!bb || adv <= 0) continue;
|
|
158
|
+
seen++;
|
|
159
|
+
if (ASC.includes(ch) && bb.yMax > inkTop) inkTop = bb.yMax;
|
|
160
|
+
if (DESC.includes(ch) && bb.yMin < inkBottom) inkBottom = bb.yMin;
|
|
161
|
+
const k = FREQ[ch];
|
|
162
|
+
w += k;
|
|
163
|
+
advSum += adv * k;
|
|
164
|
+
lsbBox += bb.xMin * k;
|
|
165
|
+
rsbBox += (adv - bb.xMax) * k;
|
|
166
|
+
inked += (bb.xMax - bb.xMin) * k;
|
|
167
|
+
const segs = pathOf(gl);
|
|
168
|
+
const l = [], r = [];
|
|
169
|
+
for (const y of ys) {
|
|
170
|
+
const xs = crossingsAt(segs, y);
|
|
171
|
+
if (xs.length) { l.push(Math.min(...xs)); r.push(Math.max(...xs)); }
|
|
172
|
+
}
|
|
173
|
+
if (l.length) {
|
|
174
|
+
lsbStem += (l.reduce((a, b) => a + b, 0) / l.length) * k;
|
|
175
|
+
rsbStem += (adv - r.reduce((a, b) => a + b, 0) / r.length) * k;
|
|
176
|
+
} else { lsbStem += bb.xMin * k; rsbStem += (adv - bb.xMax) * k; }
|
|
177
|
+
}
|
|
178
|
+
if (seen < 20) throw new Error(`only ${seen} of 26 Latin lowercase glyphs present — not enough to measure`);
|
|
179
|
+
|
|
180
|
+
let monospace = false;
|
|
181
|
+
if (tables.post && tables.post.length >= 16) {
|
|
182
|
+
const pr = new Reader(tables.post, 12);
|
|
183
|
+
monospace = pr.u32() !== 0;
|
|
184
|
+
}
|
|
185
|
+
if (!monospace) {
|
|
186
|
+
const advs = [];
|
|
187
|
+
for (const ch of LOWER) { const g = gid(ch); if (g != null && glyphs[g]) advs.push(advance(g)); }
|
|
188
|
+
monospace = advs.length > 5 && advs.every(a => a === advs[0]);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const stemGlyph = gid('l') ?? gid('i');
|
|
192
|
+
let stemWidth = null;
|
|
193
|
+
if (stemGlyph != null && glyphs[stemGlyph] && glyphs[stemGlyph].contours.length) {
|
|
194
|
+
const segs = pathOf(glyphs[stemGlyph]);
|
|
195
|
+
const ws = [];
|
|
196
|
+
for (const t of [0.35, 0.5, 0.65]) {
|
|
197
|
+
const xs = crossingsAt(segs, xHeight * t);
|
|
198
|
+
if (xs.length >= 2) ws.push(Math.max(...xs) - Math.min(...xs));
|
|
199
|
+
}
|
|
200
|
+
if (ws.length) stemWidth = ws.reduce((a, b) => a + b, 0) / ws.length;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const round = (v, n = 4) => v == null ? null : Number(v.toFixed(n));
|
|
204
|
+
return {
|
|
205
|
+
...(parseName(tables.name) ?? { family: null, familyRaw: null }),
|
|
206
|
+
unitsPerEm,
|
|
207
|
+
xHeightRatio: round(xHeight / unitsPerEm),
|
|
208
|
+
capHeightRatio: round(capHeight == null ? null : capHeight / unitsPerEm),
|
|
209
|
+
ascenderRatio: round(inkTop / unitsPerEm),
|
|
210
|
+
descenderRatio: round(-inkBottom / unitsPerEm),
|
|
211
|
+
inkRatio: round((inkTop - inkBottom) / unitsPerEm),
|
|
212
|
+
advanceX: round((advSum / w) / xHeight),
|
|
213
|
+
gapBox: round(((lsbBox + rsbBox) / w) / xHeight),
|
|
214
|
+
gapStem: round(((lsbStem + rsbStem) / w) / xHeight),
|
|
215
|
+
inkedX: round((inked / w) / xHeight),
|
|
216
|
+
stemX: round(stemWidth == null ? null : stemWidth / xHeight),
|
|
217
|
+
topSpread: round(spreadOf(flatTops)),
|
|
218
|
+
footSpread: round(spreadOf(flatFeet)),
|
|
219
|
+
ascLetterRatio: ascTops.length ? round(Math.max(...ascTops), 3) : null,
|
|
220
|
+
weightAxis: vary.weightAxis,
|
|
221
|
+
weightMeasured: vary.weightMeasured,
|
|
222
|
+
monospace,
|
|
223
|
+
glyphsMeasured: seen,
|
|
224
|
+
};
|
|
225
|
+
}
|