@openpresentation/opf-render 0.33.0 → 0.34.1

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.
@@ -1,5 +1,6 @@
1
+ import { fontCoverageProbe } from './script-fonts.js';
1
2
  import { fontPolicyFor } from "@openpresentation/opf/font-policy";
2
- import { pickFace } from "./font-registry.js";
3
+ import { pickFace, OPFFontError } from "./font-registry.js";
3
4
  import { toSvg } from "./svg.js";
4
5
  import { deckInternals } from "./svg-internals.js";
5
6
  export { lazyFontEntries, lazyFontList } from "./lazy-font-list.js";
@@ -44,11 +45,32 @@ export function presentationFamilies(presentation, options = {}) {
44
45
  const RECORDED_EM = 0.01;
45
46
 
46
47
  /** The registry's view with faces added: what a registry holding `faces` resolves families to (`pickFace`, its own selection). */
47
- function registryView({ faces, policy = "none", aliases = new Map(), fallbackFamily }) {
48
+ function registryView({ faces, policy = "none", aliases = new Map(), fallbackFamily, mapFamily }) {
48
49
  const pool = [...faces].map(face => ({ ...face, familyGroup: face.familyGroup ?? face.family }));
49
- return style => {
50
- const family = style?.fontFamily;
51
- const { face } = pickFace(pool, family, style, { policy, aliases, fallbackFamily });
50
+ // Fitting asks about the same styles many times. This view owns one fixed pool
51
+ // and selection policy: keep only successful choices, never full styles or
52
+ // failures (their paths belong to the current request), for this call only.
53
+ const selected = new Map();
54
+ let selections = 0;
55
+ return (style, preserveChosen = false) => {
56
+ if(mapFamily&&typeof style?.fontFamily==="string")style={...style,fontFamily:mapFamily(style.fontFamily)};
57
+ const family = style?.fontFamily, weight = style?.fontWeight ?? 400, italic = !!style?.italic;
58
+ let weights = selected.get(family), variants = weights?.get(weight), choice = variants?.get(italic);
59
+ if (choice === undefined) {
60
+ choice = pickFace(pool, family, style, { policy, aliases, fallbackFamily });
61
+ // Bound memory even for a host with hundreds of distinct requested styles.
62
+ if (selections >= 512) { selected.clear(); selections = 0; weights = undefined; variants = undefined; }
63
+ if (!weights) selected.set(family, weights = new Map());
64
+ if (!variants) weights.set(weight, variants = new Map());
65
+ variants.set(italic, choice);
66
+ selections++;
67
+ }
68
+ if (preserveChosen && choice.via !== "family") {
69
+ const chosen = { ...style };
70
+ delete chosen.fontFace;
71
+ return chosen;
72
+ }
73
+ const { face } = choice;
52
74
  return { ...style, fontFamily: face.family, fontWeight: face.weight, italic: face.italic };
53
75
  };
54
76
  }
@@ -89,7 +111,7 @@ const byFace = (a, b) => a.family < b.family ? -1 : a.family > b.family ? 1 : Nu
89
111
  * The measurement `presentationFaces` draws with: it records every style it is asked to measure (resolved through `settle`) into
90
112
  * the map `record.into` holds (switch it to file what follows elsewhere).
91
113
  */
92
- function recordingMeasurement(settle, into) {
114
+ function recordingMeasurement(settle, into, coverage) {
93
115
  const record = { into };
94
116
  record.textMeasurement = {
95
117
  measure(text, size, style) {
@@ -100,10 +122,49 @@ function recordingMeasurement(settle, into) {
100
122
  const key = faceKey(family, weight, italic);
101
123
  if (!record.into.has(key)) record.into.set(key, { family, weight, italic });
102
124
  }
125
+ // Demand loaders know coverage only after selected bytes are verified. Unknown faces are optimistic for one round.
126
+ try { coverage?.(String(text), size, settled); }
127
+ catch(error) { if(!['missing-glyph','font-unavailable','font-style-unavailable'].includes(error?.code))throw error; }
128
+ // Recording must finish on unresolved styles or uncovered glyphs: ensure still runs its bounded optional fallback chain.
129
+ // Actual rendering has no recording hook and retains its original missing-glyph refusal.
103
130
  }
104
131
  return String(text).length * size * RECORDED_EM;
105
132
  },
106
133
  resolveStyle: settle,
134
+ ...(coverage ? { [fontCoverageProbe](text,size,style) { coverage(String(text),size,settle(style)); } } : {}),
135
+ };
136
+ return record;
137
+ }
138
+
139
+ /**
140
+ * The measurement of the real-metrics pass (RR-105): it records like `recordingMeasurement`, and a style that resolves to a
141
+ * face in `held` measures with `metrics` (the registry's own measurement, as export measures it). Any other style measures
142
+ * as the narrow pass does and has no outline, so a branch that a held face's real width takes is taken and the faces it asks
143
+ * for are recorded.
144
+ */
145
+ function metricMeasurement(settle, into, coverage, metrics, held) {
146
+ const record = recordingMeasurement(settle, into, coverage), recording = record.textMeasurement, estimate = recording.measure;
147
+ const soft = new Set(["missing-glyph", "font-unavailable", "font-style-unavailable"]);
148
+ const physical = (text, style) => {
149
+ if (text === "") return undefined;
150
+ const settled = settle(style);
151
+ return held.has(faceKey(settled?.fontFamily, Number.isFinite(settled?.fontWeight) ? settled.fontWeight : 400, settled?.italic === true)) ? settled : undefined;
152
+ };
153
+ record.textMeasurement = {
154
+ ...recording,
155
+ measure(text, size, style) {
156
+ const width = estimate(text, size, style), settled = physical(String(text), style);
157
+ if (!settled) return width;
158
+ try { return metrics.measure(text, size, settled); }
159
+ catch (error) { if (soft.has(error?.code)) return width; throw error; }
160
+ },
161
+ outlineBounds(text, size, style) {
162
+ estimate(text, size, style);
163
+ const settled = physical(String(text), style);
164
+ if (!settled || typeof metrics.outlineBounds !== "function") return null;
165
+ try { return metrics.outlineBounds(text, size, settled); }
166
+ catch (error) { if (soft.has(error?.code)) return null; throw error; }
167
+ },
107
168
  };
108
169
  return record;
109
170
  }
@@ -112,6 +173,7 @@ function recordingMeasurement(settle, into) {
112
173
  // freezes its catalog list), plain values and small plain objects by content.
113
174
  const objectTokens = new WeakMap();
114
175
  let nextObjectToken = 0;
176
+ // A function option (the exporter's `mapFamily`) is keyed by identity: a host that passes a fresh closure on every call gets a cold cache each time, so the option docs ask for one stable function.
115
177
  function optionToken(value) {
116
178
  if (value === null || typeof value !== "object" && typeof value !== "function") return JSON.stringify(value ?? null);
117
179
  if (Array.isArray(value)) return `[${value.map(optionToken).join(",")}]`;
@@ -181,11 +243,12 @@ function slideMemory(contexts = 8) {
181
243
  * checked) even when every slide is known, and a slide that fails throws what `toSvg` throws for it (only slides that succeed are
182
244
  * kept).
183
245
  *
184
- * `stats` counts the work, for tests and benchmarks: `decks` (decks opened), `slides` (slides composed and drawn for faces) and
246
+ * `stats` counts the work, for tests and benchmarks: `decks` (decks opened), `slides` (slides composed and drawn for faces),
247
+ * `metricSlides` (slides composed and drawn again with real metrics, RR-105) and
185
248
  * `designs` (slide designs resolved for families).
186
249
  */
187
250
  export function createFontAnalysis() {
188
- const memory = slideMemory(), stats = { decks: 0, slides: 0, designs: 0 }, checked = new Set();
251
+ const memory = slideMemory(16), stats = { decks: 0, slides: 0, metricSlides: 0, designs: 0 }, checked = new Set();
189
252
  // The deck behind `keys`, opened (resolved and checked as `toSvg` does) when work is needed or this exact deck was never checked.
190
253
  const opener = (presentation, resolveOptions, keys, optionsToken) => {
191
254
  const whole = `${optionsToken}\u0001${keys.context}\u0001${keys.slides.join("\u0001")}`;
@@ -206,43 +269,77 @@ export function createFontAnalysis() {
206
269
  function faces(presentation, options = {}, registry) {
207
270
  const resolveOptions = resolveOptionsOf(options);
208
271
  if (registry) registry = { ...registry, faces: [...registry.faces] };
209
- const view = registry ? registryView(registry) : undefined;
272
+ const view = registry ? registryView(registry.preserveChosenFamilies ? {...registry, mapFamily: undefined} : registry) : undefined;
210
273
  const settle = style => {
211
274
  if (!view) return { ...style };
212
275
  try { return view(style); } catch { return { ...style }; }
213
276
  };
277
+ // Native keeps chosen roles outside its raw script planner. Its inner resolver must still expose physical Emoji/script faces.
278
+ const inputBinding = registry?.preserveChosenFamilies && view ? {
279
+ mapInputFamily: registry.mapFamily,
280
+ resolveInputStyle: style => { try { return view(style, true); } catch { return { ...style }; } },
281
+ } : undefined;
214
282
  const keys = deckKeys(presentation);
215
- if (!keys) {
216
- // Not a deck object: one whole-deck pass, kept nowhere.
283
+ // One recording pass over the deck: every slide composed, then drawn, with the measurement `recorder(into)` makes. `tag`
284
+ // separates the per-slide memory of passes that measure differently.
285
+ const recordPass = (recorder, tag, counter = "slides") => {
286
+ if (!keys) {
287
+ // Not a deck object: one whole-deck pass, kept nowhere.
288
+ const seen = new Map();
289
+ const measurement = recorder(seen).textMeasurement;
290
+ if (inputBinding) {
291
+ const opened = deckInternals.openDeck(presentation, resolveOptions);
292
+ for (let index = 0; index < opened.presentation.slides.length; index++) opened.bind(index, measurement, inputBinding);
293
+ for (let index = 0; index < opened.presentation.slides.length; index++) if (resolveOptions.skipHidden !== true || !opened.presentation.slides[index].hidden) opened.render(index);
294
+ } else toSvg(presentation, { ...resolveOptions, fonts: { textMeasurement: measurement } });
295
+ stats.decks++;
296
+ return seen;
297
+ }
298
+ const optionsToken = optionsKey(resolveOptions, presentation);
299
+ const slides = memory(`faces${tag}${optionsToken}${registry ? registryKey(registry) : ""}${keys.context}`, keys.slides.length);
300
+ const deck = opener(presentation, resolveOptions, keys, optionsToken);
301
+ const entries = keys.slides.map(slides.get);
302
+ const missing = entries.flatMap((entry, index) => entry === undefined ? [index] : []);
303
+ if (missing.length) {
304
+ // Composition of the slides, then their drawing, as `toSvg` runs them.
305
+ const opened = deck.open();
306
+ const made = new Map(missing.map(index => [index, { composed: new Map(), drawn: new Map() }]));
307
+ const recorders = new Map(missing.map(index => [index, recorder(made.get(index).composed)]));
308
+ for (const index of missing) opened.bind(index, recorders.get(index).textMeasurement, inputBinding);
309
+ // A slide is drawn with the measurement it was composed with; what it measures from here on is its drawing. `skipHidden`
310
+ // leaves hidden slides undrawn (they are still composed), as in `toSvg`.
311
+ for (const index of missing) {
312
+ if (resolveOptions.skipHidden === true && opened.presentation.slides[index]?.hidden === true) continue;
313
+ recorders.get(index).into = made.get(index).drawn;
314
+ opened.render(index);
315
+ }
316
+ for (const [index, entry] of made) { slides.set(keys.slides[index], entry); entries[index] = entry; }
317
+ stats[counter] += missing.length;
318
+ } else deck.check();
319
+ // In the order one `toSvg` records them: every slide's composition, then every slide's drawing.
217
320
  const seen = new Map();
218
- toSvg(presentation, { ...resolveOptions, fonts: { textMeasurement: recordingMeasurement(settle, seen).textMeasurement } });
219
- stats.decks++;
220
- return [...seen.values()].sort(byFace);
221
- }
222
- const optionsToken = optionsKey(resolveOptions, presentation);
223
- const slides = memory(`faces\u0001${optionsToken}\u0001${registry ? registryKey(registry) : ""}\u0001${keys.context}`, keys.slides.length);
224
- const deck = opener(presentation, resolveOptions, keys, optionsToken);
225
- const entries = keys.slides.map(slides.get);
226
- const missing = entries.flatMap((entry, index) => entry === undefined ? [index] : []);
227
- if (missing.length) {
228
- // Composition of the slides, then their drawing, as `toSvg` runs them.
229
- const opened = deck.open();
230
- const made = new Map(missing.map(index => [index, { composed: new Map(), drawn: new Map() }]));
231
- const recorders = new Map(missing.map(index => [index, recordingMeasurement(settle, made.get(index).composed)]));
232
- for (const index of missing) opened.bind(index, recorders.get(index).textMeasurement);
233
- // A slide is drawn with the measurement it was composed with; what it measures from here on is its drawing. `skipHidden`
234
- // leaves hidden slides undrawn (they are still composed), as in `toSvg`.
235
- for (const index of missing) {
236
- if (resolveOptions.skipHidden === true && opened.presentation.slides[index]?.hidden === true) continue;
237
- recorders.get(index).into = made.get(index).drawn;
238
- opened.render(index);
321
+ for (const phase of ["composed", "drawn"]) for (const entry of entries) for (const [key, face] of entry[phase]) if (!seen.has(key)) seen.set(key, face);
322
+ return seen;
323
+ };
324
+ const seen = recordPass(into => recordingMeasurement(settle, into, registry?.coverage), "narrow");
325
+ // RR-105, the preparation invariant: the faces a handle prepares for a deck cover every face the deck's real-metrics
326
+ // composition and drawing measure. The narrow pass above measures every string as almost nothing, so it never takes a
327
+ // branch that only real widths take (a title that wraps and splits at its colon, text that overflows into another
328
+ // arrangement, a continuation slide), and such a branch can measure a face the narrow pass never asked for. With
329
+ // `registry.metrics` (the registry's own measurement and the faces it holds) a second pass composes and draws the deck
330
+ // with the real metrics of every held face, once every face the narrow pass found is held; a face it is not holding
331
+ // measures as in the narrow pass and is recorded. A loader that loads what this returns and asks again reaches the
332
+ // fixpoint: a call that returns only held faces means the real pass measured nothing else (`ensure` bounds the rounds).
333
+ const metrics = registry?.metrics;
334
+ if (metrics) {
335
+ const keyOf = face => faceKey(face.family, face.weight ?? 400, face.italic === true);
336
+ const pool = new Set(registry.faces.map(keyOf)), held = new Set([...metrics.held].map(keyOf));
337
+ // A face outside the pool cannot be prepared (drawing reports it); every other narrow face must be held first.
338
+ if (![...seen.keys()].some(key => pool.has(key) && !held.has(key))) {
339
+ const real = recordPass(into => metricMeasurement(settle, into, registry.coverage, metrics, held), `metrics${[...held].sort().join("")}`, "metricSlides");
340
+ for (const [key, face] of real) if (!seen.has(key)) seen.set(key, face);
239
341
  }
240
- for (const [index, entry] of made) { slides.set(keys.slides[index], entry); entries[index] = entry; }
241
- stats.slides += missing.length;
242
- } else deck.check();
243
- // In the order one `toSvg` records them: every slide's composition, then every slide's drawing.
244
- const seen = new Map();
245
- for (const phase of ["composed", "drawn"]) for (const entry of entries) for (const [key, face] of entry[phase]) if (!seen.has(key)) seen.set(key, face);
342
+ }
246
343
  return [...seen.values()].sort(byFace).map(face => ({ ...face }));
247
344
  }
248
345
 
@@ -276,9 +373,69 @@ export function createFontAnalysis() {
276
373
  return { faces, families, stats };
277
374
  }
278
375
 
279
- function registryKey({ faces, policy = "none", aliases = new Map(), fallbackFamily }) {
376
+ function registryKey({ faces, policy = "none", aliases = new Map(), fallbackFamily, coverageKey, mapFamily, preserveChosenFamilies }) {
280
377
  // Every field `pickFace` reads, as it reads them (`italic` is compared with ===, `fallbackOnly` and `scripts` by truth).
281
- return JSON.stringify([faces.map(face => [face.family, face.familyGroup ?? face.family, face.weight ?? null, face.italic ?? null, !!face.fallbackOnly, !!face.scripts]), policy, [...aliases], fallbackFamily ?? null]);
378
+ return JSON.stringify([faces.map(face => [face.family, face.familyGroup ?? face.family, face.weight ?? null, face.italic ?? null, !!face.fallbackOnly, !!face.scripts]), policy, [...aliases], fallbackFamily ?? null, coverageKey ?? null, optionToken(mapFamily), !!preserveChosenFamilies]);
379
+ }
380
+
381
+ /** Validate extra measurements without changing the caller's requests. */
382
+ export function fontMeasurementRequests(requests = []) {
383
+ if (!Array.isArray(requests) || requests.some(request =>
384
+ !request || typeof request.text !== 'string' || !Number.isFinite(request.size) || request.size <= 0 ||
385
+ !request.style || typeof request.style.fontFamily !== 'string' || !request.style.fontFamily.trim() ||
386
+ !Number.isFinite(request.style.fontWeight ?? 400) || (request.style.fontWeight ?? 400) < 1 || (request.style.fontWeight ?? 400) > 1000))
387
+ throw new OPFFontError('invalid-font-measurement-request', 'Measurement requests need text, a positive finite size, and a concrete font style.');
388
+ return requests;
389
+ }
390
+
391
+ // Nominal names only: an exporter can resolve an undrawn role without loading
392
+ // it. Actual measurement still requires the registry's verified physical face.
393
+ // `generation` (optional) returns a number that changes whenever the registry's faces change (registry.facesGeneration): the pool is then
394
+ // rebuilt only on a change, and a call costs a map lookup. Without it every call describes the faces and compares them.
395
+ export function lazyFontNames({lazy, describeFaces, generation, policy = 'none', aliases = new Map(), fallbackFamily}) {
396
+ let signature, stamp, pool, selected = new Map();
397
+ const unavailable=error=>['font-unavailable','font-style-unavailable','font-encoding-required'].includes(error?.code);
398
+ const pick = style => {
399
+ if(typeof style?.fontFamily!=='string'||!style.fontFamily.trim()||/[\u0000-\u001f"'\\<>;]/.test(style.fontFamily))
400
+ throw new OPFFontError('invalid-font-family','Font family must be a nonempty plain name.');
401
+ if(!Number.isFinite(style.fontWeight??400)||(style.fontWeight??400)<1||(style.fontWeight??400)>1000)
402
+ throw new OPFFontError('invalid-font-weight','Font weight must be between 1 and 1000.');
403
+ const now = generation?.();
404
+ // With a generation the faces are described only when it changed; without one, on every call, to compare them.
405
+ const held = now !== undefined && now === stamp ? undefined : describeFaces({selection: true});
406
+ const current = held && now === undefined ? JSON.stringify(held) : undefined;
407
+ if (held && (now !== undefined || current !== signature)) {
408
+ signature = current;
409
+ stamp = now;
410
+ const keys = new Set(held.map(faceKeyOf));
411
+ pool = [...held, ...lazy.filter(face => !keys.has(faceKeyOf(face)))].map(face => ({...face, familyGroup: face.familyGroup ?? face.family}));
412
+ selected = new Map();
413
+ }
414
+ const key = JSON.stringify([style.fontFamily, style.fontWeight ?? 400, !!style.italic]);
415
+ let result = selected.get(key);
416
+ if (!result) {
417
+ result = pickFace(pool, style.fontFamily, style, {policy, aliases, fallbackFamily});
418
+ if (selected.size >= 512) selected.clear();
419
+ selected.set(key, result);
420
+ }
421
+ return result;
422
+ };
423
+ return {
424
+ resolveStyle(style) {
425
+ try {
426
+ const {face} = pick(style), result = {...style, fontFamily: face.family, fontWeight: face.weight, italic: !!face.italic};
427
+ delete result.fontFace;
428
+ return result;
429
+ } catch(error) { if(!unavailable(error))throw error;return {...style}; }
430
+ },
431
+ resolveFont(style) {
432
+ try {
433
+ const {face, via, compatibility} = pick(style);
434
+ return {requestedFamily: style.fontFamily, sourceFamily: style.fontFamily, resolvedFamily: face.family,
435
+ requestedWeight: style.fontWeight ?? 400, resolvedWeight: face.weight, italic: !!face.italic, substitute: via !== 'family', compatibility};
436
+ } catch(error) { if(!unavailable(error))throw error;return {requestedFamily: style.fontFamily, resolvedFamily: style.fontFamily, substitute: false}; }
437
+ },
438
+ };
282
439
  }
283
440
 
284
441
  /**
@@ -288,12 +445,20 @@ function registryKey({ faces, policy = "none", aliases = new Map(), fallbackFami
288
445
  * registry's. `renderOptions` are the `toSvg` options the document resolves with (`catalogs`, ...), and a document that
289
446
  * does not resolve throws what `toSvg` throws for it. Face level: a bold or italic run added by an edit adds just that face.
290
447
  * Pass `analysis` (`createFontAnalysis()`) to keep each slide's faces between calls: then only slides that changed are analyzed.
448
+ * Pass `metrics` (the registry's `textMeasurement`) to include the faces a real-metrics composition measures (RR-105).
291
449
  */
292
- export function lazyFacesNeeded(presentation, renderOptions, { lazy, held, loaded = new Set(), policy = "none", aliases = new Map(), fallbackFamily, analysis }) {
450
+ export function lazyFacesNeeded(presentation, renderOptions, { lazy, held, loaded = new Set(), policy = "none", aliases = new Map(), fallbackFamily, analysis, metrics, mapFamily, preserveChosenFamilies, measurementRequests = [] }) {
293
451
  const heldFaces = [...held], heldKeys = new Set(heldFaces.map(faceKeyOf));
294
452
  const missing = lazy.filter(face => !heldKeys.has(faceKeyOf(face)) && !loaded.has(face.file));
453
+ const pool = [...heldFaces, ...missing].map(face => ({...face, familyGroup: face.familyGroup ?? face.family}));
295
454
  // `analysis` (from `createFontAnalysis`) keeps each slide's faces between calls, so a fonts handle redoes only changed slides.
296
- const drawn = new Set((analysis ?? createFontAnalysis()).faces(presentation, renderOptions, { faces: [...heldFaces, ...missing], policy, aliases, fallbackFamily }).map(faceKeyOf));
455
+ const drawn = new Set((analysis ?? createFontAnalysis()).faces(presentation, renderOptions, { faces: pool, policy, aliases, fallbackFamily, mapFamily, preserveChosenFamilies,
456
+ // RR-105: with the registry's measurement, the faces real widths ask for too (see `faces`).
457
+ ...(metrics ? { metrics: { measure: metrics.measure, outlineBounds: metrics.outlineBounds, held: heldFaces } } : {}) }).map(faceKeyOf));
458
+ // Requests already use the exporter's chosen/safe family. Keep them separate
459
+ // from SVG analysis and its cache identity; only actual measurement adds a face.
460
+ for (const request of fontMeasurementRequests(measurementRequests)) if (request.text !== '')
461
+ drawn.add(faceKeyOf(pickFace(pool, request.style.fontFamily, request.style, {policy, aliases, fallbackFamily}).face));
297
462
  return missing.filter(face => drawn.has(faceKeyOf(face)));
298
463
  }
299
464
  function faceKeyOf(face) { return `${lc(face.family)}\u0000${face.weight}\u0000${!!face.italic}`; }
@@ -343,8 +508,8 @@ export function lazyFontsFor(entries, { lazy, held, hasFamily, loaded = new Set(
343
508
  // The registry's view with every vendored face added: what Node draws with everything loaded.
344
509
  let pool;
345
510
  const universe = () => pool ??= [
346
- ...heldFaces.map(face => ({ ...face, familyGroup: face.family })),
347
- ...lazy.filter(face => !heldKeys.has(faceKey(face)) && !loaded.has(face.file)).map(face => ({ family: face.family, familyGroup: face.family, weight: face.weight, italic: !!face.italic, lazy: face })),
511
+ ...heldFaces.map(face => ({ ...face, familyGroup: face.familyGroup ?? face.family })),
512
+ ...lazy.filter(face => !heldKeys.has(faceKey(face)) && !loaded.has(face.file)).map(face => ({ family: face.family, familyGroup: face.familyGroup ?? face.family, weight: face.weight, italic: !!face.italic, lazy: face })),
348
513
  ];
349
514
  for (const entry of entries) {
350
515
  if (typeof entry === "string") { addFamily(entry); continue; }
package/dist/pdf-fonts.js CHANGED
@@ -37,7 +37,7 @@ export class FontLibrary {
37
37
 
38
38
  /** Register font bytes once (by content hash). Returns the face, or null when the file cannot be used for embedding. */
39
39
  addData(data, origin, declaredFamily) {
40
- const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
40
+ const bytes = new Uint8Array(data);
41
41
  const face = this.adopt(parseFace(bytes, hex(sha256(bytes)), origin), origin);
42
42
  // The family a style sheet declares for the data names the face too (the name table may say something else).
43
43
  if (face && declaredFamily) face.names.add(declaredFamily.toLowerCase());
package/dist/pdf-text.js CHANGED
@@ -12,6 +12,7 @@ import { attributesOf, inheritStyle, parseFontFamilies, parseFontWeight, parseLe
12
12
 
13
13
  const bidi = bidiFactory();
14
14
  const IGNORED = /[⁦-⁩‎‏‪-‮؜]/u;
15
+ const chunkDirection = chunk => chunk.chars[0].style.direction === "rtl" ? "rtl" : "ltr";
15
16
 
16
17
  /** Parse `font-feature-settings` / `font-variant-ligatures` of a style into an object of OpenType feature booleans. */
17
18
  export function featuresOf(style) {
@@ -122,7 +123,13 @@ export function layoutText(textNode, env, parentStyle, link) {
122
123
  const runs = runsByChunk[chunkIndex];
123
124
  const total = runs.reduce((sum, run) => sum + run.width, 0);
124
125
  const anchor = chunk.chars[0].style["text-anchor"];
125
- let x = chunk.x + (anchor === "middle" ? -total / 2 : anchor === "end" ? -total : 0);
126
+ const rtl = chunkDirection(chunk) === "rtl";
127
+ // LH-189: the letter spacing after the chunk's last character does not count toward its anchor, as resvg anchors it, so outlined
128
+ // text and the PDF place a tracked middle or end anchored line where the raster preview does.
129
+ const last = runs.at(-1), trailing = last && last.width === last.natural ? last.glyphs.at(-1)?.letter ?? 0 : 0, extent = total - trailing;
130
+ // SVG start/end follow the chunk's base direction; middle stays physical.
131
+ // Use the same explicit-direction decision as bidi shaping below.
132
+ let x = chunk.x - (anchor === "middle" ? extent / 2 : anchor === "end" ? rtl ? 0 : extent : anchor === "start" && rtl ? extent : 0);
126
133
  for (const run of reorder(runs)) {
127
134
  run.x = x + (run.dx ?? 0);
128
135
  run.y = chunk.y + (run.dy ?? 0);
@@ -158,7 +165,7 @@ function collapseWhitespace(chars) {
158
165
 
159
166
  function buildRuns(chunk, env, styleIds, faceCache, linkIds, ownerIds) {
160
167
  const text = chunk.chars.map((char) => char.ch).join("");
161
- const baseDirection = chunk.chars[0].style.direction === "rtl" ? "rtl" : "ltr";
168
+ const baseDirection = chunkDirection(chunk);
162
169
  // Levels per UTF-16 unit; characters take the level of their first unit.
163
170
  const embedding = bidi.getEmbeddingLevels(text, baseDirection);
164
171
  const levels = [];
@@ -255,6 +262,7 @@ function shapeRun(run, env) {
255
262
  run.glyphs = glyphs;
256
263
  run.natural = glyphs.reduce((sum, glyph, index) => {
257
264
  glyph.spacing = letterSpacing + (glyph.codePoints.length === 1 && glyph.codePoints[0] === 0x20 ? wordSpacing : 0);
265
+ glyph.letter = letterSpacing;
258
266
  glyph.nominalIndex = index;
259
267
  return sum + glyph.advance * scale + glyph.spacing;
260
268
  }, 0);
@@ -1,3 +1,4 @@
1
+ import { loadFontFiles } from './font-files.js';
1
2
  import { FontEmbedder, FontLibrary, nominalAdvance } from "./pdf-fonts.js";
2
3
  import { actualTextFor, layoutText, textClusters } from "./pdf-text.js";
3
4
  import { IDENTITY, viewBoxTransform, applyPoint, applyStyleSheets, attributesOf, inheritStyle, invert, multiply, parseColor, parseFontWeight, parseLength, parseNumberList, parsePath, parseTransform, pathBounds, ROOT_STYLE, shapeToPath, transformPath } from "./pdf-style.js";
@@ -129,25 +130,7 @@ class Converter {
129
130
  // Fonts
130
131
 
131
132
  async loadFontFiles(files, directories) {
132
- // Font files are Node-only. A browser host passes no paths: its faces come from the SVG's @font-face data or `fontData`.
133
- if (!files.length && !directories.length) return;
134
- const { readdir, readFile, stat: fsStat, path } = await nodeFileSystem();
135
- const seen = new Set();
136
- const read = async (file) => {
137
- const resolved = path.resolve(file);
138
- if (seen.has(resolved)) return;
139
- seen.add(resolved);
140
- try {
141
- const stat = await fsStat(resolved);
142
- await this.fonts.addFile(resolved, stat, () => readFile(resolved));
143
- } catch (error) {
144
- this.diagnostic({ code: "pdf-font-unreadable", message: `Font file ${resolved} could not be read: ${error.code ?? error.message}.`, origin: resolved });
145
- }
146
- };
147
- for (const directory of directories) {
148
- for (const file of await listFonts(directory, { readdir, path })) await read(file);
149
- }
150
- for (const file of files) await read(file);
133
+ await loadFontFiles(this.fonts, files, directories, d => this.diagnostic(d));
151
134
  }
152
135
 
153
136
  addEmbeddedFontFaces(root) {
@@ -1242,18 +1225,6 @@ export function dataUriBytes(header, payload) {
1242
1225
  return bytes;
1243
1226
  }
1244
1227
 
1245
- async function listFonts(directory, { readdir, path }) {
1246
- const found = [];
1247
- let entries;
1248
- try { entries = await readdir(directory, { withFileTypes: true }); } catch { return found; }
1249
- entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1250
- for (const entry of entries) {
1251
- const full = path.join(directory, entry.name);
1252
- if (entry.isDirectory()) found.push(...await listFonts(full, { readdir, path }));
1253
- else if (/\.(ttf|otf)$/i.test(entry.name)) found.push(full);
1254
- }
1255
- return found;
1256
- }
1257
1228
 
1258
1229
  /**
1259
1230
  * Convert SVG slides to a vector PDF. `options` carries the resolved conversion settings (see toPdf in raster.js).
@@ -1,15 +1,25 @@
1
1
  #!/usr/bin/env node
2
- // RR-28: `opf-preview-fonts <outDir> [--scripts all|Jpan,Arab]` fills a self-hosted font root for <opf-deck>.
3
- import { copyPreviewFonts } from "./preview-fonts-node.js";
2
+ // RR-28: `opf-preview-fonts <outDir> [--scripts all|Jpan,Arab] [--fontconfig <file>]` fills a self-hosted font root for <opf-deck>.
3
+ // RR-106: --fontconfig also writes a fontconfig file (the font directory and the font-policy aliases), so an app on Linux that resolves
4
+ // fonts through fontconfig, LibreOffice among them, draws each family with the face OPF measured it with.
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { copyPreviewFonts, fontconfigConf } from "./preview-fonts-node.js";
4
8
 
5
9
  const args = process.argv.slice(2);
6
10
  const flag = (name) => { const at = args.indexOf(name); return at === -1 ? undefined : args[at + 1]; };
7
- const outDir = args.find((arg, index) => !arg.startsWith("--") && args[index - 1] !== "--scripts");
11
+ const outDir = args.find((arg, index) => !arg.startsWith("--") && args[index - 1] !== "--scripts" && args[index - 1] !== "--fontconfig");
8
12
  if (!outDir || args.includes("--help")) {
9
- console.error("Usage: opf-preview-fonts <outDir> [--scripts all|Jpan,Arab,...]\nCopies the pinned, license-verified preview fonts to <outDir> (serve it as <opf-deck fonts=\"/<outDir>/\">).");
13
+ console.error("Usage: opf-preview-fonts <outDir> [--scripts all|Jpan,Arab,...] [--fontconfig <file>]\nCopies the pinned, license-verified preview fonts to <outDir> (serve it as <opf-deck fonts=\"/<outDir>/\">).\n--fontconfig <file> also writes a fontconfig file with <outDir> and an alias per font-policy replacement (Aptos to Intos, ...),\nfor example ~/.config/fontconfig/conf.d/60-opf-fonts.conf, so LibreOffice on Linux draws each family with OPF's face.");
10
14
  process.exit(outDir ? 0 : 2);
11
15
  }
12
16
  const scripts = flag("--scripts");
13
17
  const result = copyPreviewFonts({ outDir, scripts: scripts === undefined ? false : scripts === "all" ? "all" : scripts.split(",").map((code) => code.trim()).filter(Boolean) });
14
18
  console.log(`Preview fonts: ${result.packages} packages, ${result.copied} copied, ${result.verified} already verified, ${(result.bytes / 1048576).toFixed(1)} MiB, all SHA-256 verified.`);
15
19
  if (result.missing.length) console.warn(`Not installed (script faces skipped): ${result.missing.join(", ")}`);
20
+ const fontconfig = flag("--fontconfig");
21
+ if (fontconfig) {
22
+ fs.mkdirSync(path.dirname(path.resolve(fontconfig)), { recursive: true });
23
+ fs.writeFileSync(fontconfig, fontconfigConf({ fontDir: path.resolve(outDir) }));
24
+ console.log(`fontconfig: wrote ${fontconfig} (the font directory and the font-policy aliases); run fc-cache -f, then restart the app.`);
25
+ }
@@ -12,3 +12,21 @@ export interface CopyPreviewFontsResult { copied: number; verified: number; byte
12
12
 
13
13
  /** Copy the pinned preview fonts into `outDir`, verifying every file's SHA-256 and writing every license notice to `LICENSES.txt`. */
14
14
  export declare function copyPreviewFonts(options: CopyPreviewFontsOptions): CopyPreviewFontsResult;
15
+
16
+ /** RR-106: a font-policy family that OPF previews with a replacement face, as a fontconfig alias. */
17
+ export interface FontconfigAlias { family: string; prefer: string; compatibility: "metric" | "visual" | string }
18
+
19
+ /** One alias per font-policy family OPF previews with a replacement (Aptos to Intos, Calibri to Carlito, ...). */
20
+ export declare function fontconfigAliases(policy?: { families: readonly unknown[] }): FontconfigAlias[];
21
+
22
+ export interface FontconfigConfOptions {
23
+ /** The directory of the copied preview fonts, added as a font directory. */
24
+ fontDir?: string;
25
+ aliases?: readonly FontconfigAlias[];
26
+ /** Include /etc/fonts/fonts.conf: a whole configuration for FONTCONFIG_FILE instead of a conf.d file. */
27
+ includeSystem?: boolean;
28
+ cacheDir?: string;
29
+ }
30
+
31
+ /** A fontconfig file with the aliases and the preview font directory (for ~/.config/fontconfig/conf.d/, or FONTCONFIG_FILE with includeSystem). */
32
+ export declare function fontconfigConf(options?: FontconfigConfOptions): string;
@@ -5,6 +5,7 @@
5
5
  import crypto from "node:crypto";
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
+ import { FONT_POLICY } from "@openpresentation/opf/font-policy";
8
9
  import { BUNDLED_FONT_MANIFEST } from "./font-manifest.js";
9
10
  import { previewFontLayout } from "./preview-fonts.js";
10
11
  import { scriptFontPackages } from "./script-font-pack.js";
@@ -81,3 +82,39 @@ export function copyPreviewFonts({ outDir, scripts = false, cwd, manifest = BUND
81
82
  fs.writeFileSync(path.join(outDir, "LICENSES.txt"), `Preview fonts served with <opf-deck>.\nEvery face is a pinned, unmodified copy, verified against its SHA-256.\n\n${notices.join("\n\n---\n\n")}\n`);
82
83
  return { copied, verified, bytes, files, packages: layout.length - missing.length, missing };
83
84
  }
85
+
86
+ /**
87
+ * RR-106: one fontconfig alias per font-policy family that OPF previews with a replacement face (Aptos to Intos, Calibri to Carlito,
88
+ * Arial to Arimo, ...): with the preview fonts installed, an app that resolves fonts through fontconfig (LibreOffice on Linux) then
89
+ * draws each family with the face OPF measured it with. Returns [{ family, prefer, compatibility }] (compatibility "metric" when the
90
+ * replacement has the original's advances, else "visual").
91
+ */
92
+ export function fontconfigAliases(policy = FONT_POLICY) {
93
+ const aliases = [];
94
+ for (const row of policy.families) {
95
+ const replacement = row.replacement;
96
+ const prefer = replacement?.family ?? replacement?.measured?.replacement;
97
+ if (typeof prefer !== "string" || !prefer || prefer.toLowerCase() === row.family.toLowerCase()) continue;
98
+ aliases.push({ family: row.family, prefer, compatibility: replacement.compatibility ?? (replacement.measured?.maxAbsWidthDelta === 0 ? "metric" : "visual") });
99
+ }
100
+ return aliases;
101
+ }
102
+
103
+ const escapeXml = (value) => String(value).replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[char]);
104
+
105
+ /**
106
+ * A fontconfig file with the aliases (fontconfigAliases) and, with `fontDir`, the directory of the preview fonts. As written it is a
107
+ * file for `~/.config/fontconfig/conf.d/`; `includeSystem` makes it a whole configuration for FONTCONFIG_FILE that includes the
108
+ * system's, and `cacheDir` names its cache. An alias replaces the family even where the original is installed.
109
+ */
110
+ export function fontconfigConf({ fontDir, aliases = fontconfigAliases(), includeSystem = false, cacheDir } = {}) {
111
+ const lines = ['<?xml version="1.0"?>', '<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">', "<!-- OPF preview fonts and font-policy aliases (opf-preview-fonts --fontconfig). -->", "<fontconfig>"];
112
+ if (includeSystem) lines.push(' <include ignore_missing="yes">/etc/fonts/fonts.conf</include>');
113
+ if (fontDir) lines.push(` <dir>${escapeXml(fontDir)}</dir>`);
114
+ if (cacheDir) lines.push(` <cachedir>${escapeXml(cacheDir)}</cachedir>`);
115
+ for (const alias of aliases) {
116
+ lines.push(` <match target="pattern"><test name="family" qual="any"><string>${escapeXml(alias.family)}</string></test><edit name="family" mode="assign" binding="same"><string>${escapeXml(alias.prefer)}</string></edit></match>`);
117
+ }
118
+ lines.push("</fontconfig>", "");
119
+ return lines.join("\n");
120
+ }
@@ -0,0 +1,46 @@
1
+ import {parseFontFamilies,parseFontWeight} from './pdf-style.js';
2
+ import {parseXml,textContent} from './pdf-xml.js';
3
+ // resvg does not follow the explicit RTL anchor/bidi of generated numeric list
4
+ // markers. Only the temporary raster SVG outlines those markers with the SAME
5
+ // layout/bidi/outline engine as vector PDF; returned logical SVG stays text.
6
+ const SELECTOR = /\bdata-opf-number-marker\s*=\s*["']rtl["']/;
7
+ const isMarker=node=>node.name==='text'&&node.attrs?.['data-opf-number-marker']==='rtl'&&node.attrs.direction==='rtl'&&node.attrs['unicode-bidi']==='isolate'&&node.attrs['aria-hidden']==='true'&&textContent(node).length>0;
8
+ const hasMarker=node=>isMarker(node)||(node.children??[]).some(child=>child.name&&hasMarker(child));
9
+
10
+ export async function outlineRasterMarkers(svg,{font,shape,report=()=>{},fail,strict=false}={}) {
11
+ if(!SELECTOR.test(svg))return svg;
12
+ // The substring is only a cheap prefilter. Prove an ACTUAL selected text node
13
+ // before constructing a library or reading any caller font file.
14
+ let tree;try{tree=parseXml(svg);}catch{return svg;}
15
+ if(!tree||!hasMarker(tree))return svg;
16
+ const refuse=({reason,fontFamily})=>{
17
+ const diagnostic={code:'raster-marker-unavailable',reason,...(fontFamily?{fontFamily}:{}),message:'An RTL numbered marker stays text because its exact raster face cannot safely be outlined; marker direction/placement parity is not established.'};
18
+ report(diagnostic);
19
+ if(strict)throw fail('raster-marker-unavailable',diagnostic.message);
20
+ };
21
+ if(font.loadSystemFonts){refuse({reason:'system-fonts'});return svg;}
22
+ const [{FontLibrary},{loadFontFiles},{outlineSlideText,prepareOutlineFace}]=await Promise.all([import('./pdf-fonts.js'),import('./font-files.js'),import('./text-paths.js')]);
23
+ const generics={serif:'Times New Roman','sans-serif':font.sansSerifFamily,monospace:font.monospaceFamily,cursive:'Comic Sans MS',fantasy:'Impact','system-ui':font.sansSerifFamily,'ui-sans-serif':font.sansSerifFamily,'ui-serif':'Times New Roman','ui-monospace':font.monospaceFamily};
24
+ const library=new FontLibrary({genericFamilies:generic=>[generics[generic]??font.defaultFontFamily]});
25
+ library.restricted=new Set();
26
+ // Exact raster inputs only: no replacement handle, SVG font URLs or system
27
+ // lookup. File bytes/name-table style match what fontdb receives. Ambiguous
28
+ // duplicate family/style faces refuse below, so directory-vs-file precedence
29
+ // cannot silently choose a different face than the rasterizer.
30
+ await loadFontFiles(library,font.fontFiles??[],font.fontDirs??[],()=>{},face=>prepareOutlineFace(library,face));
31
+ const validateFace=(face,style)=>{
32
+ const families=parseFontFamilies(style['font-family']),weight=parseFontWeight(style['font-weight'],400),italic=/italic|oblique/i.test(style['font-style']??'');
33
+ if(library.match(families,weight,italic)?.face!==face)return 'unresolved';
34
+ // Resolve generic names through the SAME mapping as matching. An earlier
35
+ // restricted actual family cannot be skipped merely because usable() hid
36
+ // it. Stop at the first actual match; later unused restrictions do not win.
37
+ for(const family of families){
38
+ const lower=family.toLowerCase(),actual=Object.hasOwn(generics,lower)?generics[lower]??font.defaultFontFamily:family;
39
+ if(library.restricted.has(actual.toLowerCase()))return 'restricted';
40
+ if(library.match([family],weight,italic))break;
41
+ }
42
+ return library.faces.some(other=>other!==face&&other.hash!==face.hash&&other.weight===face.weight&&other.italic===face.italic&&[...other.names].some(name=>face.names.has(name)))?'unresolved':undefined;
43
+ };
44
+ const result=outlineSlideText([svg],{library,shape,selectText:isMarker,onRefusal:refuse,fail,validateFace});
45
+ return result.defs?result.content[0].replace(/<svg\b(?:[^>"']|"[^"]*"|'[^']*')*>/,root=>root+result.defs):result.content[0];
46
+ }