@mark1russell7/typeset 0.1.3 → 0.1.5

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/src/fonts/font.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { fnv1a32 } from "@mark1russell7/rigor-generators";
2
2
  import type { Reader } from "./binary.ts";
3
+ import { readContextKerning } from "./context.ts";
3
4
  import { readGposKerning, readKernTable, IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, type PairLookup } from "./kerning.ts";
4
5
  import { readTables, type Decompress, type TableMap } from "./sfnt.ts";
5
6
  import { defaultFeatures, readGlyphFilter, readSubstitutions, type GlyphFilter, type SubstitutionLookup } from "./substitution.ts";
@@ -8,6 +9,7 @@ import { gvarAdvanceDeltas, readPointCounts, readTransformedPointCounts, type Gl
8
9
  import { instanceAdvances, normalize, readAxes, readVariationStore, type Axis, type Instance } from "./variations.ts";
9
10
  import { indicScripts, indicShaper } from "./indic.ts";
10
11
  import { joiningFeatures, joiningForms, joiningScripts, joiningStages } from "./joining.ts";
12
+ import { hasDefaultIgnorable, hasMark, isHidden, normalizeCodePoints, zeroedMarks } from "./normalize.ts";
11
13
  import { canvasSegments, canvasWords } from "./words.ts";
12
14
 
13
15
  /** The options of `readFont`. */
@@ -56,6 +58,10 @@ export interface Font {
56
58
  /** The source of the advances of this instance. The default instance and a font that is not variable use `hmtx`. */
57
59
  readonly advanceSource: AdvanceSource;
58
60
  readonly numGlyphs: number;
61
+ /** This value tells if the font has a GPOS table. */
62
+ readonly hasPositioning?: boolean;
63
+ /** This value tells if GDEF has glyph classes. */
64
+ readonly hasGlyphClasses?: boolean;
59
65
  /** This function gives the glyph of a code point, or 0 when the font has no glyph for it. */
60
66
  glyph(codePoint: number): number;
61
67
  /** This function gives the advance of a glyph in font units, as the shaper uses it. A mark has the advance 0. */
@@ -64,6 +70,8 @@ export interface Font {
64
70
  glyphClass(glyph: number): number;
65
71
  /** This function gives the pair lookups of the kerning for an OpenType script tag, for example `latn`. */
66
72
  kerning(script: string): readonly PairLookup[];
73
+ /** This function gives a test for each lookup of `kern` and `dist` that the model does not apply. */
74
+ contextKerning?(script: string): readonly ((glyphs: readonly number[]) => boolean)[];
67
75
  /** This function gives the GSUB lookups of a list of feature tags for an OpenType script tag, in the order of the lookup list. */
68
76
  substitutions(script: string, features: readonly string[]): readonly SubstitutionLookup[];
69
77
  /** This function gives the same font at another instance. It uses the tables that are already read. */
@@ -159,12 +167,15 @@ function build(parsed: Parsed, requested: Instance, modes: Modes): Font {
159
167
  const kern = tables.get("kern");
160
168
  const gsub = tables.get("GSUB");
161
169
  const lookups = new Map<string, readonly PairLookup[]>();
170
+ const contexts = new Map<string, ReturnType<NonNullable<Font["contextKerning"]>>>();
162
171
  const substitutions = new Map<string, readonly SubstitutionLookup[]>();
163
172
  const hashed = [tables.get("cmap"), gdef, gpos, kern, tables.get("fvar"), tables.get("avar"), tables.get("HVAR"), gsub];
164
173
  return {
165
174
  epoch: `${header.revision.toString(16).padStart(8, "0")}-${widthHash(header.unitsPerEm, coordinates, advances, hashed)}${deltas === "exact" ? "-exact" : ""}${advanceSource === "gvar" && hvar !== undefined ? "-gvar" : ""}${metrics !== undefined ? "-metrics" : ""}`,
166
175
  unitsPerEm: header.unitsPerEm,
167
176
  numGlyphs: header.numGlyphs,
177
+ hasPositioning: gpos !== undefined,
178
+ hasGlyphClasses: gdef !== undefined && gdef.u16(4) !== 0,
168
179
  axes,
169
180
  instance,
170
181
  coordinates,
@@ -181,11 +192,17 @@ function build(parsed: Parsed, requested: Instance, modes: Modes): Font {
181
192
  }
182
193
  return found;
183
194
  },
195
+ contextKerning(script) {
196
+ if (!contexts.has(script)) contexts.set(script, gpos === undefined ? [] : readContextKerning(gpos, script, parsed.filter, !noMarkZero.includes(script)));
197
+ return contexts.get(script)!;
198
+ },
184
199
  substitutions(script, features) {
185
200
  const key = `${script} ${features.join(",")}`;
186
201
  let found = substitutions.get(key);
187
202
  if (found === undefined) {
188
- found = gsub === undefined ? [] : readSubstitutions(gsub, script, features, parsed.filter);
203
+ // The Indic shaper of HarfBuzz keeps the joiners visible, so only the other shapers skip them
204
+ const joiners = script === "deva" ? [] : [characters.get(0x200c) ?? 0, characters.get(0x200d) ?? 0].filter((glyph) => glyph !== 0);
205
+ found = gsub === undefined ? [] : readSubstitutions(gsub, script, features, { ...parsed.filter, joiners });
189
206
  substitutions.set(key, found);
190
207
  }
191
208
  return found;
@@ -311,26 +328,50 @@ export function shapingOf(font: Font, options: MeasureOptions): Shaping {
311
328
  return { script, features, shaper: options.joining !== false && joiningScripts.includes(script) ? "joining" : "plain", kerning };
312
329
  }
313
330
 
331
+ /** The bits of a mask: all the glyphs, a default ignorable, a mark with no advance. */
332
+ const GLOBAL_MASK = 0x80;
333
+ const IGNORABLE_MASK = 0x100;
334
+ const ZEROED_MASK = 0x200;
335
+
336
+ /** The scripts whose shaper in HarfBuzz has no fallback mark position. */
337
+ const noFallbackPosition: readonly string[] = ["thai", "lao ", "khmr", "mymr", "mym2", ...indicScripts];
338
+ /** The scripts whose shaper in HarfBuzz does not zero the marks. */
339
+ const noMarkZero: readonly string[] = ["hang", "khmr", ...indicScripts];
340
+
314
341
  /** The GSUB pass of one set of options: a function that gives the glyphs of one word, and the kerning lookups. */
315
342
  function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: string) => number[]; kerning: readonly PairLookup[] } {
316
343
  const { script, features, shaper, kerning } = shapingOf(font, options);
317
344
  if (shaper === "indic") return { substitute: indicShaper(font, script, features), kerning };
345
+ const classes = font.hasGlyphClasses === false && !noMarkZero.includes(script);
346
+ const fallback = font.hasPositioning === false && !noFallbackPosition.includes(script);
318
347
  const joins = shaper === "joining";
319
348
  const lookups = joins ? [] : font.substitutions(script, features);
320
349
  const stages = joins ? joiningStages(features, features.includes("rclt") && font.substitutions(script, ["rclt"]).length > 0).map((stage) => ({ stage, lookups: font.substitutions(script, stage.features) })) : [];
350
+ // The shaper of Hangul has its own normalization in HarfBuzz: the mode `NONE` keeps each character with a glyph
351
+ const normalizes = script !== "hang";
352
+ const rules = { hasGlyph: (codePoint: number) => font.glyph(codePoint) !== 0, shortCircuit: true };
321
353
  const substitute = (word: string): number[] => {
322
- const codePoints = [...word].map((character) => character.codePointAt(0)!);
323
- const wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
324
- for (const lookup of lookups) lookup.apply(wordGlyphs);
325
- if (joins) {
326
- // Each glyph has the bit of its joining form, and the bit 7 for the features of all the glyphs
327
- const masks = joiningForms(codePoints).map((form) => 0x80 | (form === undefined ? 0 : 1 << joiningFeatures.indexOf(form)));
328
- for (const { stage, lookups: stageLookups } of stages) {
329
- const mask = stage.form === undefined ? 0x80 : 1 << joiningFeatures.indexOf(stage.form);
330
- for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
331
- }
354
+ let codePoints = [...word].map((character) => character.codePointAt(0)!);
355
+ let wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
356
+ if (normalizes && (hasMark(word) || wordGlyphs.includes(0))) {
357
+ codePoints = normalizeCodePoints(codePoints, rules);
358
+ wordGlyphs = codePoints.map((codePoint) => font.glyph(codePoint));
332
359
  }
333
- return wordGlyphs;
360
+ const hides = hasDefaultIgnorable(word);
361
+ const zeroed = (classes || fallback) && hasMark(word) ? zeroedMarks(codePoints, classes, fallback) : [];
362
+ const forms = joins ? joiningForms(codePoints) : [];
363
+ const masks = joins || hides || zeroed.length > 0 ? codePoints.map((codePoint, i) => GLOBAL_MASK | (forms[i] === undefined ? 0 : 1 << joiningFeatures.indexOf(forms[i])) | (hides && isHidden(codePoint) ? IGNORABLE_MASK : 0) | (zeroed[i] === true ? ZEROED_MASK : 0)) : undefined;
364
+ const before = hides ? [...wordGlyphs] : [];
365
+ for (const lookup of lookups) lookup.apply(wordGlyphs, masks, GLOBAL_MASK);
366
+ for (const { stage, lookups: stageLookups } of stages) {
367
+ const mask = stage.form === undefined ? GLOBAL_MASK : 1 << joiningFeatures.indexOf(stage.form);
368
+ for (const lookup of stageLookups) lookup.apply(wordGlyphs, masks, mask);
369
+ }
370
+ // A new glyph has the mask of its source: a default ignorable with a new id is not hidden
371
+ return masks === undefined ? wordGlyphs : wordGlyphs.map((glyph, i) => {
372
+ const mask = masks[i] ?? 0;
373
+ return (mask & ZEROED_MASK) !== 0 || ((mask & IGNORABLE_MASK) !== 0 && before.includes(glyph)) ? ~glyph : glyph;
374
+ });
334
375
  };
335
376
  return { substitute, kerning };
336
377
  }
@@ -342,6 +383,12 @@ function shaperOf(font: Font, options: MeasureOptions): { substitute: (word: str
342
383
  * the joining forms of each word, in the stages of `joiningStages`. A script of `indicScripts` uses `indicShaper`.
343
384
  */
344
385
  export function glyphAdvances(font: Font, text: string, options: MeasureOptions = {}): { glyphs: number[]; advances: number[] } {
386
+ const { glyphs, advances } = shapedAdvances(font, text, options);
387
+ return { glyphs: glyphs.map((glyph) => (glyph < 0 ? ~glyph : glyph)), advances };
388
+ }
389
+
390
+ /** This function is `glyphAdvances`, with `~glyph` for a hidden glyph. It has no advance, and the kerning skips it. */
391
+ function shapedAdvances(font: Font, text: string, options: MeasureOptions): { glyphs: number[]; advances: number[] } {
345
392
  const { substitute, kerning } = shaperOf(font, options);
346
393
  const canvas = options.shaping === "canvas";
347
394
  const glyphs: number[] = [];
@@ -389,7 +436,7 @@ function kerningPosition(value: number, delta: number, scale: PositionScale): nu
389
436
  function kern(font: Font, lookups: readonly PairLookup[], glyphs: readonly number[], advances: number[], positions?: number[], scale?: PositionScale): void {
390
437
  for (const lookup of lookups) {
391
438
  const next = (from: number): number => {
392
- for (let j = from; j < glyphs.length; j++) if (!(lookup.skip?.(glyphs[j]!) ?? skips(lookup.flags, font.glyphClass(glyphs[j]!)))) return j;
439
+ for (let j = from; j < glyphs.length; j++) if (glyphs[j]! >= 0 && !(lookup.skip?.(glyphs[j]!) ?? skips(lookup.flags, font.glyphClass(glyphs[j]!)))) return j;
393
440
  return -1;
394
441
  };
395
442
  let i = next(0);
@@ -441,7 +488,7 @@ function float32Width(font: Font, text: string, size: number, options: MeasureOp
441
488
  */
442
489
  export function measureWidth(font: Font, text: string, size: number, options: MeasureOptions = {}): number {
443
490
  if (options.sum === "float32" && options.rounding !== "pixel") return float32Width(font, text, size, options);
444
- const { glyphs, advances } = glyphAdvances(font, text, options);
491
+ const { glyphs, advances } = shapedAdvances(font, text, options);
445
492
  if (options.rounding === "pixel") {
446
493
  const scale = size / font.unitsPerEm;
447
494
  let px = 0;
@@ -1,5 +1,6 @@
1
1
  export { readFont, measureWidth, glyphAdvances, shapingWords, type AdvanceSource, type Font, type ReadOptions, type MeasureOptions } from "./font.ts";
2
2
  export { widthBound, type WidthBound } from "./bound.ts";
3
+ export { shapingRisks, type ShapingRisk, type ShapingRiskCode } from "./risks.ts";
3
4
  export { canvasSegments, canvasWords, isCjkIdeographOrSymbol } from "./words.ts";
4
5
  export { bidiLevels, visualOrder } from "./bidi.ts";
5
6
  export { indicScripts, indicShaper, indicSyllables, type IndicSyllableType } from "./indic.ts";
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * The Indic shaper of HarfBuzz for the script Devanagari. This module follows `hb-ot-shaper-indic.cc`, the syllable machine
3
3
  * of `hb-ot-shaper-indic-machine.rl`, the dotted circles of `hb-ot-shaper-syllabic.cc` and `hb-ot-shaper-vowel-constraints.cc`,
4
- * and the normalization of `hb-ot-shape-normalize.cc`. The table of the categories comes from `hb-ot-shaper-indic-table.cc`.
4
+ * and the rules of the mode `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT`. The table of the categories comes from `hb-ot-shaper-indic-table.cc`.
5
5
  */
6
6
  import type { Font } from "./font.ts";
7
+ import { normalForms, normalizeCodePoints, type NormalForms } from "./normalize.ts";
7
8
  import { LIGATED, MULTIPLIED, SUBSTITUTED, type GlyphInfo } from "./substitution.ts";
9
+ import { isHidden } from "./normalize.ts";
8
10
 
9
11
  /** The OpenType script tags that use the Indic shaper in this model. */
10
12
  export const indicScripts: readonly string[] = ["deva"];
@@ -85,29 +87,9 @@ function indicProperties(codePoint: number): [number, number] {
85
87
  return [X, END];
86
88
  }
87
89
 
88
- /**
89
- * The canonical combining classes of the marks of the Devanagari blocks that are not 0. The normalization uses them to
90
- * sort the marks and to block a composition. A mark of another block has the class 0 in this model.
91
- */
92
- const combiningClasses: readonly number[] = [
93
- 0x93c, 0x93c, 7, 0x94d, 0x94d, 9, 0x951, 0x951, 230, 0x952, 0x952, 220, 0x953, 0x954, 230, 0x1cd0, 0x1cd2, 230,
94
- 0x1cd4, 0x1cd4, 1, 0x1cd5, 0x1cd9, 220, 0x1cda, 0x1cdb, 230, 0x1cdc, 0x1cdf, 220, 0x1ce0, 0x1ce0, 230, 0x1ce2, 0x1ce8, 1,
95
- 0x1ced, 0x1ced, 220, 0x1cf4, 0x1cf4, 230, 0x1cf8, 0x1cf9, 230, 0xa8e0, 0xa8f1, 230,
96
- ];
97
-
98
- function combiningClass(codePoint: number): number {
99
- for (let i = 0; i < combiningClasses.length; i += 3) if (codePoint >= combiningClasses[i]! && codePoint <= combiningClasses[i + 1]!) return combiningClasses[i + 2]!;
100
- return 0;
101
- }
102
-
103
- const unicodeMark = /\p{M}/u;
104
90
  /** The general categories from `FORMAT` to `NON_SPACING_MARK` of HarfBuzz: a letter, a mark, or a format or other code point. */
105
91
  const letterOrMark = /[\p{L}\p{M}\p{Cf}\p{Cn}\p{Co}\p{Cs}]/u;
106
92
 
107
- function isMark(codePoint: number): boolean {
108
- return unicodeMark.test(String.fromCodePoint(codePoint));
109
- }
110
-
111
93
  /**
112
94
  * This function inserts a dotted circle in each vowel sequence of Devanagari that looks like another vowel, as
113
95
  * `_hb_preprocess_text_vowel_constraints` does.
@@ -134,90 +116,12 @@ function vowelConstraints(codePoints: readonly number[]): number[] {
134
116
  return out;
135
117
  }
136
118
 
137
- /**
138
- * This function normalizes the code points as HarfBuzz does in the mode `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT`. It
139
- * decomposes each character that has a canonical decomposition when the font has the glyphs of its parts. The letter
140
- * U+0931 does not decompose. A text with a mark after its first character then gets more steps. The function sorts the
141
- * marks, and composes each mark with its starter again when the font has the glyph of the composite.
142
- */
143
- function normalize(codePoints: readonly number[], hasGlyph: (codePoint: number) => boolean): number[] {
144
- const allSimple = !codePoints.some((codePoint, i) => i > 0 && isMark(codePoint));
145
- const decomposed = codePoints.flatMap((codePoint) => decomposition(codePoint, hasGlyph));
146
- if (allSimple) return decomposed;
147
- // A stable sort of each run of marks with a class that is not 0
148
- for (let i = 1; i < decomposed.length; i++) {
149
- for (let j = i; j > 0; j--) {
150
- const before = combiningClass(decomposed[j - 1]!);
151
- const after = combiningClass(decomposed[j]!);
152
- if (after === 0 || before <= after) break;
153
- [decomposed[j - 1], decomposed[j]] = [decomposed[j]!, decomposed[j - 1]!];
154
- }
155
- }
156
- const out: number[] = decomposed.slice(0, 1);
157
- let starter = 0;
158
- for (let i = 1; i < decomposed.length; i++) {
159
- const codePoint = decomposed[i]!;
160
- if (isMark(codePoint) && (starter === out.length - 1 || combiningClass(out[out.length - 1]!) < combiningClass(codePoint))) {
161
- const composed = compose(out[starter]!, codePoint);
162
- if (composed !== undefined && hasGlyph(composed)) {
163
- out[starter] = composed;
164
- continue;
165
- }
166
- }
167
- out.push(codePoint);
168
- if (combiningClass(codePoint) === 0) starter = out.length - 1;
169
- }
170
- return out;
171
- }
172
-
173
- /** This function gives the code points of a character after the decomposition of `normalize`. */
174
- function decomposition(codePoint: number, hasGlyph: (codePoint: number) => boolean): number[] {
175
- const parts = codePoint === 0x931 ? [codePoint] : [...String.fromCodePoint(codePoint).normalize("NFD")].map((part) => part.codePointAt(0)!);
176
- return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
177
- }
178
-
179
- /** The code points that `normalize` and `vowelConstraints` can give for a set of characters. */
180
- export interface IndicForms {
181
- /** The parts of each character of the set after the decomposition. A character with no decomposition is its one part. */
182
- readonly parts: ReadonlyMap<number, readonly number[]>;
183
- /** The composites of each code point: the code points that it becomes when a mark composes with it. */
184
- readonly composites: ReadonlyMap<number, readonly number[]>;
185
- /** All the code points that the shaper can see: the set, its parts, the dotted circle and each composite. */
186
- readonly codePoints: ReadonlySet<number>;
187
- }
188
-
189
- /**
190
- * This function gives the code points that the normalization can give for the characters `characters`. A composite is
191
- * not always in the set: a nukta that follows U+0928 gives U+0929. The function repeats until no new composite appears.
192
- */
193
- export function indicForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean): IndicForms {
194
- const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph)]));
195
- const codePoints = new Set([...parts.values()].flat());
196
- for (const codePoint of characters) codePoints.add(codePoint);
197
- codePoints.add(0x25cc);
198
- const composites = new Map<number, number[]>();
199
- for (let size = 0; size !== codePoints.size; ) {
200
- size = codePoints.size;
201
- const marks = [...codePoints].filter(isMark);
202
- for (const starter of codePoints) {
203
- for (const mark of marks) {
204
- const composed = compose(starter, mark);
205
- if (composed === undefined || !hasGlyph(composed)) continue;
206
- const known = composites.get(starter) ?? [];
207
- if (!known.includes(composed)) composites.set(starter, [...known, composed]);
208
- codePoints.add(composed);
209
- }
210
- }
211
- }
212
- return { parts, composites, codePoints };
213
- }
119
+ /** The code points of Devanagari that do not decompose. */
120
+ const kept: ReadonlySet<number> = new Set([0x931]);
214
121
 
215
- /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
216
- function compose(first: number, second: number): number | undefined {
217
- if (isMark(first)) return undefined;
218
- const composed = [(String.fromCodePoint(first) + String.fromCodePoint(second)).normalize("NFC")];
219
- const [single, ...rest] = [...composed[0]!];
220
- return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
122
+ /** This function gives the code points that `normalizeCodePoints` and `vowelConstraints` can give for a set of characters. */
123
+ export function indicForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean): NormalForms {
124
+ return normalForms(new Set([...characters, 0x25cc]), hasGlyph, kept);
221
125
  }
222
126
 
223
127
  // The syllable machine, with one letter for each category
@@ -596,7 +500,7 @@ export function indicShaper(font: Font, script: string, features: readonly strin
596
500
  };
597
501
 
598
502
  return (word: string): number[] => {
599
- const codePoints = normalize(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), (codePoint) => font.glyph(codePoint) !== 0);
503
+ const codePoints = normalizeCodePoints(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), { hasGlyph: (codePoint) => font.glyph(codePoint) !== 0, shortCircuit: false, kept });
600
504
  const run: Run = { glyphs: codePoints.map((codePoint) => font.glyph(codePoint)), infos: [] };
601
505
  for (const codePoint of codePoints) {
602
506
  const [category, position] = indicProperties(codePoint);
@@ -621,6 +525,6 @@ export function indicShaper(font: Font, script: string, features: readonly strin
621
525
  for (const { lookups, mask } of basic) for (const lookup of lookups) lookup.applyInfos(run.glyphs, run.infos, mask, true);
622
526
  for (const [start, end] of syllables(run.infos)) finalReordering(run, start, end);
623
527
  for (const { lookup, mask, perSyllable } of last) lookup.applyInfos(run.glyphs, run.infos, mask, perSyllable);
624
- return run.glyphs;
528
+ return run.glyphs.map((glyph, i) => ((run.infos[i]!.props & SUBSTITUTED) === 0 && isHidden(run.infos[i]!.codePoint) ? ~glyph : glyph));
625
529
  };
626
530
  }
@@ -44,8 +44,8 @@ const joiningTable: readonly number[] = [
44
44
  0x855, 0x855, D, 0x856, 0x858, R, 0x860, 0x860, D, 0x861, 0x861, U, 0x862, 0x865, D, 0x866, 0x866, U, 0x867, 0x867, R,
45
45
  0x868, 0x868, D, 0x869, 0x86a, R, 0x870, 0x882, R, 0x883, 0x885, D, 0x886, 0x886, D, 0x887, 0x888, U, 0x889, 0x88d, D,
46
46
  0x88e, 0x88e, R, 0x88f, 0x88f, D, 0x890, 0x891, U, 0x8a0, 0x8a9, D, 0x8aa, 0x8ac, R, 0x8ad, 0x8ad, U, 0x8ae, 0x8ae, R,
47
- 0x8af, 0x8b0, D, 0x8b1, 0x8b2, R, 0x8b3, 0x8b8, D, 0x8b9, 0x8b9, R, 0x8ba, 0x8c8, D, 0x8e2, 0x8e2, U, 0x200c, 0x200c, U,
48
- 0x200d, 0x200d, D,
47
+ 0x8af, 0x8b0, D, 0x8b1, 0x8b2, R, 0x8b3, 0x8b8, D, 0x8b9, 0x8b9, R, 0x8ba, 0x8c8, D, 0x8e2, 0x8e2, U, 0x180e, 0x180e, U, 0x200c, 0x200c, U,
48
+ 0x200d, 0x200d, D, 0x2066, 0x2069, U,
49
49
  ];
50
50
 
51
51
  const transparent = /[\p{Mn}\p{Me}\p{Cf}]/u;
@@ -171,25 +171,46 @@ const pairFeatures = new Set(["kern", "dist"]);
171
171
  /** The lookup flag that selects a mark filtering set of GDEF. */
172
172
  const USE_MARK_FILTERING_SET = 0x10;
173
173
 
174
- /**
175
- * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
176
- * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
177
- */
178
- export function readGposKerning(gpos: Reader, script: string, store?: VariationStore, filter?: GlyphFilter): PairLookup[] {
179
- const scripts = gpos.part(gpos.u16(4));
180
- const features = gpos.part(gpos.u16(6));
181
- const lookups = gpos.part(gpos.u16(8));
182
- const scriptCount = scripts.u16(0);
183
- let langSys: Reader | undefined;
174
+ /** This function gives the test of the glyphs that a lookup skips. */
175
+ export function lookupSkip(lookup: Reader, flags: number, filter: GlyphFilter): (glyph: number) => boolean {
176
+ const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
177
+ return (glyph) => {
178
+ const kind = filter.glyphClass(glyph);
179
+ if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
180
+ if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
181
+ if (kind !== 3) return false;
182
+ if ((flags & IGNORE_MARKS) !== 0) return true;
183
+ if (markSet >= 0) return !filter.inMarkSet(markSet, glyph);
184
+ const attach = flags >> 8;
185
+ return attach !== 0 && filter.markAttachClass(glyph) !== attach;
186
+ };
187
+ }
188
+
189
+ /** This function gives the subtables of a lookup with their types, after each extension of the type `extension`. */
190
+ export function subtablesOf(lookup: Reader, extension: number): (readonly [number, Reader])[] {
191
+ return Array.from({ length: lookup.u16(4) }, (_, s) => {
192
+ const subtable = lookup.part(lookup.u16(6 + s * 2));
193
+ return lookup.u16(0) === extension ? [subtable.u16(2), subtable.part(subtable.u32(4))] : [lookup.u16(0), subtable];
194
+ });
195
+ }
196
+
197
+ /** This function gives the default language system of a table for a script. */
198
+ export function languageSystem(table: Reader, script: string): Reader | undefined {
199
+ const scripts = table.part(table.u16(4));
184
200
  for (const wanted of scriptTags(script)) {
185
- for (let i = 0; i < scriptCount && langSys === undefined; i++) {
201
+ for (let i = 0; i < scripts.u16(0); i++) {
186
202
  if (scripts.tag(2 + i * 6) !== wanted) continue;
187
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
188
- const fallback = table.u16(0);
189
- if (fallback !== 0) langSys = table.part(fallback);
203
+ const entry = scripts.part(scripts.u16(2 + i * 6 + 4));
204
+ if (entry.u16(0) !== 0) return entry.part(entry.u16(0));
190
205
  }
191
- if (langSys !== undefined) break;
192
206
  }
207
+ return undefined;
208
+ }
209
+
210
+ /** This function gives the indices of the lookups of `kern` and `dist` for a script, in the order of the lookup list. */
211
+ export function pairLookupIndices(gpos: Reader, script: string): number[] {
212
+ const features = gpos.part(gpos.u16(6));
213
+ const langSys = languageSystem(gpos, script);
193
214
  if (langSys === undefined) return [];
194
215
  const indices = new Set<number>();
195
216
  const featureCount = langSys.u16(4);
@@ -199,29 +220,22 @@ export function readGposKerning(gpos: Reader, script: string, store?: VariationS
199
220
  const feature = features.part(features.u16(record + 4));
200
221
  for (let k = 0; k < feature.u16(2); k++) indices.add(feature.u16(4 + k * 2));
201
222
  }
202
- return [...indices].sort((a, b) => a - b).flatMap((index) => {
223
+ return [...indices].sort((a, b) => a - b);
224
+ }
225
+
226
+ /**
227
+ * This function gives the pair lookups of the features `kern` and `dist` of GPOS for a script, in the order of the lookup
228
+ * list. The store gives the deltas of a variable font at its instance. The filter gives the mark filtering sets of GDEF.
229
+ */
230
+ export function readGposKerning(gpos: Reader, script: string, store?: VariationStore, filter?: GlyphFilter): PairLookup[] {
231
+ const lookups = gpos.part(gpos.u16(8));
232
+ return pairLookupIndices(gpos, script).flatMap((index) => {
203
233
  const lookup = lookups.part(lookups.u16(2 + index * 2));
204
234
  const subtables: PairSubtable[] = [];
205
- const type = lookup.u16(0);
206
- for (let s = 0; s < lookup.u16(4); s++) {
207
- let subtable = lookup.part(lookup.u16(6 + s * 2));
208
- let subtype = type;
209
- if (type === 9) {
210
- subtype = subtable.u16(2);
211
- subtable = subtable.part(subtable.u32(4));
212
- }
213
- if (subtype === 2) subtables.push(pairSubtable(subtable, store));
214
- }
235
+ for (const [subtype, subtable] of subtablesOf(lookup, 9)) if (subtype === 2) subtables.push(pairSubtable(subtable, store));
215
236
  if (subtables.length === 0) return [];
216
237
  const flags = lookup.u16(2);
217
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 && filter !== undefined ? lookup.u16(6 + lookup.u16(4) * 2) : -1;
218
- const skip = markSet < 0 ? undefined : (glyph: number): boolean => {
219
- const kind = filter!.glyphClass(glyph);
220
- if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
221
- if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
222
- if (kind !== 3) return false;
223
- return (flags & IGNORE_MARKS) !== 0 || !filter!.inMarkSet(markSet, glyph);
224
- };
238
+ const skip = (flags & USE_MARK_FILTERING_SET) !== 0 && filter !== undefined ? lookupSkip(lookup, flags, filter) : undefined;
225
239
  return [{
226
240
  flags,
227
241
  ...(skip === undefined ? {} : { skip }),
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The Unicode normalization of HarfBuzz, from `hb-ot-shape-normalize.cc`. HarfBuzz decomposes each cluster of a base and its marks.
3
+ * It then sorts the marks, and composes each mark with its base when the font has the glyph of the composite.
4
+ */
5
+
6
+ const unicodeMark = /\p{M}/u;
7
+ const nonspacingMark = /\p{Mn}/u;
8
+
9
+ /**
10
+ * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
11
+ * for example the shadda comes first. Each other pair of marks uses the canonical order.
12
+ */
13
+ const sortClasses: ReadonlyMap<number, number> = new Map([
14
+ [0x5b0, 22], [0x5b1, 15], [0x5b2, 16], [0x5b3, 17], [0x5b4, 23], [0x5b5, 18], [0x5b6, 19], [0x5b7, 20], [0x5b8, 21], [0x5b9, 14],
15
+ [0x5ba, 14], [0x5bb, 24], [0x5bc, 12], [0x5bd, 25], [0x5bf, 13], [0x5c1, 10], [0x5c2, 11], [0x5c7, 21], [0xfb1e, 26],
16
+ [0x618, 31], [0x619, 32], [0x61a, 33], [0x64b, 28], [0x64c, 29], [0x64d, 30], [0x64e, 31], [0x64f, 32], [0x650, 33],
17
+ [0x651, 27], [0x652, 34], [0x670, 35], [0x8f0, 28], [0x8f1, 29], [0x8f2, 30],
18
+ ]);
19
+
20
+ /** The default ignorables of `hb-unicode.hh`. This set is not the Unicode property: it does not have the Hangul fillers. */
21
+ const defaultIgnorable = /[\u00ad\u034f\u061c\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufe00-\ufe0f\ufeff\ufff0-\ufff8\u{1d173}-\u{1d17a}\u{e0000}-\u{e0fff}]/u;
22
+
23
+ /** This function tells if a text has a default ignorable. */
24
+ export function hasDefaultIgnorable(text: string): boolean {
25
+ return defaultIgnorable.test(text);
26
+ }
27
+
28
+ /** This function tells if the model hides a code point. A hidden code point takes no advance, and the kerning skips it. */
29
+ export function isHidden(codePoint: number): boolean {
30
+ return hasDefaultIgnorable(String.fromCodePoint(codePoint));
31
+ }
32
+
33
+ /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
34
+ function isMark(codePoint: number): boolean {
35
+ return codePoint >= 0x300 && unicodeMark.test(String.fromCodePoint(codePoint));
36
+ }
37
+
38
+ /** This function tells if a text has a mark of Unicode. */
39
+ export function hasMark(text: string): boolean {
40
+ return unicodeMark.test(text);
41
+ }
42
+
43
+ /** This function tells which code points take no advance: nonspacing marks with `classes`, marks with a class after a base with `fallback`. */
44
+ export function zeroedMarks(codePoints: readonly number[], classes: boolean, fallback: boolean): boolean[] {
45
+ let base = false;
46
+ return codePoints.map((codePoint) => {
47
+ const character = String.fromCodePoint(codePoint);
48
+ if (!isMark(codePoint)) {
49
+ base = true;
50
+ return false;
51
+ }
52
+ return (classes && nonspacingMark.test(character) && !hasDefaultIgnorable(character)) || (fallback && base && !isStarter(codePoint));
53
+ });
54
+ }
55
+
56
+ function decomposed(codePoint: number): string {
57
+ return String.fromCodePoint(codePoint).normalize("NFD");
58
+ }
59
+
60
+ /**
61
+ * This function tells if the mark `second` sorts before the mark `first`. That is true when the class of `first` is larger
62
+ * than the class of `second`, and neither class is 0. The form NFD of JavaScript gives the canonical order, so no table is needed.
63
+ */
64
+ function reorders(first: number, second: number): boolean {
65
+ const firstClass = sortClasses.get(first);
66
+ const secondClass = sortClasses.get(second);
67
+ if (firstClass !== undefined && secondClass !== undefined) return firstClass > secondClass;
68
+ const text = decomposed(first) + decomposed(second);
69
+ return text.normalize("NFD") !== text;
70
+ }
71
+
72
+ /** This function tells if a code point has the combining class 0. U+0345 has the largest class of Unicode. */
73
+ function isStarter(codePoint: number): boolean {
74
+ return !isMark(codePoint) || (codePoint !== 0x345 && !reorders(0x345, codePoint));
75
+ }
76
+
77
+ /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
78
+ function compose(first: number, second: number): number | undefined {
79
+ if (isMark(first)) return undefined;
80
+ const [single, ...rest] = [...String.fromCodePoint(first, second).normalize("NFC")];
81
+ return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
82
+ }
83
+
84
+ /**
85
+ * This function gives the code points of a character after the decomposition. A character keeps its form when the font has
86
+ * no glyph for one of its parts, or when the set `kept` has the character.
87
+ */
88
+ function decomposition(codePoint: number, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number>): number[] {
89
+ const parts = kept.has(codePoint) ? [codePoint] : Array.from(decomposed(codePoint), (part) => part.codePointAt(0)!);
90
+ return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
91
+ }
92
+
93
+ /** The rules of one shaper for `normalizeCodePoints`. */
94
+ export interface NormalizeRules {
95
+ /** This function tells if the font has a glyph for a code point. */
96
+ readonly hasGlyph: (codePoint: number) => boolean;
97
+ /**
98
+ * When this is `true`, a character with a glyph and with no mark near it keeps its form, as the mode `COMPOSED_DIACRITICS`
99
+ * of HarfBuzz does. When this is `false`, each character decomposes, as `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT` does.
100
+ */
101
+ readonly shortCircuit: boolean;
102
+ /** The code points that do not decompose. */
103
+ readonly kept?: ReadonlySet<number>;
104
+ }
105
+
106
+ /**
107
+ * This function normalizes code points as HarfBuzz does. It decomposes the characters by `rules`. A text with a mark after
108
+ * its first character then gets more steps. The function sorts the marks, and composes each mark with its starter again
109
+ * when the font has the glyph of the composite. A mark between them with the same class or a larger class blocks this.
110
+ */
111
+ export function normalizeCodePoints(codePoints: readonly number[], rules: NormalizeRules): number[] {
112
+ const { hasGlyph, shortCircuit, kept = new Set<number>() } = rules;
113
+ const marked = codePoints.map(isMark);
114
+ const parts = codePoints.flatMap((codePoint, i) => {
115
+ const simple = marked[i + 1] !== true && !(i > 0 && marked[i]!);
116
+ return shortCircuit && simple && hasGlyph(codePoint) ? [codePoint] : decomposition(codePoint, hasGlyph, kept);
117
+ });
118
+ if (!marked.slice(1).includes(true)) return parts;
119
+ // A stable sort of each run of marks with a class that is not 0
120
+ for (let i = 1; i < parts.length; i++) {
121
+ for (let j = i; j > 0 && isMark(parts[j - 1]!) && isMark(parts[j]!) && reorders(parts[j - 1]!, parts[j]!); j--) {
122
+ [parts[j - 1], parts[j]] = [parts[j]!, parts[j - 1]!];
123
+ }
124
+ }
125
+ const out: number[] = parts.slice(0, 1);
126
+ let starter = 0;
127
+ for (let i = 1; i < parts.length; i++) {
128
+ const codePoint = parts[i]!;
129
+ if (isMark(codePoint) && (starter === out.length - 1 || reorders(codePoint, out[out.length - 1]!))) {
130
+ const composed = compose(out[starter]!, codePoint);
131
+ if (composed !== undefined && hasGlyph(composed)) {
132
+ out[starter] = composed;
133
+ continue;
134
+ }
135
+ }
136
+ out.push(codePoint);
137
+ if (isStarter(codePoint)) starter = out.length - 1;
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /** The code points that `normalizeCodePoints` can give for a set of characters. */
143
+ export interface NormalForms {
144
+ /** The parts of each character of the set after the decomposition. A character with no decomposition is its one part. */
145
+ readonly parts: ReadonlyMap<number, readonly number[]>;
146
+ /** The composites of each code point: the code points that it becomes when a mark composes with it. */
147
+ readonly composites: ReadonlyMap<number, readonly number[]>;
148
+ /** All the code points that the shaper can see: the set, its parts and each composite. */
149
+ readonly codePoints: ReadonlySet<number>;
150
+ }
151
+
152
+ /** This function gives the forms of a set of characters. It repeats the compositions until the set of code points is stable. */
153
+ export function normalForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number> = new Set()): NormalForms {
154
+ const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph, kept)]));
155
+ const codePoints = new Set([...characters, ...[...parts.values()].flat()]);
156
+ const composites = new Map<number, number[]>();
157
+ for (let size = 0; size !== codePoints.size; ) {
158
+ size = codePoints.size;
159
+ const marks = [...codePoints].filter(isMark);
160
+ for (const starter of codePoints) {
161
+ for (const mark of marks) {
162
+ const composed = compose(starter, mark);
163
+ if (composed === undefined || !hasGlyph(composed)) continue;
164
+ const known = composites.get(starter) ?? [];
165
+ if (!known.includes(composed)) composites.set(starter, [...known, composed]);
166
+ codePoints.add(composed);
167
+ }
168
+ }
169
+ }
170
+ return { parts, composites, codePoints };
171
+ }