Skip to content

Commit f6b53ca

Browse files
committed
charge glyph outlines to the point budget, find spans in logarithmic time and keep textPaths on long paths working
1 parent 95ee8c7 commit f6b53ca

7 files changed

Lines changed: 98 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
137137
### Fixes
138138

139139
- `renderSVG()` bounds the points paths are made of: an arc between far-apart ends is drawn with at most 64 curves a turn (a 139-byte path, `M 1e25 100 A 40 30 20 1 1 160 100`, stroked, ran the process out of memory), and the curves of arcs and the points of all paths, also of each copy drawn through `<use>`, count against 2^25 points plus 4 per pixel of the output in one render and 2^21 in one path. Reading path data and placing text along a `<textPath>` count, too, and SVGs embedded as images share the budget of the render they are in. More throw a `LimitError` (which a text's layout no longer takes for a damaged font). A path drawn through `<use>` is read once a render instead of once a copy.
140-
- Very long SVG text (50,000 characters) no longer overflows the call stack.
140+
- SVG text: the glyph outlines of long texts count against the render's points before they are made (20,000 characters of a complex font ran the process out of memory), many `<tspan>`s in one `<text>` take linear time (10,000 took 20 s), and a `<textPath>` on a long path (up to 2^21 commands) renders at a normal size.
141+
- Very long text (50,000 characters in SVG, 200,000 combining marks or lines in `renderText()`) no longer overflows the call stack or says the font is damaged.
141142
- Binary data and dates of other realms (iframes, `node:vm`, Jest) are accepted; objects that only claim to be one by `Symbol.toStringTag` aren't, and a detached buffer throws a `TypeError` that says so.
142143
- `encodeJPEG()` and `encodeWebP()` check the image's size before going over its pixels; `metadata.creationTime` of another type than a `Date`, a number or a string throws a `TypeError` (`true` was 1970).
143144
- `Colors.gradient()` has the later stop's color at every hard edge (two stops at one position), like CSS, also inside the gradient and with 2 stops.

‎src/render/svg-text.ts‎

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,8 @@ export interface TextInput<S> {
435435
vertical: boolean;
436436
/** the scale the text is drawn at, for the precision of text on paths */
437437
scale: number;
438+
/** called with the number of commands of each glyph outline before it is placed, to bound long texts */
439+
charge?: (commands: number) => void;
438440
}
439441

440442
export interface SpanOutput<S> {
@@ -502,7 +504,19 @@ function upright(u: number): boolean {
502504
|| (u >= 0x2460 && u <= 0x24ff) || (u >= 0x2600 && u <= 0x27bf && u !== 0x2771 && u !== 0x2770);
503505
}
504506

505-
const spanAt = <S>(chunk: ChunkInput<S>, i: number): SpanInput<S> | undefined => chunk.spans.find(s => i >= s.start && i < s.end);
507+
// (the spans of a chunk are disjoint: found by a binary search over their starts, kept per chunk, as a find over them
508+
// made many spans, a tspan each, quadratic)
509+
const sortedSpans = new WeakMap<object, unknown[]>();
510+
const spanAt = <S>(chunk: ChunkInput<S>, i: number): SpanInput<S> | undefined => {
511+
let spans = sortedSpans.get(chunk.spans) as SpanInput<S>[] | undefined;
512+
if (!spans) sortedSpans.set(chunk.spans, spans = chunk.spans.slice().sort((a, b) => a.start - b.start));
513+
let low = 0, high = spans.length - 1, found = -1;
514+
while (low <= high) {
515+
const mid = (low + high) >>> 1;
516+
if (spans[mid].start <= i) { found = mid; low = mid + 1; } else high = mid - 1;
517+
}
518+
return found >= 0 && i < spans[found].end ? spans[found] : undefined;
519+
};
506520

507521
/**
508522
* Shapes a chunk (in visual order): runs of one embedding level, script and features, and of the span faces or one
@@ -1044,6 +1058,21 @@ export function layOutText<S>(text: TextInput<S>, fonts: FontFace[], fallback: F
10441058
const position = chunk.path ? positionOnPath(text, chunk, clusters, shiftOf) : positionLinear(text, chunk, clusters);
10451059

10461060
const textMatrix = text.vertical && !chunk.path ? rotate(IDENTITY, 90, x, y) : IDENTITY;
1061+
// the clusters of each span, by their index (the spans are disjoint, in order): a span looks at its own, not at
1062+
// all of the chunk's, which took quadratic time for many spans (a tspan each)
1063+
const owned = new Map<SpanInput<S>, number[]>(), ordered = chunk.spans.slice().sort((a, b) => a.start - b.start);
1064+
clusters.forEach((c, i) => {
1065+
let low = 0, high = ordered.length - 1, found = -1;
1066+
while (low <= high) {
1067+
const mid = (low + high) >>> 1;
1068+
if (ordered[mid].start <= c.start) { found = mid; low = mid + 1; } else high = mid - 1;
1069+
}
1070+
if (found < 0 || c.start >= ordered[found].end) return;
1071+
const list = owned.get(ordered[found]);
1072+
if (list) list.push(i); else owned.set(ordered[found], [i]);
1073+
});
1074+
// (the bounding box of all clusters, from the metrics, is the same for spans with the same shift)
1075+
const boxed = new Set<number>();
10471076
for (const span of chunk.spans) {
10481077
const face = primary.get(span);
10491078
if (!face) continue;
@@ -1055,13 +1084,16 @@ export function layOutText<S>(text: TextInput<S>, fonts: FontFace[], fallback: F
10551084

10561085
// decorations: one line per run of the span's clusters without relative shifts between them
10571086
const runs: Array<{ width: number, transform: Matrix }> = [];
1058-
let current: { width: number, transform: Matrix } | null = null;
1059-
for (const c of clusters) {
1060-
if (c.start >= span.start && c.start < span.end) {
1061-
if (current && c.hasRelativeShift) current = null;
1062-
if (!current) runs.push(current = { width: c.advance, transform: c.transform });
1063-
else current.width += c.advance;
1064-
} else current = null;
1087+
let current: { width: number, transform: Matrix } | null = null, previous = -2;
1088+
const own = owned.get(span) ?? [];
1089+
for (const i of own) {
1090+
const c = clusters[i];
1091+
// (a cluster of another span between two of this one ends the run)
1092+
if (i !== previous + 1) current = null;
1093+
previous = i;
1094+
if (current && c.hasRelativeShift) current = null;
1095+
if (!current) runs.push(current = { width: c.advance, transform: c.transform });
1096+
else current.width += c.advance;
10651097
}
10661098
const decoration = (paint: S | null, offset: number, list: Array<{ path: PathCommand[], paint: S }>): void => {
10671099
if (!paint || !runs.length) return;
@@ -1077,18 +1109,29 @@ export function layOutText<S>(text: TextInput<S>, fonts: FontFace[], fallback: F
10771109
decoration(span.lineThrough, text.vertical ? 0 : -face.lineThroughPosition * s, out.after);
10781110

10791111
let any = false;
1080-
for (const c of clusters) {
1112+
const shift = chunk.path ? 0 : shiftOf(span);
1113+
if (!boxed.has(shift)) {
1114+
boxed.add(shift);
1115+
for (const c of clusters) {
1116+
if (!c.visible) continue;
1117+
// (the bounding box from the metrics, of all clusters)
1118+
extend(rectPath(multiply(spanMatrix, multiply(c.transform, c.pathTransform)), 0, -c.ascent, c.advance > 0 ? c.advance : 1, c.ascent - c.descent));
1119+
}
1120+
}
1121+
for (const i of own) {
1122+
const c = clusters[i];
10811123
if (!c.visible) continue;
1082-
// (the bounding box from the metrics, of all clusters)
10831124
const m = multiply(spanMatrix, multiply(c.transform, c.pathTransform));
1084-
extend(rectPath(m, 0, -c.ascent, c.advance > 0 ? c.advance : 1, c.ascent - c.descent));
1085-
if (c.start < span.start || c.start >= span.end) continue;
10861125
any = true;
10871126
for (const g of c.glyphs) {
10881127
const gs = c.fontSize / g.face.font.unitsPerEm, matrix = scale(translate(scale(m, gs, gs), g.x, -g.y), 1, -1);
10891128
const kind = colorKind(g.face, g.glyph, c.fontSize);
10901129
if (kind) out.colors.push({ face: g.face, glyph: g.glyph, kind, fontSize: c.fontSize, matrix });
1091-
else placeOutline(out.glyphs, g.face.font.outline(g.glyph), matrix);
1130+
else {
1131+
const outline = g.face.font.outline(g.glyph);
1132+
text.charge?.(outline.length);
1133+
placeOutline(out.glyphs, outline, matrix);
1134+
}
10921135
}
10931136
}
10941137
if (any || out.before.length || out.after.length) spans.push(out);

‎src/render/svg.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1362,7 +1362,7 @@ class Document {
13621362
collect(root);
13631363

13641364
const mode = textStyle['writing-mode'];
1365-
return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale };
1365+
return { chunks, dx, dy, rotate: rotations, vertical: mode === 'tb' || mode === 'tb-rl' || mode === 'vertical-rl' || mode === 'vertical-lr', scale, charge: pointCounter() };
13661366
}
13671367

13681368
// a textPath's path (the shape it references, with its transform) and its start offset
@@ -1372,7 +1372,7 @@ class Document {
13721372
if (!target || !raw || !raw.length) return null;
13731373
// (the text is placed along the path, measured for each copy drawn through <use>: a command takes about the time
13741374
// of flattening 16 points, measuring its length to place the glyphs)
1375-
pointCounter()(16 * raw.length);
1375+
chargePoints(16 * raw.length);
13761376
const m = target.attrs.transform ? originTransform(target.attrs.transform, target.attrs['transform-origin'], viewport) : null;
13771377
const path = m ? raw.map(c => [c[0], ...transformPoints(c.slice(1) as number[], m)] as PathCommand) : raw;
13781378
const offset = (node.attrs.startOffset ?? '').trim();
@@ -3414,6 +3414,11 @@ function pointCounter(): (points: number) => void {
34143414
};
34153415
}
34163416

3417+
/** charges points to the render's budget, without the limit of one path */
3418+
function chargePoints(points: number): void {
3419+
if ((pointsLeft -= points) < 0) pointCounter()(0);
3420+
}
3421+
34173422
function parsePath(d: string): PathCommand[] {
34183423
const path: PathCommand[] = [];
34193424
// (the curves of arcs count, before they are made: an arc between far-apart ends was 1024 curves a turn)
@@ -3429,7 +3434,7 @@ function parsePath(d: string): PathCommand[] {
34293434
}
34303435
// (reading takes about the time of flattening 2 points a number or command: it counts against the render's points,
34313436
// so a path read again and again, the copies of one not kept, or many different ones, is bounded like its points)
3432-
if ((pointsLeft -= 2 * items.length) < 0) pointCounter()(0);
3437+
chargePoints(2 * items.length);
34333438

34343439
let i = 0;
34353440
let command: string | null = null;

‎src/render/text.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
233233
// paragraphs end at hard line breaks (CR LF, CR, LF, NEL, LS, PS)
234234
const paragraphs = text.split(/\r\n|[\r\n\u0085\u2028\u2029]/);
235235
const lines: Line[] = [];
236-
for (const paragraph of paragraphs) lines.push(...layOutParagraph(analyze(paragraph, fonts.length, font), layout, font, size, features));
236+
// (loops, not spreads: 200,000 lines or marks are more than a call takes arguments)
237+
for (const paragraph of paragraphs) for (const line of layOutParagraph(analyze(paragraph, fonts.length, font), layout, font, size, features)) lines.push(line);
237238

238239
// lines that fit into the height, chosen by the vertical alignment
239240
let visible = lines;
@@ -333,7 +334,7 @@ function analyze(text: string, count: number, font: (i: number) => SizedFont): P
333334
}
334335
return first;
335336
};
336-
const normalized = (grapheme: number[], form: string): number[] => Array.from(String.fromCodePoint(...grapheme).normalize(form), char => char.codePointAt(0) as number);
337+
const normalized = (grapheme: number[], form: string): number[] => Array.from(grapheme.map(c => String.fromCodePoint(c)).join('').normalize(form), char => char.codePointAt(0) as number);
337338

338339
const graphemes = graphemeBoundaries(codepoints), fontOf = new Int32Array(n);
339340
for (let start = 0; start < n;) {

‎tests/svg-arcs.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ const cases = {
4848
// long text in a clip path and as text: its glyphs were collected with spreads, past the call stack's limit
4949
'long text in a clip path': `<svg ${NS} width="10" height="10"><clipPath id="c"><text font-size="1" y="5">${'W'.repeat(50000)}</text></clipPath><rect width="10" height="10" clip-path="url(#c)"/></svg>`,
5050
'long text': `<svg ${NS} width="10" height="10"><text font-size="1" y="5">${'W'.repeat(50000)}</text></svg>`,
51+
// a long path with one label (a map's contour line), at a normal size: only many copies of it are too much
52+
'textPath on one long path': `<svg viewBox="0 0 100 100" width="100" height="100" ${NS}><defs><path id="p" d="M0 0${'L1 1L0 0'.repeat(80000)}"/></defs><text font-size="5"><textPath href="#p">A</textPath></text></svg>`,
53+
// long text builds every glyph's outline: they count against the budget before they are made
54+
'long text with complex glyphs': `<svg viewBox="0 0 100 100" width="10" height="10" ${NS}><text font-size="1" font-family="carbon">${'A'.repeat(20000)}</text></svg>`,
55+
// many tspans in one text took quadratic time
56+
'many tspans': `<svg viewBox="0 0 100 100" width="10" height="10" ${NS}><text font-size="1">${'<tspan>A</tspan>'.repeat(10000)}</text></svg>`,
5157
// a path of lines only, drawn 90000 times through <use> without painting anything: no budget counted its points
5258
'lines through use': (() => {
5359
let defs = `<path id="g0" d="M0 0${'h1h-1'.repeat(50000)}" fill="none"/>`;
@@ -70,6 +76,7 @@ try {
7076
}
7177
if (output.result !== 'ok' && !output.result.startsWith('LimitError')) panic(`${name}: ${output.result}`);
7278
if (name === 'textPath along a too long path' && !output.result.startsWith('LimitError')) panic(`${name}: should throw a LimitError`);
79+
if (name === 'textPath on one long path' && output.result !== 'ok') panic(`${name}: ${output.result}, it is a normal document`);
7380
if (Date.now() - begin > 20000) panic(`${name}: took ${Date.now() - begin} ms`);
7481
if (output.mb > 768) panic(`${name}: took ${output.mb} MB`);
7582
console.log(name, output.result.slice(0, 60), `${Date.now() - begin} ms`, `${output.mb} MB`);

‎tests/text-spreads.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const {Image} = require('..');
2+
const fs = require('fs');
3+
4+
const panic = message => {
5+
console.error(message);
6+
process.exit(1);
7+
};
8+
9+
// text with 200,000 combining marks or lines is laid out like any other: the arrays of its parts are not spread into a
10+
// call (past the stack's limit), and a failure doesn't blame the font
11+
(async () => {
12+
const font = fs.readFileSync(__dirname + '/fonts/resvg/NotoSans-Regular.ttf');
13+
for (const [name, text, options] of [
14+
['combining marks', 'a' + '\u0301'.repeat(200000), {}],
15+
['lines', 'a '.repeat(200000), {width: 1}],
16+
]) {
17+
const result = await Image.renderText(text, {font, size: 1, maxPixels: 1e8, ...options}).then(() => 'ok', err => err);
18+
if (result !== 'ok' && !(result instanceof RangeError && !/damaged/.test(result.message))) panic(`${name}: ${result}`);
19+
if (/damaged/.test(String(result.message))) panic(`${name}: blames the font: ${result.message}`);
20+
}
21+
})();

‎tests/util/render-svg.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const fs = require('fs');
88
const svg = fs.readFileSync(process.argv[2], 'utf8');
99
let result = 'ok';
1010
try {
11-
await Image.renderSVG(svg, {...(/width="10"/.test(svg) ? {maxPixels: 100} : {width: 50}), font: fs.readFileSync('./tests/fonts/resvg/NotoSans-Regular.ttf')});
11+
await Image.renderSVG(svg, {...(/width="10"/.test(svg) ? {maxPixels: 100} : {width: 50}), font: fs.readFileSync(svg.includes('font-family="carbon"') ? './tests/fonts/carbon phyber.ttf' : './tests/fonts/resvg/NotoSans-Regular.ttf')});
1212
} catch (error) {
1313
result = `${error.name}: ${error.message}`;
1414
}

0 commit comments

Comments
 (0)