@mark1russell7/typeset 0.1.2 → 0.1.4

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,9 +1,10 @@
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";
8
9
 
9
10
  /** The OpenType script tags that use the Indic shaper in this model. */
@@ -85,29 +86,9 @@ function indicProperties(codePoint: number): [number, number] {
85
86
  return [X, END];
86
87
  }
87
88
 
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
89
  /** The general categories from `FORMAT` to `NON_SPACING_MARK` of HarfBuzz: a letter, a mark, or a format or other code point. */
105
90
  const letterOrMark = /[\p{L}\p{M}\p{Cf}\p{Cn}\p{Co}\p{Cs}]/u;
106
91
 
107
- function isMark(codePoint: number): boolean {
108
- return unicodeMark.test(String.fromCodePoint(codePoint));
109
- }
110
-
111
92
  /**
112
93
  * This function inserts a dotted circle in each vowel sequence of Devanagari that looks like another vowel, as
113
94
  * `_hb_preprocess_text_vowel_constraints` does.
@@ -134,58 +115,12 @@ function vowelConstraints(codePoints: readonly number[]): number[] {
134
115
  return out;
135
116
  }
136
117
 
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: number[] = [];
146
- for (const codePoint of codePoints) {
147
- const parts = codePoint === 0x931 ? [codePoint] : [...String.fromCodePoint(codePoint).normalize("NFD")].map((part) => part.codePointAt(0)!);
148
- if (parts.length > 1 || parts[0] !== codePoint) {
149
- if (parts.every(hasGlyph)) {
150
- decomposed.push(...parts);
151
- continue;
152
- }
153
- }
154
- decomposed.push(codePoint);
155
- }
156
- if (allSimple) return decomposed;
157
- // A stable sort of each run of marks with a class that is not 0
158
- for (let i = 1; i < decomposed.length; i++) {
159
- for (let j = i; j > 0; j--) {
160
- const before = combiningClass(decomposed[j - 1]!);
161
- const after = combiningClass(decomposed[j]!);
162
- if (after === 0 || before <= after) break;
163
- [decomposed[j - 1], decomposed[j]] = [decomposed[j]!, decomposed[j - 1]!];
164
- }
165
- }
166
- const out: number[] = decomposed.slice(0, 1);
167
- let starter = 0;
168
- for (let i = 1; i < decomposed.length; i++) {
169
- const codePoint = decomposed[i]!;
170
- if (isMark(codePoint) && (starter === out.length - 1 || combiningClass(out[out.length - 1]!) < combiningClass(codePoint))) {
171
- const composed = compose(out[starter]!, codePoint);
172
- if (composed !== undefined && hasGlyph(composed)) {
173
- out[starter] = composed;
174
- continue;
175
- }
176
- }
177
- out.push(codePoint);
178
- if (combiningClass(codePoint) === 0) starter = out.length - 1;
179
- }
180
- return out;
181
- }
118
+ /** The code points of Devanagari that do not decompose. */
119
+ const kept: ReadonlySet<number> = new Set([0x931]);
182
120
 
183
- /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
184
- function compose(first: number, second: number): number | undefined {
185
- if (isMark(first)) return undefined;
186
- const composed = [(String.fromCodePoint(first) + String.fromCodePoint(second)).normalize("NFC")];
187
- const [single, ...rest] = [...composed[0]!];
188
- return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
121
+ /** This function gives the code points that `normalizeCodePoints` and `vowelConstraints` can give for a set of characters. */
122
+ export function indicForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean): NormalForms {
123
+ return normalForms(new Set([...characters, 0x25cc]), hasGlyph, kept);
189
124
  }
190
125
 
191
126
  // The syllable machine, with one letter for each category
@@ -288,6 +223,16 @@ const basicFeatures: readonly (readonly [string, boolean])[] = [
288
223
  ];
289
224
  /** The features of the last stage, after the final reordering. They match only in a syllable. */
290
225
  const finalFeatures: readonly string[] = ["init", "pres", "abvs", "blws", "psts", "haln"];
226
+ /** This function gives the features of the page that the last stage applies. */
227
+ function pageFeatures(features: readonly string[]): string[] {
228
+ return features.filter((tag) => !["ccmp", "locl", "liga"].includes(tag) && !finalFeatures.includes(tag));
229
+ }
230
+
231
+ /** This function gives all the features that `indicShaper` applies for the features `features` of the page. */
232
+ export function indicFeatures(features: readonly string[]): string[] {
233
+ return ["locl", "ccmp", ...basicFeatures.map(([tag]) => tag), ...finalFeatures, ...pageFeatures(features)];
234
+ }
235
+
291
236
  /** The mask bit of the global features. Each glyph has it. */
292
237
  const GLOBAL = 1;
293
238
  /** The mask bits of the features that apply only to some glyphs of a syllable. */
@@ -352,8 +297,7 @@ export function indicShaper(font: Font, script: string, features: readonly strin
352
297
  };
353
298
  const first = lookupsOf(["locl", "ccmp"]);
354
299
  const basic = basicFeatures.map(([tag, global]) => ({ lookups: lookupsOf([tag]), mask: global ? GLOBAL : featureBits.get(tag)! }));
355
- const extra = features.filter((tag) => !["ccmp", "locl", "liga"].includes(tag) && !finalFeatures.includes(tag));
356
- const last = lookupsOf([...finalFeatures, ...extra]).map((lookup) => ({
300
+ const last = lookupsOf([...finalFeatures, ...pageFeatures(features)]).map((lookup) => ({
357
301
  lookup,
358
302
  mask: lookup.features.reduce((mask, tag) => mask | (tag === "init" ? initMask : GLOBAL), 0),
359
303
  perSyllable: lookup.features.some((tag) => finalFeatures.includes(tag)),
@@ -555,7 +499,7 @@ export function indicShaper(font: Font, script: string, features: readonly strin
555
499
  };
556
500
 
557
501
  return (word: string): number[] => {
558
- const codePoints = normalize(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), (codePoint) => font.glyph(codePoint) !== 0);
502
+ const codePoints = normalizeCodePoints(vowelConstraints([...word].map((character) => character.codePointAt(0)!)), { hasGlyph: (codePoint) => font.glyph(codePoint) !== 0, shortCircuit: false, kept });
559
503
  const run: Run = { glyphs: codePoints.map((codePoint) => font.glyph(codePoint)), infos: [] };
560
504
  for (const codePoint of codePoints) {
561
505
  const [category, position] = indicProperties(codePoint);
@@ -25,8 +25,22 @@ export interface PairLookup {
25
25
  readonly skip?: (glyph: number) => boolean;
26
26
  /** This function gives the value for a pair, or `undefined` when no subtable applies. */
27
27
  pair(first: number, second: number): PairValue | undefined;
28
+ /**
29
+ * This function gives the largest positive value of each glyph of a pair, over the pairs with two glyphs of `glyphs`.
30
+ * A value is at least 0. It uses the values of the instance, so it includes each variation delta.
31
+ */
32
+ largest(glyphs: ReadonlySet<number>): LargestKerning;
33
+ }
34
+
35
+ /** The largest positive kerning of the first glyph and of the second glyph of a pair, in font units. */
36
+ export interface LargestKerning {
37
+ readonly first: number;
38
+ readonly second: number;
28
39
  }
29
40
 
41
+ /** One PairPos subtable. */
42
+ type PairSubtable = Pick<PairLookup, "pair" | "largest">;
43
+
30
44
  /** The lookup flags of OpenType. */
31
45
  export const IGNORE_BASE = 0x2;
32
46
  export const IGNORE_LIGATURES = 0x4;
@@ -63,8 +77,8 @@ function pairValue(first: { value: number; delta: number }, second: { value: num
63
77
  return { first: first.value, second: second.value, firstDelta: first.delta, secondDelta: second.delta, skipSecond };
64
78
  }
65
79
 
66
- /** This function makes the pair function of one PairPos subtable. */
67
- function pairSubtable(table: Reader, store: VariationStore | undefined): (first: number, second: number) => PairValue | undefined {
80
+ /** This function makes the functions of one PairPos subtable. */
81
+ function pairSubtable(table: Reader, store: VariationStore | undefined): PairSubtable {
68
82
  const format = table.u16(0);
69
83
  const coverage = table.part(table.u16(2));
70
84
  const format1 = table.u16(4);
@@ -73,11 +87,11 @@ function pairSubtable(table: Reader, store: VariationStore | undefined): (first:
73
87
  const size2 = valueSize(format2);
74
88
  const skipSecond = format2 !== 0;
75
89
  if (format === 1) {
76
- return (first, second) => {
90
+ const recordSize = 2 + size1 + size2;
91
+ const pair = (first: number, second: number): PairValue | undefined => {
77
92
  const index = coverageIndex(coverage, first);
78
93
  if (index < 0) return undefined;
79
94
  const set = table.part(table.u16(10 + index * 2));
80
- const recordSize = 2 + size1 + size2;
81
95
  let low = 0;
82
96
  let high = set.u16(0) - 1;
83
97
  while (low <= high) {
@@ -90,13 +104,30 @@ function pairSubtable(table: Reader, store: VariationStore | undefined): (first:
90
104
  }
91
105
  return undefined;
92
106
  };
107
+ const largest = (glyphs: ReadonlySet<number>): LargestKerning => {
108
+ let first = 0;
109
+ let second = 0;
110
+ for (const glyph of glyphs) {
111
+ const index = coverageIndex(coverage, glyph);
112
+ if (index < 0) continue;
113
+ const set = table.part(table.u16(10 + index * 2));
114
+ for (let record = 0; record < set.u16(0); record++) {
115
+ const at = 2 + record * recordSize;
116
+ if (!glyphs.has(set.u16(at))) continue;
117
+ first = Math.max(first, xAdvance(set, at + 2, format1, set, store).value);
118
+ second = Math.max(second, xAdvance(set, at + 2 + size1, format2, set, store).value);
119
+ }
120
+ }
121
+ return { first, second };
122
+ };
123
+ return { pair, largest };
93
124
  }
94
125
  if (format === 2) {
95
126
  const classes1 = table.part(table.u16(8));
96
127
  const classes2 = table.part(table.u16(10));
97
128
  const count1 = table.u16(12);
98
129
  const count2 = table.u16(14);
99
- return (first, second) => {
130
+ const pair = (first: number, second: number): PairValue | undefined => {
100
131
  if (coverageIndex(coverage, first) < 0) return undefined;
101
132
  const class1 = classOf(classes1, first);
102
133
  const class2 = classOf(classes2, second);
@@ -104,6 +135,26 @@ function pairSubtable(table: Reader, store: VariationStore | undefined): (first:
104
135
  const at = 16 + (class1 * count2 + class2) * (size1 + size2);
105
136
  return pairValue(xAdvance(table, at, format1, table, store), xAdvance(table, at + size1, format2, table, store), skipSecond);
106
137
  };
138
+ const largest = (glyphs: ReadonlySet<number>): LargestKerning => {
139
+ const firsts = new Set<number>();
140
+ const seconds = new Set<number>();
141
+ for (const glyph of glyphs) {
142
+ if (coverageIndex(coverage, glyph) >= 0) firsts.add(classOf(classes1, glyph));
143
+ seconds.add(classOf(classes2, glyph));
144
+ }
145
+ let first = 0;
146
+ let second = 0;
147
+ for (const class1 of firsts) {
148
+ for (const class2 of seconds) {
149
+ if (class1 >= count1 || class2 >= count2) continue;
150
+ const at = 16 + (class1 * count2 + class2) * (size1 + size2);
151
+ first = Math.max(first, xAdvance(table, at, format1, table, store).value);
152
+ second = Math.max(second, xAdvance(table, at + size1, format2, table, store).value);
153
+ }
154
+ }
155
+ return { first, second };
156
+ };
157
+ return { pair, largest };
107
158
  }
108
159
  throw new Error(`the PairPos format ${format} is unknown`);
109
160
  }
@@ -150,7 +201,7 @@ export function readGposKerning(gpos: Reader, script: string, store?: VariationS
150
201
  }
151
202
  return [...indices].sort((a, b) => a - b).flatMap((index) => {
152
203
  const lookup = lookups.part(lookups.u16(2 + index * 2));
153
- const subtables: ((first: number, second: number) => PairValue | undefined)[] = [];
204
+ const subtables: PairSubtable[] = [];
154
205
  const type = lookup.u16(0);
155
206
  for (let s = 0; s < lookup.u16(4); s++) {
156
207
  let subtable = lookup.part(lookup.u16(6 + s * 2));
@@ -176,11 +227,16 @@ export function readGposKerning(gpos: Reader, script: string, store?: VariationS
176
227
  ...(skip === undefined ? {} : { skip }),
177
228
  pair(first: number, second: number): PairValue | undefined {
178
229
  for (const subtable of subtables) {
179
- const value = subtable(first, second);
230
+ const value = subtable.pair(first, second);
180
231
  if (value !== undefined) return value;
181
232
  }
182
233
  return undefined;
183
234
  },
235
+ // A pair gets the value of one subtable, so the largest value of a lookup is the largest value of its subtables
236
+ largest(glyphs: ReadonlySet<number>): LargestKerning {
237
+ const values = subtables.map((subtable) => subtable.largest(glyphs));
238
+ return { first: Math.max(...values.map((value) => value.first)), second: Math.max(...values.map((value) => value.second)) };
239
+ },
184
240
  }];
185
241
  });
186
242
  }
@@ -213,5 +269,10 @@ export function readKernTable(kern: Reader): PairLookup[] {
213
269
  const value = pairs.get(first * 0x10000 + second);
214
270
  return value === undefined ? undefined : { first: value, second: 0, skipSecond: false };
215
271
  },
272
+ largest(glyphs: ReadonlySet<number>): LargestKerning {
273
+ let first = 0;
274
+ for (const [key, value] of pairs) if (glyphs.has(Math.floor(key / 0x10000)) && glyphs.has(key % 0x10000)) first = Math.max(first, value);
275
+ return { first, second: 0 };
276
+ },
216
277
  }];
217
278
  }
@@ -0,0 +1,144 @@
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
+
8
+ /**
9
+ * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
10
+ * for example the shadda comes first. Each other pair of marks uses the canonical order.
11
+ */
12
+ const sortClasses: ReadonlyMap<number, number> = new Map([
13
+ [0x5b0, 22], [0x5b1, 15], [0x5b2, 16], [0x5b3, 17], [0x5b4, 23], [0x5b5, 18], [0x5b6, 19], [0x5b7, 20], [0x5b8, 21], [0x5b9, 14],
14
+ [0x5ba, 14], [0x5bb, 24], [0x5bc, 12], [0x5bd, 25], [0x5bf, 13], [0x5c1, 10], [0x5c2, 11], [0x5c7, 21], [0xfb1e, 26],
15
+ [0x618, 31], [0x619, 32], [0x61a, 33], [0x64b, 28], [0x64c, 29], [0x64d, 30], [0x64e, 31], [0x64f, 32], [0x650, 33],
16
+ [0x651, 27], [0x652, 34], [0x670, 35], [0x8f0, 28], [0x8f1, 29], [0x8f2, 30],
17
+ ]);
18
+
19
+ /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
20
+ function isMark(codePoint: number): boolean {
21
+ return codePoint >= 0x300 && unicodeMark.test(String.fromCodePoint(codePoint));
22
+ }
23
+
24
+ /** This function tells if a text has a mark of Unicode. */
25
+ export function hasMark(text: string): boolean {
26
+ return unicodeMark.test(text);
27
+ }
28
+
29
+ function decomposed(codePoint: number): string {
30
+ return String.fromCodePoint(codePoint).normalize("NFD");
31
+ }
32
+
33
+ /**
34
+ * This function tells if the mark `second` sorts before the mark `first`. That is true when the class of `first` is larger
35
+ * than the class of `second`, and neither class is 0. The form NFD of JavaScript gives the canonical order, so no table is needed.
36
+ */
37
+ function reorders(first: number, second: number): boolean {
38
+ const firstClass = sortClasses.get(first);
39
+ const secondClass = sortClasses.get(second);
40
+ if (firstClass !== undefined && secondClass !== undefined) return firstClass > secondClass;
41
+ const text = decomposed(first) + decomposed(second);
42
+ return text.normalize("NFD") !== text;
43
+ }
44
+
45
+ /** This function tells if a code point has the combining class 0. U+0345 has the largest class of Unicode. */
46
+ function isStarter(codePoint: number): boolean {
47
+ return !isMark(codePoint) || (codePoint !== 0x345 && !reorders(0x345, codePoint));
48
+ }
49
+
50
+ /** This function gives the canonical composite of two code points, or `undefined`. A mark does not compose with a mark. */
51
+ function compose(first: number, second: number): number | undefined {
52
+ if (isMark(first)) return undefined;
53
+ const [single, ...rest] = [...String.fromCodePoint(first, second).normalize("NFC")];
54
+ return rest.length === 0 && single !== undefined ? single.codePointAt(0) : undefined;
55
+ }
56
+
57
+ /**
58
+ * This function gives the code points of a character after the decomposition. A character keeps its form when the font has
59
+ * no glyph for one of its parts, or when the set `kept` has the character.
60
+ */
61
+ function decomposition(codePoint: number, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number>): number[] {
62
+ const parts = kept.has(codePoint) ? [codePoint] : Array.from(decomposed(codePoint), (part) => part.codePointAt(0)!);
63
+ return (parts.length > 1 || parts[0] !== codePoint) && parts.every(hasGlyph) ? parts : [codePoint];
64
+ }
65
+
66
+ /** The rules of one shaper for `normalizeCodePoints`. */
67
+ export interface NormalizeRules {
68
+ /** This function tells if the font has a glyph for a code point. */
69
+ readonly hasGlyph: (codePoint: number) => boolean;
70
+ /**
71
+ * When this is `true`, a character with a glyph and with no mark near it keeps its form, as the mode `COMPOSED_DIACRITICS`
72
+ * of HarfBuzz does. When this is `false`, each character decomposes, as `COMPOSED_DIACRITICS_NO_SHORT_CIRCUIT` does.
73
+ */
74
+ readonly shortCircuit: boolean;
75
+ /** The code points that do not decompose. */
76
+ readonly kept?: ReadonlySet<number>;
77
+ }
78
+
79
+ /**
80
+ * This function normalizes code points as HarfBuzz does. It decomposes the characters by `rules`. A text with a mark after
81
+ * its first character then gets more steps. The function sorts the marks, and composes each mark with its starter again
82
+ * when the font has the glyph of the composite. A mark between them with the same class or a larger class blocks this.
83
+ */
84
+ export function normalizeCodePoints(codePoints: readonly number[], rules: NormalizeRules): number[] {
85
+ const { hasGlyph, shortCircuit, kept = new Set<number>() } = rules;
86
+ const marked = codePoints.map(isMark);
87
+ const parts = codePoints.flatMap((codePoint, i) => {
88
+ const simple = marked[i + 1] !== true && !(i > 0 && marked[i]!);
89
+ return shortCircuit && simple && hasGlyph(codePoint) ? [codePoint] : decomposition(codePoint, hasGlyph, kept);
90
+ });
91
+ if (!marked.slice(1).includes(true)) return parts;
92
+ // A stable sort of each run of marks with a class that is not 0
93
+ for (let i = 1; i < parts.length; i++) {
94
+ for (let j = i; j > 0 && isMark(parts[j - 1]!) && isMark(parts[j]!) && reorders(parts[j - 1]!, parts[j]!); j--) {
95
+ [parts[j - 1], parts[j]] = [parts[j]!, parts[j - 1]!];
96
+ }
97
+ }
98
+ const out: number[] = parts.slice(0, 1);
99
+ let starter = 0;
100
+ for (let i = 1; i < parts.length; i++) {
101
+ const codePoint = parts[i]!;
102
+ if (isMark(codePoint) && (starter === out.length - 1 || reorders(codePoint, out[out.length - 1]!))) {
103
+ const composed = compose(out[starter]!, codePoint);
104
+ if (composed !== undefined && hasGlyph(composed)) {
105
+ out[starter] = composed;
106
+ continue;
107
+ }
108
+ }
109
+ out.push(codePoint);
110
+ if (isStarter(codePoint)) starter = out.length - 1;
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /** The code points that `normalizeCodePoints` can give for a set of characters. */
116
+ export interface NormalForms {
117
+ /** The parts of each character of the set after the decomposition. A character with no decomposition is its one part. */
118
+ readonly parts: ReadonlyMap<number, readonly number[]>;
119
+ /** The composites of each code point: the code points that it becomes when a mark composes with it. */
120
+ readonly composites: ReadonlyMap<number, readonly number[]>;
121
+ /** All the code points that the shaper can see: the set, its parts and each composite. */
122
+ readonly codePoints: ReadonlySet<number>;
123
+ }
124
+
125
+ /** This function gives the forms of a set of characters. It repeats the compositions until the set of code points is stable. */
126
+ export function normalForms(characters: ReadonlySet<number>, hasGlyph: (codePoint: number) => boolean, kept: ReadonlySet<number> = new Set()): NormalForms {
127
+ const parts = new Map([...characters].map((codePoint) => [codePoint, decomposition(codePoint, hasGlyph, kept)]));
128
+ const codePoints = new Set([...characters, ...[...parts.values()].flat()]);
129
+ const composites = new Map<number, number[]>();
130
+ for (let size = 0; size !== codePoints.size; ) {
131
+ size = codePoints.size;
132
+ const marks = [...codePoints].filter(isMark);
133
+ for (const starter of codePoints) {
134
+ for (const mark of marks) {
135
+ const composed = compose(starter, mark);
136
+ if (composed === undefined || !hasGlyph(composed)) continue;
137
+ const known = composites.get(starter) ?? [];
138
+ if (!known.includes(composed)) composites.set(starter, [...known, composed]);
139
+ codePoints.add(composed);
140
+ }
141
+ }
142
+ }
143
+ return { parts, composites, codePoints };
144
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Reader } from "./binary.ts";
2
2
  import { IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, scriptTags } from "./kerning.ts";
3
- import { classOf, coverageIndex } from "./tables.ts";
3
+ import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
4
4
 
5
5
  /**
6
6
  * The GSUB features that the default model applies: the features that HarfBuzz and Chromium apply to horizontal text
@@ -66,6 +66,16 @@ export interface GlyphInfo {
66
66
  readonly codePoint: number;
67
67
  }
68
68
 
69
+ /** One substitution that a lookup can do, with no context. */
70
+ export interface SubstitutionRule {
71
+ /** The glyph that the rule replaces. The first glyph of a ligature is this glyph. */
72
+ readonly from: number;
73
+ /** The glyphs that replace it. A multiple substitution can give no glyph. */
74
+ readonly to: readonly number[];
75
+ /** The other glyphs of a ligature, in order. Another rule has no such glyphs. */
76
+ readonly components?: readonly number[];
77
+ }
78
+
69
79
  /** A lookup of GSUB for one script and one set of features. */
70
80
  export interface SubstitutionLookup {
71
81
  /** The index of the lookup in the lookup list of GSUB. */
@@ -93,6 +103,12 @@ export interface SubstitutionLookup {
93
103
  * `hb_ot_layout_lookup_would_substitute` with zero context tells it. A context rule with backtrack or lookahead does not apply.
94
104
  */
95
105
  wouldApply(glyphs: readonly number[]): boolean;
106
+ /**
107
+ * This function gives the rules of the lookup, and the rules of each lookup that it nests in a context rule. Each lookup
108
+ * has one list, and the list of this lookup is the first. The lists do not tell a context, so each nested rule counts.
109
+ * An alternate substitution gives one rule for each alternate.
110
+ */
111
+ rules(): readonly (readonly SubstitutionRule[])[];
96
112
  }
97
113
 
98
114
  /** One lookup of the lookup list, with the subtables of an extension lookup resolved. */
@@ -113,6 +129,71 @@ function records(table: Reader, at: number, count: number): SequenceRecord[] {
113
129
  return Array.from({ length: count }, (_, k) => ({ sequenceIndex: table.u16(at + k * 4), lookupIndex: table.u16(at + k * 4 + 2) }));
114
130
  }
115
131
 
132
+ /** This function gives each rule table of the rule sets at `at` of a context subtable of format 1 or 2. An offset 0 is an empty set. */
133
+ function ruleTables(t: Reader, at: number): Reader[] {
134
+ const tables: Reader[] = [];
135
+ for (let s = 0; s < t.u16(at); s++) {
136
+ const offset = t.u16(at + 2 + s * 2);
137
+ if (offset === 0) continue;
138
+ const set = t.part(offset);
139
+ for (let r = 0; r < set.u16(0); r++) tables.push(set.part(set.u16(2 + r * 2)));
140
+ }
141
+ return tables;
142
+ }
143
+
144
+ /** This function gives the records of each rule of a context subtable (lookup type 5). */
145
+ function contextRecords(t: Reader): SequenceRecord[] {
146
+ const format = t.u16(0);
147
+ if (format === 3) return records(t, 6 + t.u16(2) * 2, t.u16(4));
148
+ return ruleTables(t, format === 2 ? 6 : 4).flatMap((rule) => records(rule, 4 + (rule.u16(0) - 1) * 2, rule.u16(2)));
149
+ }
150
+
151
+ /** This function gives the records of each rule of a chained context subtable (lookup type 6). */
152
+ function chainRecords(t: Reader): SequenceRecord[] {
153
+ const format = t.u16(0);
154
+ if (format === 3) {
155
+ const inputAt = 4 + t.u16(2) * 2;
156
+ const aheadAt = inputAt + 2 + t.u16(inputAt) * 2;
157
+ const recordsAt = aheadAt + 2 + t.u16(aheadAt) * 2;
158
+ return records(t, recordsAt + 2, t.u16(recordsAt));
159
+ }
160
+ return ruleTables(t, format === 2 ? 10 : 4).flatMap((rule) => {
161
+ const inputAt = 2 + rule.u16(0) * 2;
162
+ const aheadAt = inputAt + 2 + Math.max(0, rule.u16(inputAt) - 1) * 2;
163
+ const recordsAt = aheadAt + 2 + rule.u16(aheadAt) * 2;
164
+ return records(rule, recordsAt + 2, rule.u16(recordsAt));
165
+ });
166
+ }
167
+
168
+ /** This function adds the rules of one subtable of a lookup type to `rules`, and each nested lookup to `nested`. */
169
+ function readRules(type: number, t: Reader, rules: SubstitutionRule[], nested: number[]): void {
170
+ if (type === 5 || type === 6) {
171
+ for (const record of type === 5 ? contextRecords(t) : chainRecords(t)) nested.push(record.lookupIndex);
172
+ return;
173
+ }
174
+ if (type < 1 || type > 8 || type === 7) return;
175
+ const format = t.u16(0);
176
+ for (const [from, index] of coverageGlyphs(t.part(t.u16(2)))) {
177
+ if (type === 1) rules.push({ from, to: [format === 1 ? (from + t.i16(4)) & 0xffff : t.u16(6 + index * 2)] });
178
+ else if (type === 2) {
179
+ const sequence = t.part(t.u16(6 + index * 2));
180
+ rules.push({ from, to: Array.from({ length: sequence.u16(0) }, (_, k) => sequence.u16(2 + k * 2)) });
181
+ } else if (type === 3) {
182
+ const set = t.part(t.u16(6 + index * 2));
183
+ for (let k = 0; k < set.u16(0); k++) rules.push({ from, to: [set.u16(2 + k * 2)] });
184
+ } else if (type === 4) {
185
+ const set = t.part(t.u16(6 + index * 2));
186
+ for (let l = 0; l < set.u16(0); l++) {
187
+ const ligature = set.part(set.u16(2 + l * 2));
188
+ rules.push({ from, to: [ligature.u16(0)], components: Array.from({ length: ligature.u16(2) - 1 }, (_, k) => ligature.u16(4 + k * 2)) });
189
+ }
190
+ } else {
191
+ const aheadAt = 6 + t.u16(4) * 2;
192
+ rules.push({ from, to: [t.u16(aheadAt + 2 + t.u16(aheadAt) * 2 + 2 + index * 2)] });
193
+ }
194
+ }
195
+ }
196
+
116
197
  /** The lookups of one GSUB table. It reads each lookup at its first use. */
117
198
  class Gsub {
118
199
  private readonly lookups: Reader;
@@ -392,6 +473,24 @@ class Gsub {
392
473
  });
393
474
  }
394
475
 
476
+ /** This function gives the rules of a lookup and of each lookup that it nests, as `rules` of `SubstitutionLookup` tells. */
477
+ rulesOf(index: number): SubstitutionRule[][] {
478
+ const lists: SubstitutionRule[][] = [];
479
+ const seen = new Set<number>();
480
+ const visit = (at: number): void => {
481
+ const lookup = this.lookup(at);
482
+ if (seen.has(at) || lookup === undefined) return;
483
+ seen.add(at);
484
+ const rules: SubstitutionRule[] = [];
485
+ const nested: number[] = [];
486
+ for (const subtable of lookup.subtables) readRules(lookup.type, subtable, rules, nested);
487
+ lists.push(rules);
488
+ nested.forEach(visit);
489
+ };
490
+ visit(index);
491
+ return lists;
492
+ }
493
+
395
494
  /** This function applies one subtable at `i`. It gives the next position, or -1 when the subtable does not match. */
396
495
  private subtable(lookup: Lookup, t: Reader, glyphs: number[], i: number, depth: number): number {
397
496
  const glyph = glyphs[i]!;
@@ -580,6 +679,7 @@ export function readSubstitutions(gsub: Reader, script: string, features: readon
580
679
  apply: (glyphs: number[], masks?: number[], mask?: number) => table.applyAll(index, glyphs, masks, mask),
581
680
  applyInfos: (glyphs: number[], infos: GlyphInfo[], mask: number, perSyllable: boolean) => table.applyRun(index, glyphs, infos, mask, perSyllable),
582
681
  wouldApply: (glyphs: readonly number[]) => table.wouldApply(index, glyphs),
682
+ rules: () => table.rulesOf(index),
583
683
  });
584
684
  }
585
685
  return result;
@@ -130,6 +130,28 @@ export function coverageIndex(table: Reader, glyph: number): number {
130
130
  throw new Error(`the Coverage format ${format} is unknown`);
131
131
  }
132
132
 
133
+ /** This function gives each glyph of a Coverage table with its coverage index, in the order of the table. */
134
+ export function coverageGlyphs(table: Reader): (readonly [glyph: number, index: number])[] {
135
+ const format = table.u16(0);
136
+ const count = table.u16(2);
137
+ const glyphs: (readonly [number, number])[] = [];
138
+ if (format === 1) {
139
+ for (let k = 0; k < count; k++) glyphs.push([table.u16(4 + k * 2), k]);
140
+ return glyphs;
141
+ }
142
+ if (format === 2) {
143
+ for (let k = 0; k < count; k++) {
144
+ const at = 4 + k * 6;
145
+ const start = table.u16(at);
146
+ const end = table.u16(at + 2);
147
+ const index = table.u16(at + 4);
148
+ for (let glyph = start; glyph <= end; glyph++) glyphs.push([glyph, index + glyph - start]);
149
+ }
150
+ return glyphs;
151
+ }
152
+ throw new Error(`the Coverage format ${format} is unknown`);
153
+ }
154
+
133
155
  /** The GDEF glyph classes: 1 base, 2 ligature, 3 mark, 4 component. */
134
156
  export function readGlyphClasses(gdef: Reader | undefined): ((glyph: number) => number) {
135
157
  if (gdef === undefined) return () => 0;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The subpath `./fonts/inspect`: the parts of the font model that a tool uses to examine a width. They give the glyphs,
3
- * the shaping words, the default features and the tables of a font file.
3
+ * the shaping words, the segments of a canvas, the default features and the tables of a font file.
4
4
  */
5
5
  export { glyphAdvances, shapingWords } from "./fonts/font.ts";
6
- export { canvasWords } from "./fonts/words.ts";
6
+ export { canvasSegments, canvasWords } from "./fonts/words.ts";
7
7
  export { defaultFeatures } from "./fonts/substitution.ts";
8
8
  export { readTables } from "./fonts/sfnt.ts";
package/src/fonts.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * the width of a text as the text engine of a browser gives it. The host gives the bytes of the font files.
4
4
  */
5
5
  export { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from "./fonts/font.ts";
6
+ export { widthBound, type WidthBound } from "./fonts/bound.ts";
6
7
  export { engines, isEngineName, type EngineName, type EngineRules } from "./fonts/engines.ts";
7
8
  export type { Decompress } from "./fonts/sfnt.ts";
8
9
  export type { Axis, Instance } from "./fonts/variations.ts";