@mark1russell7/typeset 0.1.4 → 0.1.6

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.
Files changed (48) hide show
  1. package/build/chunks/breaking.js +9 -2
  2. package/build/chunks/breaking.js.map +1 -1
  3. package/build/chunks/engines.js +46 -1
  4. package/build/chunks/engines.js.map +1 -1
  5. package/build/chunks/font.d.ts +6 -0
  6. package/build/chunks/font.d.ts.map +1 -1
  7. package/build/chunks/font.js +543 -315
  8. package/build/chunks/font.js.map +1 -1
  9. package/build/chunks/fonts.d.ts +12 -2
  10. package/build/chunks/fonts.d.ts.map +1 -1
  11. package/build/chunks/fonts.js +3 -2
  12. package/build/chunks/fonts.js.map +1 -1
  13. package/build/chunks/measurer.d.ts +6 -2
  14. package/build/chunks/measurer.d.ts.map +1 -1
  15. package/build/chunks/measurer.js +45 -8
  16. package/build/chunks/measurer.js.map +1 -1
  17. package/build/chunks/paragraph.d.ts +5 -0
  18. package/build/chunks/paragraph.d.ts.map +1 -1
  19. package/build/fonts-inspect.d.ts +11 -1
  20. package/build/fonts-inspect.d.ts.map +1 -1
  21. package/build/fonts-inspect.js +1 -1
  22. package/build/fonts.d.ts +2 -2
  23. package/build/fonts.js +2 -2
  24. package/build/measurer.d.ts +2 -2
  25. package/build/segmentation.d.ts +19 -0
  26. package/build/segmentation.d.ts.map +1 -0
  27. package/build/segmentation.js +267 -0
  28. package/build/segmentation.js.map +1 -0
  29. package/package.json +7 -3
  30. package/src/breaking/paragraph.ts +8 -2
  31. package/src/fonts/context.ts +48 -0
  32. package/src/fonts/font.ts +52 -13
  33. package/src/fonts/index.ts +1 -0
  34. package/src/fonts/indic.ts +51 -42
  35. package/src/fonts/joining.ts +2 -2
  36. package/src/fonts/kerning.ts +48 -34
  37. package/src/fonts/machine.ts +133 -0
  38. package/src/fonts/normalize.ts +27 -0
  39. package/src/fonts/risks.ts +48 -0
  40. package/src/fonts/substitution.ts +15 -44
  41. package/src/fonts-inspect.ts +2 -1
  42. package/src/fonts.ts +1 -0
  43. package/src/measurer/advance.ts +46 -1
  44. package/src/measurer.ts +1 -1
  45. package/src/segmentation/line-table.ts +5 -0
  46. package/src/segmentation/line.ts +203 -0
  47. package/src/segmentation/segments.ts +18 -0
  48. package/src/segmentation.ts +3 -0
@@ -4,8 +4,10 @@
4
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 { alt, any, compile, longestMatch, opt, seq, set, star, type Machine, type Pattern } from "./machine.ts";
7
8
  import { normalForms, normalizeCodePoints, type NormalForms } from "./normalize.ts";
8
9
  import { LIGATED, MULTIPLIED, SUBSTITUTED, type GlyphInfo } from "./substitution.ts";
10
+ import { isHidden } from "./normalize.ts";
9
11
 
10
12
  /** The OpenType script tags that use the Indic shaper in this model. */
11
13
  export const indicScripts: readonly string[] = ["deva"];
@@ -128,55 +130,62 @@ const letters = new Map<number, string>([
128
130
  [X, "x"], [C, "c"], [V, "v"], [N, "n"], [H, "h"], [ZWNJ, "w"], [ZWJ, "j"], [M, "m"], [SM, "s"], [A, "a"], [PLACEHOLDER, "p"],
129
131
  [DOTTEDCIRCLE, "d"], [RS, "r"], [MPST, "q"], [REPHA, "f"], [RA, "R"], [CM, "k"], [SYMBOL, "y"], [CS, "S"], [SMPST, "t"],
130
132
  ]);
131
- const c = "[cR]";
132
- const n = "(?:w?r)?(?:nn?)?";
133
- const z = "[wj]";
134
- const reph = "(?:Rh|f)";
135
- const sm = "[st]";
136
- const cn = `${c}j?${n}`;
137
- const matraGroup = `${z}*(?:m|${sm}?q)n?h?`;
138
- const syllableTail = `(?:${z}?${sm}${sm}?w?)?a*`;
139
- const halantGroup = `(?:${z}?h(?:jn?)?)`;
140
- const finalHalantGroup = `(?:${halantGroup}|hw)`;
141
- const complexSyllableTail = `(?:${halantGroup}${cn})*k?(?:${finalHalantGroup}|(?:${matraGroup})*)${syllableTail}`;
142
- /** The rules of the machine in the order of HarfBuzz. A tie of two lengths goes to the first rule. */
143
- const machine: readonly (readonly [RegExp, number])[] = (
144
- [
145
- [`[fS]?${cn}${complexSyllableTail}`, CONSONANT_SYLLABLE],
146
- [`${reph}?v${n}(?:j|${complexSyllableTail})`, VOWEL_SYLLABLE],
147
- [`(?:[fS]?p|${reph}?d)${n}${complexSyllableTail}`, STANDALONE_CLUSTER],
148
- [`yn?${syllableTail}`, SYMBOL_CLUSTER],
149
- ["t", NON_INDIC_CLUSTER],
150
- [`${reph}?${n}${complexSyllableTail}`, BROKEN_CLUSTER],
151
- ["[^]", NON_INDIC_CLUSTER],
152
- ] as const
153
- ).map(([rule, type]) => [new RegExp(`^(?:${rule})$`), type] as const);
133
+ const c = set("cR");
134
+ const n = seq(opt(seq(opt("w"), "r")), opt(seq("n", opt("n"))));
135
+ const z = set("wj");
136
+ const reph = alt("Rh", "f");
137
+ const sm = set("st");
138
+ const cn = seq(c, opt("j"), n);
139
+ const matraGroup = seq(star(z), alt("m", seq(opt(sm), "q")), opt("n"), opt("h"));
140
+ const syllableTail = seq(opt(seq(opt(z), sm, opt(sm), opt("w"))), star("a"));
141
+ const halantGroup = seq(opt(z), "h", opt(seq("j", opt("n"))));
142
+ const finalHalantGroup = alt(halantGroup, "hw");
143
+ const complexSyllableTail = seq(star(seq(halantGroup, cn)), opt("k"), alt(finalHalantGroup, star(matraGroup)), syllableTail);
144
+ /** The rules of the machine in the order of HarfBuzz, with the type of each. A tie of two lengths goes to the first rule. */
145
+ const indicRules: readonly (readonly [Pattern, number])[] = [
146
+ [seq(opt(set("fS")), cn, complexSyllableTail), CONSONANT_SYLLABLE],
147
+ [seq(opt(reph), "v", n, alt("j", complexSyllableTail)), VOWEL_SYLLABLE],
148
+ [seq(alt(seq(opt(set("fS")), "p"), seq(opt(reph), "d")), n, complexSyllableTail), STANDALONE_CLUSTER],
149
+ [seq("y", opt("n"), syllableTail), SYMBOL_CLUSTER],
150
+ ["t", NON_INDIC_CLUSTER],
151
+ [seq(opt(reph), n, complexSyllableTail), BROKEN_CLUSTER],
152
+ [any, NON_INDIC_CLUSTER],
153
+ ];
154
+ const machines: readonly Machine[] = indicRules.map(([rule]) => compile(rule));
155
+
156
+ /**
157
+ * This function divides a text of category letters into syllables, as the machine of HarfBuzz does. At each position,
158
+ * it takes the longest match of the rules, in one pass. It gives the length and the type of each syllable.
159
+ */
160
+ export function letterSyllables(text: string): (readonly [length: number, type: number])[] {
161
+ const out: (readonly [number, number])[] = [];
162
+ let at = 0;
163
+ while (at < text.length) {
164
+ // No rule but the last one matches the category X, so a syllable stops before it
165
+ const next = text.indexOf("x", at + 1);
166
+ const match = longestMatch(machines, text, at, next < 0 ? text.length : next);
167
+ const length = match?.length ?? 1;
168
+ out.push([length, match === undefined ? NON_INDIC_CLUSTER : indicRules[match.rule]![1]]);
169
+ at += length;
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /** This function gives the category letter of each code point of a text. The tests use it. */
175
+ export function indicLetters(text: string): string {
176
+ return Array.from(text, (character) => letters.get(indicProperties(character.codePointAt(0)!)[0]) ?? "x").join("");
177
+ }
154
178
 
155
179
  /**
156
- * This function divides the glyphs into syllables, as the machine of HarfBuzz does. At each position, it takes the
157
- * longest match of the rules. Each glyph gets the syllable byte. Its high 4 bits are a serial number from 1 to 15, and
158
- * its low 4 bits are the type. The function tells if a syllable is a broken cluster.
180
+ * This function divides the glyphs into syllables. Each glyph gets the syllable byte. Its high 4 bits are a serial
181
+ * number from 1 to 15, and its low 4 bits are the type. The function tells if a syllable is a broken cluster.
159
182
  */
160
183
  function findSyllables(infos: GlyphInfo[]): boolean {
161
184
  const text = infos.map((info) => letters.get(info.category) ?? "x").join("");
162
185
  let serial = 1;
163
186
  let broken = false;
164
187
  let at = 0;
165
- while (at < text.length) {
166
- // No rule but the last one matches the category X, so a syllable stops before it
167
- const next = text.indexOf("x", at + 1);
168
- let length = 1;
169
- let type = NON_INDIC_CLUSTER;
170
- search: for (let end = next < 0 ? text.length : next; end > at; end--) {
171
- const piece = text.slice(at, end);
172
- for (const [rule, kind] of machine) {
173
- if (rule.test(piece)) {
174
- length = end - at;
175
- type = kind;
176
- break search;
177
- }
178
- }
179
- }
188
+ for (const [length, type] of letterSyllables(text)) {
180
189
  if (type === BROKEN_CLUSTER) broken = true;
181
190
  for (let i = at; i < at + length; i++) infos[i]!.syllable = (serial << 4) | type;
182
191
  serial = serial === 15 ? 1 : serial + 1;
@@ -524,6 +533,6 @@ export function indicShaper(font: Font, script: string, features: readonly strin
524
533
  for (const { lookups, mask } of basic) for (const lookup of lookups) lookup.applyInfos(run.glyphs, run.infos, mask, true);
525
534
  for (const [start, end] of syllables(run.infos)) finalReordering(run, start, end);
526
535
  for (const { lookup, mask, perSyllable } of last) lookup.applyInfos(run.glyphs, run.infos, mask, perSyllable);
527
- return run.glyphs;
536
+ return run.glyphs.map((glyph, i) => ((run.infos[i]!.props & SUBSTITUTED) === 0 && isHidden(run.infos[i]!.codePoint) ? ~glyph : glyph));
528
537
  };
529
538
  }
@@ -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,133 @@
1
+ /**
2
+ * A small rule machine over a text of letters. Each rule is a pattern, and the machine finds the longest match of all
3
+ * rules at a position in one pass. It moves an automaton of each rule over the letters, so the time is linear in the
4
+ * length of the match. A regular expression with `^` and `$` gives the same matches, but a search over each end is
5
+ * quadratic. This module is internal to typeset.
6
+ */
7
+
8
+ /** A pattern of a rule. A string is a sequence of its letters. */
9
+ export type Pattern =
10
+ | string
11
+ | { readonly kind: "set"; readonly letters: string }
12
+ | { readonly kind: "any" }
13
+ | { readonly kind: "seq"; readonly parts: readonly Pattern[] }
14
+ | { readonly kind: "alt"; readonly parts: readonly Pattern[] }
15
+ | { readonly kind: "star"; readonly part: Pattern }
16
+ | { readonly kind: "opt"; readonly part: Pattern };
17
+
18
+ /** This function gives a pattern that matches one of the letters. */
19
+ export const set = (letters: string): Pattern => ({ kind: "set", letters });
20
+ /** The pattern that matches any one letter. */
21
+ export const any: Pattern = { kind: "any" };
22
+ /** This function gives a pattern that matches the parts one after the other. */
23
+ export const seq = (...parts: Pattern[]): Pattern => ({ kind: "seq", parts });
24
+ /** This function gives a pattern that matches one of the parts. */
25
+ export const alt = (...parts: Pattern[]): Pattern => ({ kind: "alt", parts });
26
+ /** This function gives a pattern that matches the part 0 or more times. */
27
+ export const star = (part: Pattern): Pattern => ({ kind: "star", part });
28
+ /** This function gives a pattern that matches the part 0 or 1 times. */
29
+ export const opt = (part: Pattern): Pattern => ({ kind: "opt", part });
30
+
31
+ /** This function escapes a letter for a regular expression. */
32
+ const escape = (letter: string): string => letter.replace(/[\\^$.*+?()[\]{}|/-]/g, "\\$&");
33
+
34
+ /** This function gives the source of a regular expression with the same matches as a pattern. The tests use it. */
35
+ export function patternSource(pattern: Pattern): string {
36
+ if (typeof pattern === "string") return [...pattern].map(escape).join("");
37
+ switch (pattern.kind) {
38
+ case "set":
39
+ return `[${[...pattern.letters].map(escape).join("")}]`;
40
+ case "any":
41
+ return "[^]";
42
+ case "seq":
43
+ return pattern.parts.map((part) => `(?:${patternSource(part)})`).join("");
44
+ case "alt":
45
+ return `(?:${pattern.parts.map(patternSource).join("|")})`;
46
+ case "star":
47
+ return `(?:${patternSource(pattern.part)})*`;
48
+ case "opt":
49
+ return `(?:${patternSource(pattern.part)})?`;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The automaton of one rule. A state with `letters` steps to `next` on one of its letters, or on any letter when
55
+ * `letters` is `null`. A state with `split` has steps with no letter to each of its states. State 0 accepts.
56
+ */
57
+ interface State {
58
+ readonly letters?: string | null;
59
+ next?: number;
60
+ split?: number[];
61
+ }
62
+
63
+ /** The automaton of one rule, with its start state. */
64
+ export interface Machine {
65
+ readonly states: readonly State[];
66
+ readonly start: number;
67
+ }
68
+
69
+ /** This function builds the automaton of a pattern, by the construction of Thompson. */
70
+ export function compile(pattern: Pattern): Machine {
71
+ const states: State[] = [{}];
72
+ const build = (p: Pattern, next: number): number => {
73
+ if (typeof p === "string") return [...p].reduceRight((to, letter) => states.push({ letters: letter, next: to }) - 1, next);
74
+ switch (p.kind) {
75
+ case "set":
76
+ return states.push({ letters: p.letters, next }) - 1;
77
+ case "any":
78
+ return states.push({ letters: null, next }) - 1;
79
+ case "seq":
80
+ return p.parts.reduceRight((to, part) => build(part, to), next);
81
+ case "alt":
82
+ return states.push({ split: p.parts.map((part) => build(part, next)) }) - 1;
83
+ case "opt":
84
+ return states.push({ split: [build(p.part, next), next] }) - 1;
85
+ case "star": {
86
+ const loop = states.push({ split: [] }) - 1;
87
+ states[loop]!.split = [build(p.part, loop), next];
88
+ return loop;
89
+ }
90
+ }
91
+ };
92
+ return { states, start: build(pattern, 0) };
93
+ }
94
+
95
+ /** This function adds a state and each state that it reaches with no letter to a set. */
96
+ function close(machine: Machine, state: number, into: Set<number>): void {
97
+ const stack = [state];
98
+ while (stack.length > 0) {
99
+ const s = stack.pop()!;
100
+ if (into.has(s)) continue;
101
+ into.add(s);
102
+ for (const to of machine.states[s]!.split ?? []) stack.push(to);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * This function gives the longest match of the rules in `text` from `at`, which ends at `end` or before it. A tie of two
108
+ * rules goes to the first rule. A match has at least one letter. It gives `undefined` when no rule matches.
109
+ */
110
+ export function longestMatch(machines: readonly Machine[], text: string, at: number, end: number): { readonly length: number; readonly rule: number } | undefined {
111
+ let best: { length: number; rule: number } | undefined;
112
+ let current = machines.map((machine) => {
113
+ const states = new Set<number>();
114
+ close(machine, machine.start, states);
115
+ return states;
116
+ });
117
+ for (let position = at; position < end && current.some((states) => states.size > 0); position++) {
118
+ const letter = text[position]!;
119
+ current = current.map((states, rule) => {
120
+ const machine = machines[rule]!;
121
+ const next = new Set<number>();
122
+ for (const s of states) {
123
+ const state = machine.states[s]!;
124
+ if (state.letters !== undefined && (state.letters === null || state.letters.includes(letter))) close(machine, state.next!, next);
125
+ }
126
+ return next;
127
+ });
128
+ const length = position + 1 - at;
129
+ const rule = current.findIndex((states) => states.has(0));
130
+ if (rule >= 0) best = { length, rule };
131
+ }
132
+ return best;
133
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  const unicodeMark = /\p{M}/u;
7
+ const nonspacingMark = /\p{Mn}/u;
7
8
 
8
9
  /**
9
10
  * The classes of HarfBuzz for the marks of Hebrew and Arabic, from `hb-unicode.hh`. Their order is not the canonical order:
@@ -16,6 +17,19 @@ const sortClasses: ReadonlyMap<number, number> = new Map([
16
17
  [0x651, 27], [0x652, 34], [0x670, 35], [0x8f0, 28], [0x8f1, 29], [0x8f2, 30],
17
18
  ]);
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
+
19
33
  /** This function tells if a code point is a mark of Unicode. The first mark of Unicode is U+0300. */
20
34
  function isMark(codePoint: number): boolean {
21
35
  return codePoint >= 0x300 && unicodeMark.test(String.fromCodePoint(codePoint));
@@ -26,6 +40,19 @@ export function hasMark(text: string): boolean {
26
40
  return unicodeMark.test(text);
27
41
  }
28
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
+
29
56
  function decomposed(codePoint: number): string {
30
57
  return String.fromCodePoint(codePoint).normalize("NFD");
31
58
  }
@@ -0,0 +1,48 @@
1
+ /** The risks of shaping: the text that the model cannot measure with trust. */
2
+ import { glyphAdvances, shapingOf, type Font, type MeasureOptions } from "./font.ts";
3
+ import { hasDefaultIgnorable, normalizeCodePoints } from "./normalize.ts";
4
+ import { canvasWords } from "./words.ts";
5
+
6
+ /** The kinds of risk. */
7
+ export type ShapingRiskCode = "missing-glyph" | "unshaped-script" | "emoji-zwj" | "variation-selector" | "keycap" | "flag" | "tag" | "positioning";
8
+
9
+ /** One part of a text that the model does not shape as HarfBuzz does, in UTF-16 units. */
10
+ export interface ShapingRisk {
11
+ readonly code: ShapingRiskCode;
12
+ readonly index: number;
13
+ readonly length: number;
14
+ }
15
+
16
+ const unshaped = /[\p{sc=Beng}\p{sc=Guru}\p{sc=Gujr}\p{sc=Orya}\p{sc=Taml}\p{sc=Telu}\p{sc=Knda}\p{sc=Mlym}\p{sc=Sinh}\p{sc=Khmr}\p{sc=Mymr}\p{sc=Tibt}\p{sc=Mong}\p{sc=Nkoo}\p{sc=Mand}]+/gu;
17
+ const pictograph = String.raw`\p{ExtPict}(?:\uFE0F|[\u{1F3FB}-\u{1F3FF}])?`;
18
+ // The longest forms come first
19
+ const sequences = new RegExp(String.raw`(\p{ExtPict}[\u{E0020}-\u{E007E}]+\u{E007F})|(${pictograph}(?:\u200D${pictograph})+)|([0-9#*]\uFE0F?\u20E3)|(\p{RI}\p{RI})|([\uFE00-\uFE0F\u{E0100}-\u{E01EF}])`, "gu");
20
+ const sequenceCodes: readonly ShapingRiskCode[] = ["tag", "emoji-zwj", "keycap", "flag", "variation-selector"];
21
+ const clusters = /\P{M}\p{M}*|\p{M}+/gu;
22
+ const control = /\p{Cc}/u;
23
+
24
+ /** This function gives the risks of a text in text order. An empty list is not a proof of a correct width. */
25
+ export function shapingRisks(font: Font, text: string, options: MeasureOptions = {}): ShapingRisk[] {
26
+ const risks: ShapingRisk[] = [];
27
+ const add = (code: ShapingRiskCode, index: number, { length }: string): number => risks.push({ code, index, length });
28
+ const absent = (codePoint: number): boolean => {
29
+ const character = String.fromCodePoint(codePoint);
30
+ return font.glyph(codePoint) === 0 && !control.test(character) && !hasDefaultIgnorable(character);
31
+ };
32
+ const hasGlyph = (codePoint: number): boolean => font.glyph(codePoint) !== 0;
33
+ for (const { 0: cluster, index } of text.matchAll(clusters)) {
34
+ if (normalizeCodePoints(Array.from(cluster, (character) => character.codePointAt(0)!), { hasGlyph, shortCircuit: true }).some(absent)) add("missing-glyph", index, cluster);
35
+ }
36
+ for (const { 0: part, index } of text.matchAll(unshaped)) add("unshaped-script", index, part);
37
+ for (const match of text.matchAll(sequences)) add(sequenceCodes[match.slice(1).findIndex(Boolean)]!, match.index, match[0]);
38
+ const tests = options.kerning === false ? [] : font.contextKerning?.(shapingOf(font, options).script) ?? [];
39
+ if (tests.length > 0) {
40
+ let index = 0;
41
+ for (const word of options.shaping === "canvas" ? canvasWords(text) : [text]) {
42
+ const { glyphs } = glyphAdvances(font, word, options);
43
+ if (tests.some((test) => test(glyphs))) add("positioning", index, word);
44
+ index += word.length;
45
+ }
46
+ }
47
+ return risks.sort((a, b) => a.index - b.index);
48
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Reader } from "./binary.ts";
2
- import { IGNORE_BASE, IGNORE_LIGATURES, IGNORE_MARKS, scriptTags } from "./kerning.ts";
2
+ import { languageSystem, lookupSkip, subtablesOf } from "./kerning.ts";
3
3
  import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
4
4
 
5
5
  /**
@@ -8,8 +8,6 @@ import { classOf, coverageGlyphs, coverageIndex } from "./tables.ts";
8
8
  */
9
9
  export const defaultFeatures: readonly string[] = ["ccmp", "locl", "rlig", "liga", "clig", "calt", "rclt"];
10
10
 
11
- /** The lookup flag that selects a mark filtering set of GDEF. */
12
- const USE_MARK_FILTERING_SET = 0x10;
13
11
  /** The largest depth of nested lookups, as in HarfBuzz. */
14
12
  const MAX_NESTING = 64;
15
13
 
@@ -21,6 +19,8 @@ export interface GlyphFilter {
21
19
  markAttachClass(glyph: number): number;
22
20
  /** This function tells if a glyph is in the mark filtering set `set`. */
23
21
  inMarkSet(set: number, glyph: number): boolean;
22
+ /** The glyphs of the joiners that the backtrack and the lookahead of a context rule skip. */
23
+ readonly joiners?: readonly number[];
24
24
  }
25
25
 
26
26
  /** This function reads the glyph classes, the mark attachment classes and the mark filtering sets of GDEF. */
@@ -142,14 +142,14 @@ function ruleTables(t: Reader, at: number): Reader[] {
142
142
  }
143
143
 
144
144
  /** This function gives the records of each rule of a context subtable (lookup type 5). */
145
- function contextRecords(t: Reader): SequenceRecord[] {
145
+ export function contextRecords(t: Reader): SequenceRecord[] {
146
146
  const format = t.u16(0);
147
147
  if (format === 3) return records(t, 6 + t.u16(2) * 2, t.u16(4));
148
148
  return ruleTables(t, format === 2 ? 6 : 4).flatMap((rule) => records(rule, 4 + (rule.u16(0) - 1) * 2, rule.u16(2)));
149
149
  }
150
150
 
151
151
  /** This function gives the records of each rule of a chained context subtable (lookup type 6). */
152
- function chainRecords(t: Reader): SequenceRecord[] {
152
+ export function chainRecords(t: Reader): SequenceRecord[] {
153
153
  const format = t.u16(0);
154
154
  if (format === 3) {
155
155
  const inputAt = 4 + t.u16(2) * 2;
@@ -210,30 +210,11 @@ class Gsub {
210
210
  let found = this.cache.get(index);
211
211
  if (found === undefined) {
212
212
  const table = this.lookups.part(this.lookups.u16(2 + index * 2));
213
- const type = table.u16(0);
214
213
  const flags = table.u16(2);
215
- const count = table.u16(4);
216
- const markSet = (flags & USE_MARK_FILTERING_SET) !== 0 ? table.u16(6 + count * 2) : -1;
217
- const subtables: Reader[] = [];
218
- let subtype = type;
219
- for (let s = 0; s < count; s++) {
220
- const subtable = table.part(table.u16(6 + s * 2));
221
- if (type === 7) {
222
- subtype = subtable.u16(2);
223
- subtables.push(subtable.part(subtable.u32(4)));
224
- } else subtables.push(subtable);
225
- }
226
- const { glyphClass, markAttachClass, inMarkSet } = this.filter;
227
- const skip = (glyph: number): boolean => {
228
- const kind = glyphClass(glyph);
229
- if ((flags & IGNORE_BASE) !== 0 && kind === 1) return true;
230
- if ((flags & IGNORE_LIGATURES) !== 0 && kind === 2) return true;
231
- if (kind !== 3) return false;
232
- if ((flags & IGNORE_MARKS) !== 0) return true;
233
- if (markSet >= 0) return !inMarkSet(markSet, glyph);
234
- const attach = flags >> 8;
235
- return attach !== 0 && markAttachClass(glyph) !== attach;
236
- };
214
+ const parts = subtablesOf(table, 7);
215
+ const subtables = parts.map((part) => part[1]);
216
+ const subtype = parts.at(-1)?.[0] ?? table.u16(0);
217
+ const skip = lookupSkip(table, flags, this.filter);
237
218
  found = { type: subtype, flags, subtables, skip };
238
219
  this.cache.set(index, found);
239
220
  }
@@ -349,8 +330,9 @@ class Gsub {
349
330
  return -1;
350
331
  }
351
332
 
352
- private previousOf(lookup: Lookup, glyphs: readonly number[], from: number): number {
353
- for (let j = from; j >= 0; j--) if (!lookup.skip(glyphs[j]!)) return j;
333
+ /** This function finds the next glyph of a backtrack or a lookahead. As in HarfBuzz, a joiner does not stop the context. */
334
+ private contextOf(lookup: Lookup, glyphs: readonly number[], from: number, step: 1 | -1): number {
335
+ for (let j = from; j >= 0 && j < glyphs.length; j += step) if (!lookup.skip(glyphs[j]!) && !this.filter.joiners?.includes(glyphs[j]!)) return j;
354
336
  return -1;
355
337
  }
356
338
 
@@ -372,7 +354,7 @@ class Gsub {
372
354
  private matchBacktrack(lookup: Lookup, glyphs: readonly number[], i: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
373
355
  let at = i;
374
356
  for (let k = 0; k < count; k++) {
375
- at = this.previousOf(lookup, glyphs, at - 1);
357
+ at = this.contextOf(lookup, glyphs, at - 1, -1);
376
358
  if (at < 0 || !this.admits(at, i, false) || !test(k, glyphs[at]!)) return false;
377
359
  }
378
360
  return true;
@@ -381,7 +363,7 @@ class Gsub {
381
363
  private matchLookahead(lookup: Lookup, glyphs: readonly number[], first: number, last: number, count: number, test: (k: number, glyph: number) => boolean): boolean {
382
364
  let at = last;
383
365
  for (let k = 0; k < count; k++) {
384
- at = this.nextOf(lookup, glyphs, at + 1);
366
+ at = this.contextOf(lookup, glyphs, at + 1, 1);
385
367
  if (at < 0 || !this.admits(at, first, false) || !test(k, glyphs[at]!)) return false;
386
368
  }
387
369
  return true;
@@ -634,19 +616,8 @@ class Gsub {
634
616
  * HarfBuzz applies them. The lookups include the lookups of the necessary feature of the language system.
635
617
  */
636
618
  export function readSubstitutions(gsub: Reader, script: string, features: readonly string[], filter: GlyphFilter): SubstitutionLookup[] {
637
- const scripts = gsub.part(gsub.u16(4));
638
619
  const featureList = gsub.part(gsub.u16(6));
639
- const scriptCount = scripts.u16(0);
640
- let langSys: Reader | undefined;
641
- for (const wanted of scriptTags(script)) {
642
- for (let i = 0; i < scriptCount && langSys === undefined; i++) {
643
- if (scripts.tag(2 + i * 6) !== wanted) continue;
644
- const table = scripts.part(scripts.u16(2 + i * 6 + 4));
645
- const fallback = table.u16(0);
646
- if (fallback !== 0) langSys = table.part(fallback);
647
- }
648
- if (langSys !== undefined) break;
649
- }
620
+ const langSys = languageSystem(gsub, script);
650
621
  if (langSys === undefined || features.length === 0) return [];
651
622
  const wanted = new Set(features);
652
623
  const indices = new Map<number, string[]>();
@@ -1,8 +1,9 @@
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 segments of a canvas, the default features and the tables of a font file.
3
+ * the shaping words, the Indic syllables, 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 { indicSyllables, type IndicSyllableType } from "./fonts/indic.ts";
6
7
  export { canvasSegments, canvasWords } from "./fonts/words.ts";
7
8
  export { defaultFeatures } from "./fonts/substitution.ts";
8
9
  export { readTables } from "./fonts/sfnt.ts";
package/src/fonts.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { measureWidth, readFont, type Font, type MeasureOptions, type ReadOptions } from "./fonts/font.ts";
6
6
  export { widthBound, type WidthBound } from "./fonts/bound.ts";
7
+ export { shapingRisks, type ShapingRisk, type ShapingRiskCode } from "./fonts/risks.ts";
7
8
  export { engines, isEngineName, type EngineName, type EngineRules } from "./fonts/engines.ts";
8
9
  export type { Decompress } from "./fonts/sfnt.ts";
9
10
  export type { Axis, Instance } from "./fonts/variations.ts";