// R4.4a generator of crates/core/src/pdf/write/afm_data.rs (plan 2026-10-17 // §B.1.3 "Text rules"): the metrics pdf-lib 1.17.1 measures the three standard // fonts with, over WinAnsi, from the frozen O5 oracle (afm.json), and the // Unicode tables of the text rules as V8 had them, from the frozen O4 oracle // (text.json): the safeText dropped classes, toUpperCase, JS \s and trim. // Every table is sorted for a binary search. Deterministic: rerunning on the // same oracles writes the same file (the header names their sha256 and the // commit that last touched each). The Rust suite crates/core/tests/pdf_text.rs // checks the tables back against the oracles. // Usage: node scripts/r4-afm-data.mjs import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' import { readFileSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))) const ORACLES = 'crates/core/tests/oracles/r4' const OUT = join(ROOT, 'crates/core/src/pdf/write/afm_data.rs') const FONTS = [ ['Helvetica', 'HELVETICA'], ['Helvetica-Bold', 'HELVETICA_BOLD'], ['Times-Roman', 'TIMES_ROMAN'], ] const MAX_LINE = 100 const INDENT = ' ' function readOracle(name) { const path = `${ORACLES}/${name}` const text = readFileSync(join(ROOT, path), 'utf8') const sha256 = createHash('sha256').update(text).digest('hex') const commit = execFileSync('git', ['log', '-1', '--format=%h', '--', path], { cwd: ROOT, encoding: 'utf8', }).trim() return { path, data: JSON.parse(text), sha256, commit: commit || 'none' } } function fail(message) { throw new Error(`r4-afm-data: ${message}`) } function hex(codePoint) { return `0x${codePoint.toString(16).toUpperCase().padStart(4, '0')}` } /** Items joined by ", " and packed greedily into lines of at most MAX_LINE. */ function pack(items, indent) { const lines = [] let line = '' for (const item of items) { const next = line ? `${line} ${item},` : `${indent}${item},` if (next.length > MAX_LINE && line) { lines.push(line) line = `${indent}${item},` } else { line = next } } if (line) lines.push(line) return lines.join('\n') } function byteGlyphs(winAnsi) { const glyphs = new Map() for (const [, byte, glyph] of winAnsi) { const known = glyphs.get(byte) if (known !== undefined && known !== glyph) { fail(`byte ${byte} prints ${known} and ${glyph}`) } glyphs.set(byte, glyph) } return glyphs } function widthsOf(font, glyphs) { const widths = new Array(256).fill(0) for (const [byte, glyph] of glyphs) { const metric = font.glyphs[glyph] if (metric !== undefined) widths[byte] = metric[0] } return widths } function kerningOf(font, glyphs) { const pairs = [] for (const [left, leftGlyph] of glyphs) { const row = font.kerning[leftGlyph] ?? {} for (const [right, rightGlyph] of glyphs) { const amount = row[rightGlyph] if (amount !== undefined) pairs.push([left, right, amount]) } } return pairs.sort((a, b) => a[0] - b[0] || a[1] - b[1]) } function fontStatic(name, constName, font, glyphs) { const widths = widthsOf(font, glyphs) const kerning = kerningOf(font, glyphs) const tuples = kerning.map(([l, r, k]) => `(${l}, ${r}, ${k})`) return [ `/// ${name}: ${kerning.length} kerning pairs between WinAnsi glyphs.`, '#[rustfmt::skip]', `pub static ${constName}: FontMetrics = FontMetrics {`, `${INDENT}widths: [`, pack(widths.map(String), INDENT.repeat(2)), `${INDENT}],`, `${INDENT}kerning: &[`, pack(tuples, INDENT.repeat(2)), `${INDENT}],`, '};', ].join('\n') } function rangesOf(rows, keep) { return rows.filter(keep).map(([start, end]) => `(${hex(start)}, ${hex(end)})`) } function sliceStatic(doc, name, type, items) { return [ ...doc.map((line) => `/// ${line}`), '#[rustfmt::skip]', `pub static ${name}: &[${type}] = &[`, pack(items, INDENT), '];', ].join('\n') } function checkSafeText(ranges, winAnsi) { const encodable = new Set(winAnsi.map(([codePoint]) => codePoint)) for (const [start, end, kind] of ranges) { for (let cp = start; cp <= end; cp += 1) { const surrogate = cp >= 0xd800 && cp <= 0xdfff const expected = encodable.has(cp) && !surrogate ? 'kept' : 'question' if (kind !== 'dropped' && kind !== expected) { fail(`safeText ${hex(cp)} is ${kind}, WinAnsi says ${expected}`) } } } } function upperSpecial([codePoint, result]) { const escaped = result .map((cp) => `\\u{${cp.toString(16).toUpperCase()}}`) .join('') return `(${hex(codePoint)}, "${escaped}")` } function header(afm, text) { const env = text.data.environment return [ `//! Generated by \`scripts/r4-afm-data.mjs\`: do not edit, rerun the generator.`, '//!', '//! The AFM metrics of Helvetica, Helvetica-Bold and Times-Roman over WinAnsi as pdf-lib', '//! 1.17.1 measures them (@pdf-lib/standard-fonts 1.0.0), and the Unicode tables of the', `//! text rules as V8 ${env.v8} had them (Node ${env.node}, ICU ${env.icu},`, `//! Unicode ${env.unicode}). Sources, the frozen oracles:`, `//! - O5 \`${afm.path}\` (commit ${afm.commit})`, `//! sha256 ${afm.sha256}`, `//! - O4 \`${text.path}\` (commit ${text.commit})`, `//! sha256 ${text.sha256}`, ].join('\n') } const FONT_METRICS = `/// The metrics one standard font is measured with, by WinAnsi byte. pub struct FontMetrics { /// AFM \`WX\` of the glyph each byte prints; 0 where the byte prints no glyph (the /// width lookup then falls back to 250, pdf-lib's \`|| 250\`). pub widths: [u16; 256], /// AFM \`KPX\` (left byte, right byte, amount) between WinAnsi glyphs, sorted by pair. pub kerning: &'static [(u8, u8, i16)], }` function checkRuns(runs) { runs.forEach(([start, end], index) => { const previous = runs[index - 1] if (end < start || (previous && previous[1] >= start)) { fail(`upper run ${hex(start)} unsorted or overlapping`) } }) } function unicodeTables(text, winAnsi) { const { safeText, upper, jsWhitespace, jsTrim } = text checkSafeText(safeText.ranges, winAnsi) checkRuns(upper.runs) const sortedWinAnsi = [...winAnsi].sort((a, b) => a[0] - b[0]) return [ sliceStatic( [ '`Encodings.WinAnsi`: (code point, byte) for every code point it encodes, sorted.', ], 'WINANSI', '(u32, u8)', sortedWinAnsi.map(([cp, byte]) => `(${hex(cp)}, ${byte})`), ), sliceStatic( [ 'safeText `[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]`: the dropped code point ranges, inclusive.', ], 'SAFE_TEXT_DROPPED', '(u32, u32)', rangesOf(safeText.ranges, ([, , kind]) => kind === 'dropped'), ), sliceStatic( [ '`toUpperCase` one-to-one: (start, end, step, delta), start + k * step <= end maps to', 'itself + delta. Sorted by start, disjoint.', ], 'UPPER_RUNS', '(u32, u32, u32, i32)', upper.runs.map( ([s, e, step, d]) => `(${hex(s)}, ${hex(e)}, ${step}, ${d})`, ), ), sliceStatic( ['`toUpperCase` one-to-many: (code point, result), sorted.'], 'UPPER_SPECIAL', '(u32, &str)', [...upper.special].sort((a, b) => a[0] - b[0]).map(upperSpecial), ), sliceStatic( ['JS `\\s`: the matched code point ranges, inclusive.'], 'JS_WHITESPACE', '(u32, u32)', rangesOf(jsWhitespace.ranges, () => true), ), sliceStatic( ['`String.prototype.trim`: the stripped code point ranges, inclusive.'], 'JS_TRIM', '(u32, u32)', rangesOf(jsTrim.ranges, () => true), ), ] } function generate() { const afm = readOracle('afm.json') const text = readOracle('text.json') const { winAnsi, fonts } = afm.data const glyphs = byteGlyphs(winAnsi) const parts = [ header(afm, text), FONT_METRICS, ...FONTS.map(([name, constName]) => fontStatic(name, constName, fonts[name], glyphs), ), ...unicodeTables(text.data, winAnsi), ] writeFileSync(OUT, `${parts.join('\n\n')}\n`) } generate()