From 2e39fea37e8a656821b8f2e68fa9029d48bf1dae Mon Sep 17 00:00:00 2001 From: Calixte Denizet Date: Sat, 21 Nov 2026 20:02:06 +0100 Subject: [PATCH] Build the text layer items from the runs of glyphs drawn on the same baseline Group glyphs with the same baseline, font and transform into runs. Infer word spaces from the positions and tracking within each run, and split runs into spans at wide gaps. Compute span advances in the worker from the generated font metrics so the text layer can lay out simple spans without measuring them. Find uses the same extracted items as the text layer. --- src/core/document.js | 12 +- src/core/evaluator.js | 186 +++++-- src/core/text_extraction.js | 651 +++++++++++++++++++++++ src/core/text_layer_font.js | 275 +++++----- src/display/api.js | 2 + src/display/text_layer.js | 89 ++-- test/integration/test_utils.mjs | 2 +- test/integration/text_extractor_spec.mjs | 2 +- test/integration/text_layer_spec.mjs | 29 +- test/unit/api_spec.js | 237 ++++++--- test/unit/pdf_find_controller_spec.js | 8 +- test/unit/test_utils.js | 33 ++ test/unit/text_layer_font_spec.js | 56 +- test/unit/text_layer_spec.js | 51 +- web/pdf_find_controller.js | 5 +- web/text_layer_builder.css | 4 + 16 files changed, 1300 insertions(+), 342 deletions(-) create mode 100644 src/core/text_extraction.js diff --git a/src/core/document.js b/src/core/document.js index e9553e643..4e3540eed 100644 --- a/src/core/document.js +++ b/src/core/document.js @@ -78,7 +78,7 @@ import { PDFImage } from "./image.js"; import { StreamsSequenceStream } from "./decode_stream.js"; import { stringToPDFString } from "./string_utils.js"; import { StructTreePage } from "./struct_tree.js"; -import { TextLayerFonts } from "./text_layer_font.js"; +import { TextExtraction } from "./text_extraction.js"; import { WasmImage } from "./wasm_image.js"; import { XRef } from "./xref.js"; @@ -715,8 +715,8 @@ class Page { const partialEvaluator = this._createPartialEvaluator(handler); // The text is buffered until the fonts of the page are known. - const textLayerFonts = sink - ? new TextLayerFonts(sink, this._localIdFactory, debugTextLayerFonts) + const textExtraction = sink + ? new TextExtraction(sink, this._localIdFactory, debugTextLayerFonts) : null; await partialEvaluator.getTextContent({ @@ -725,13 +725,13 @@ class Page { resources, includeMarkedContent, disableNormalization, - textLayerFonts, - sink: textLayerFonts, + textExtraction, + sink: textExtraction, viewBox: this.view, lang, intersector, }); - textLayerFonts?.send(); + textExtraction?.send(); } async getStructTree() { diff --git a/src/core/evaluator.js b/src/core/evaluator.js index 3599fb966..1ea5ae41d 100644 --- a/src/core/evaluator.js +++ b/src/core/evaluator.js @@ -75,6 +75,7 @@ import { RegionalImageCache, } from "./image_utils.js"; import { parseMarkedContentProps, textSinkWrapper } from "./evaluator_utils.js"; +import { TextRuns, unmirrorTransform } from "./text_extraction.js"; import { BaseStream } from "./base_stream.js"; import { bidi } from "./bidi.js"; import { CharCodeMap } from "./char_code_map.js"; @@ -124,6 +125,9 @@ const PatternType = { // could easily end up hurting *overall* performance (e.g. rendering as well). const TEXT_CHUNK_BATCH_SIZE = 10; +// The page-space rise offset of the text drawn without Ts. +const NO_TEXT_RISE = Object.freeze([0, 0]); + const deferred = Promise.resolve(); // Callback function used when validating operation arguments. @@ -2382,7 +2386,7 @@ class PartialEvaluator { viewBox, lang = null, disableNormalization = false, - textLayerFonts = null, + textExtraction = null, keepWhiteSpace = false, prevRefs = null, intersector = null, @@ -2420,6 +2424,11 @@ class PartialEvaluator { styles: Object.create(null), lang, }; + const textRuns = + textExtraction && !keepWhiteSpace && !intersector + ? new TextRuns(item => textContent.items.push(item)) + : null; + const textLayerFonts = textExtraction?.fonts ?? null; const textContentItem = { initialized: false, str: [], @@ -2563,26 +2572,6 @@ class PartialEvaluator { const textSpaceMatrix = new Float32Array(6); const glyphTransform = new Float32Array(6); let lastFakeSpaceExtraCharId = -1; - // A Tz since the previous glyph leaves the em of the next gap unknown. - let hScaleChanged = false; - - // For a reflected transform with d > 0, move the origin along the baseline - // by the item width, then reverse the baseline direction. - function unmirrorTransform(transform, width) { - const a = transform[0]; - const b = transform[1]; - const c = transform[2]; - const d = transform[3]; - if (a * d - b * c >= 0 || d <= 0) { - return false; - } - const scale = width / Math.hypot(a, b); - transform[0] = -a; - transform[1] = -b; - transform[4] += a * scale; - transform[5] += b * scale; - return true; - } function pushWhitespace({ width = 0, @@ -2632,10 +2621,7 @@ class PartialEvaluator { return Util.transform(textState.ctm, result, result); } - function ensureTextContentItem() { - if (textContentItem.initialized) { - return textContentItem; - } + function ensureTextStyle() { const { font, loadedName } = textState; if (!seenStyles.has(loadedName)) { seenStyles.add(loadedName); @@ -2650,12 +2636,20 @@ class PartialEvaluator { style.fontSubstitution = font.systemFontInfo.css; style.fontSubstitutionLoadedName = font.systemFontInfo.loadedName; } - textLayerFonts?.addFont( + textExtraction?.addFont( loadedName, font, /* heightScaled = */ getType3HeightScale() !== 1 ); } + } + + function ensureTextContentItem() { + if (textContentItem.initialized) { + return textContentItem; + } + const { font, loadedName } = textState; + ensureTextStyle(); textContentItem.fontName = loadedName; const trm = (textContentItem.transform = getCurrentTextTransform()); @@ -2822,8 +2816,8 @@ class PartialEvaluator { // spacing measurement, even when the new position is on the same line. function resetTextMatrix() { textState.setTextMatrix(textState.textLineMatrix); - hScaleChanged = false; resetAdaptiveSpacing(); + textRuns?.resetTracking(); } function moveText(x, y) { @@ -3033,9 +3027,7 @@ class PartialEvaluator { } else { textContentItem.height += advanceY; } - } else if ( - !addFakeSpaces(advanceY, currentTransform, textOrientation) - ) { + } else if (!addFakeSpaces(advanceY, textOrientation)) { if (textContentItem.str.length === 0) { resetLastChars(); pushWhitespace({ height: Math.abs(advanceY) }); @@ -3127,7 +3119,7 @@ class PartialEvaluator { } else { textContentItem.width += advanceX; } - } else if (!addFakeSpaces(advanceX, currentTransform, textOrientation)) { + } else if (!addFakeSpaces(advanceX, textOrientation)) { if (textContentItem.str.length === 0) { resetLastChars(); pushWhitespace({ width: Math.abs(advanceX) }); @@ -3150,7 +3142,113 @@ class PartialEvaluator { return true; } + // Move the cursor along the writing direction. + function advanceTextMatrix(distance, vertical) { + if (vertical) { + textState.translateTextMatrix(0, -distance); + } else { + textState.translateTextMatrix(distance * textState.textHScale, 0); + } + } + + function buildTextRun(chars, extraSpacing) { + const { font, fontSize, fontMatrix, loadedName, textRise } = textState; + const { vertical } = font; + if (!chars) { + // A TJ number moves the cursor without painting a glyph or adding Tc. + advanceTextMatrix(extraSpacing, vertical); + return; + } + const glyphs = font.charsToGlyphs(chars); + const unitScale = fontMatrix[0] * 1000; + const spaceWidth = font.isType3Font + ? null + : (vertical ? Math.abs(font.defaultVMetrics[0]) : font.spaceWidth) * + unitScale; + const charSpacing = vertical + ? -textState.charSpacing + : textState.charSpacing; + const wordSpacing = vertical + ? -textState.wordSpacing + : textState.wordSpacing; + const charSpacingUnits = (1000 * charSpacing) / fontSize; + // The rise offset in page space, the same for all the glyphs. + let rise = null; + for (let i = 0, ii = glyphs.length; i < ii; i++) { + const glyph = glyphs[i]; + const { isWhitespace, isInvisibleFormatMark } = glyph.category; + const advance = + (vertical ? -glyph.vmetric[0] : glyph.width) * unitScale; + // The generated glyph has a positive extent even if W2 moves the + // cursor back up the column. Keep the signed advance for positioning. + const extent = vertical ? Math.abs(advance) : advance; + const spacing = + charSpacing + + (glyph.isSpace ? wordSpacing : 0) + + (i + 1 === ii ? extraSpacing : 0); + if (isWhitespace) { + textLayerFonts?.addGlyph(font, " ", extent); + textRuns.addSpace(); + } else if (!isInvisibleFormatMark) { + // TextRuns copies what it keeps from the shared transform. + const transform = getCurrentTextTransform(glyphTransform); + const c = transform[2], + d = transform[3], + x = transform[4], + y = transform[5]; + const endX = x + ((vertical ? -c : transform[0]) * advance) / 1000; + const endY = y + ((vertical ? -d : transform[1]) * advance) / 1000; + const unicode = disableNormalization + ? glyph.unicode + : glyph.normalizedUnicode; + if ( + unicode && + Math.max(x, endX) >= viewBox[0] && + Math.min(x, endX) <= viewBox[2] && + Math.max(y, endY) >= viewBox[1] && + Math.min(y, endY) <= viewBox[3] + ) { + ensureTextStyle(); + if (!rise) { + // The transform's y axis is scaled by the Type 3 height scale. + const riseScale = textRise / (fontSize * getType3HeightScale()); + rise = textRise ? [c * riseScale, d * riseScale] : NO_TEXT_RISE; + } + textRuns.addGlyph( + loadedName, + transform, + rise, + unicode, + glyph.isUnicodeVisual, + extent, + charSpacingUnits, + spaceWidth, + vertical + ); + textLayerFonts?.addGlyph(font, unicode, extent); + } + } + advanceTextMatrix((advance * fontSize) / 1000 + spacing, vertical); + } + } + function buildTextContentItem({ chars, extraSpacing }) { + if ( + textRuns && + textState.fontSize > 0 && + textState.textHScale > 0 && + textState.fontMatrix[0] > 0 + ) { + // A text state outside the run extractor may have left an item open. + if (textContentItem.initialized) { + flushTextContentItem(); + } + textContentItem.prevTransform = null; + resetLastChars(); + buildTextRun(chars, extraSpacing); + return; + } + textRuns?.reset(); if ( currentFontSize !== textState.fontSize || (currentFontName !== textState.fontName && @@ -3190,10 +3288,8 @@ class PartialEvaluator { const glyphs = font.charsToGlyphs(chars); const scale = textState.fontMatrix[0] * textState.fontSize; - // Converts the glyph widths to 1/1000 of the text layer em. - const advanceScale = Math.abs( - (textState.fontMatrix[0] * 1000) / getType3HeightScale() - ); + // Converts the glyph widths to 1/1000 em. + const advanceScale = Math.abs(textState.fontMatrix[0] * 1000); for (let i = 0, ii = glyphs.length; i < ii; i++) { const glyph = glyphs[i]; @@ -3239,7 +3335,6 @@ class PartialEvaluator { const inView = isZeroWidthDiacritic || compareWithLastPosition(scaledDim); - hScaleChanged = false; if (!inView) { // The glyph is not in page so just skip it but move the cursor. if (!font.vertical) { @@ -3350,7 +3445,7 @@ class PartialEvaluator { } } - function addFakeSpaces(width, currentTransform, textOrientation) { + function addFakeSpaces(width, textOrientation) { lastFakeSpaceExtraCharId = -1; if ( textOrientation * textContentItem.spaceInFlowMin <= width && @@ -3360,19 +3455,6 @@ class PartialEvaluator { resetLastChars(); textContentItem.str.push(" "); lastFakeSpaceExtraCharId = intersector?.addExtraChar(" ") ?? -1; - if (textLayerFonts && !textContentItem.vertical && !hScaleChanged) { - // Measure the gap in page units, in the em along the baseline. - const emLength = - Math.hypot(currentTransform[0], currentTransform[1]) * - Math.abs(getType3HeightScale()); - if (emLength > 0) { - textLayerFonts.addSpaceGap( - textContentItem.fontName, - (1000 * Math.abs(width) * textContentItem.textAdvanceScale) / - emLength - ); - } - } } return false; } @@ -3397,6 +3479,7 @@ class PartialEvaluator { } function flushTextContentItem() { + textRuns?.flush(); if (!textContentItem.initialized || !textContentItem.str) { return; } @@ -3503,7 +3586,6 @@ class PartialEvaluator { case OPS.setHScale: if (textState.textHScale !== args[0] / 100) { textState.textHScale = args[0] / 100; - hScaleChanged = true; resetAdaptiveSpacing(); } break; @@ -3701,7 +3783,7 @@ class PartialEvaluator { viewBox, lang, disableNormalization, - textLayerFonts, + textExtraction, keepWhiteSpace, prevRefs: seenRefs, markedContentScope: xObjMarkedContentScope, diff --git a/src/core/text_extraction.js b/src/core/text_extraction.js new file mode 100644 index 000000000..2d2e5c353 --- /dev/null +++ b/src/core/text_extraction.js @@ -0,0 +1,651 @@ +/* Copyright 2026 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + getTextAdvance, + isZeroWidth, + TextLayerFonts, +} from "./text_layer_font.js"; +import { AbortException } from "../shared/util.js"; +import { bidi } from "./bidi.js"; + +// These scripts can be fitted using the generated font's advances and the +// visual glyph order. Fullwidth digits and Kana prolonged sound marks have +// script Common. Contextual and mixed-direction runs use width fitting. +const SIMPLE_TEXT = + /^[ 0-9\u30fc\uff10-\uff19\uff70\p{sc=Latin}\p{sc=Greek}\p{sc=Cyrillic}\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Thai}\p{sc=Lao}\p{Mn}\p{P}\p{Sc}\p{Sm}\p{Sk}]+$/u; +const SIMPLE_RTL_TEXT = + /^[ \ufb50-\ufdff\ufe70-\ufefc\p{sc=Hebr}\p{Mn}\p{P}]+$/u; +const GAP_STEP = 5; // thousandths of an em +const MIN_SPACE_GAP = 30; +const MAX_GLYPH_OVERLAP = 200; +const MAX_INLINE_SPACE = 600; // thousandths of an em +// In page units, how far the cursor can move back before the previous glyph's +// origin and stay in its run. +const POSITION_TOLERANCE = 0.75; +// The word space heuristics of the original text extraction: a gap narrower +// than 0.102 em is tracking, and a font space wider than 1/3 em is unreliable. +const MIN_SPACE_THRESHOLD = 102; // thousandths of an em +const MAX_SPACE_WIDTH = 333; // thousandths of an em +// For Type 3 fonts, a fraction of the narrower adjacent glyph. +const TYPE3_SPACE_FACTOR = 0.25; + +// Offsets and advances along the baseline are in thousandths of an em. +function transformAt(transform, offset, vertical) { + const result = new Float32Array(transform); + result[4] += ((vertical ? -transform[2] : transform[0]) * offset) / 1000; + result[5] += ((vertical ? -transform[3] : transform[1]) * offset) / 1000; + return result; +} + +function makeItem(str, dir, transform, length, fontName) { + const vertical = dir === "ttb"; + return { + str, + dir, + transform, + width: vertical ? Math.hypot(transform[0], transform[1]) : length, + height: vertical ? length : Math.hypot(transform[2], transform[3]), + fontName, + hasEOL: false, + }; +} + +function makeSpaceItem(transform, advance, length, fontName, dir) { + return makeItem( + " ", + dir, + transformAt(transform, advance, dir === "ttb"), + Math.max(0, length), + fontName + ); +} + +function getSpaceThreshold(spaceWidth, leftAdvance, rightAdvance) { + if (spaceWidth === null) { + // Type 3 glyph widths can be far outside the usual range of an em. + const left = Math.abs(leftAdvance); + const right = Math.abs(rightAdvance); + return ( + TYPE3_SPACE_FACTOR * (Math.min(left, right) || left || right) || + MIN_SPACE_THRESHOLD + ); + } + // Half of the font space, between 0.102 and 0.1665 em. + return Math.max( + MIN_SPACE_THRESHOLD, + Math.min(spaceWidth || 0, MAX_SPACE_WIDTH) / 2 + ); +} + +function hasSameAxes(left, right) { + return ( + left[0] === right[0] && + left[1] === right[1] && + left[2] === right[2] && + left[3] === right[3] + ); +} + +// For a reflected transform with d > 0, move the origin along the baseline +// by the item width, then reverse the baseline direction. +function unmirrorTransform(transform, width) { + const a = transform[0]; + const b = transform[1]; + const c = transform[2]; + const d = transform[3]; + if (a * d - b * c >= 0 || d <= 0) { + return false; + } + const scale = width / Math.hypot(a, b); + transform[0] = -a; + transform[1] = -b; + transform[4] += a * scale; + transform[5] += b * scale; + return true; +} + +// The evaluator walks each content stream in PDF drawing order. A run retains +// the cursor positions on one baseline and with one font and text transform. +class TextRuns { + #emit; + + #run = null; + + // The run of the last glyph, which may already be flushed. + #prevRun = null; + + #prevGlyph = null; + + // Copied, since the caller reuses its transform for the next glyph. + #prevTransform = new Float32Array(6); + + #prevTextRise = null; + + #space = false; + + #trackingStart = false; + + constructor(emit) { + this.#emit = emit; + } + + addSpace() { + this.#space = true; + } + + resetTracking() { + this.#trackingStart = true; + } + + addGlyph( + fontName, + transform, + textRise, + unicode, + isUnicodeVisual, + advance, + charSpacing, + spaceWidth, + vertical + ) { + // Project onto the writing axis: +x for horizontal text, -y for vertical. + const axis = vertical ? 2 : 0; + const sign = vertical ? -1 : 1; + const a = sign * transform[axis], + b = sign * transform[axis + 1], + x = transform[4], + y = transform[5]; + + const scale = Math.hypot(a, b) / 1000; + if (!scale || !Number.isFinite(scale)) { + return; + } + + let leadingSpace = null; + const prevRun = this.#prevRun; + if (prevRun && prevRun.vertical !== vertical) { + this.reset(); + } else if (prevRun) { + const base = this.#prevGlyph, + prevTransform = this.#prevTransform, + prevTextRise = this.#prevTextRise; + const { + scale: prevScale, + spaceWidth: prevSpaceWidth, + fontName: prevFontName, + } = prevRun; + const pa = sign * prevTransform[axis], + pb = sign * prevTransform[axis + 1]; + const baselineLength = 1000 * prevScale; + const dx = x - prevTransform[4], + dy = y - prevTransform[5]; + const along = (dx * pa + dy * pb) / baselineLength; + const across = (dy * pa - dx * pb) / baselineLength; + const riseX = textRise[0] - prevTextRise[0], + riseY = textRise[1] - prevTextRise[1]; + const lineShift = across - (riseY * pa - riseX * pb) / baselineLength; + const height = Math.hypot( + prevTransform[2 - axis], + prevTransform[3 - axis] + ); + const run = this.#run; + const sameFontAndAxes = + prevFontName === fontName && hasSameAxes(transform, prevTransform); + if ( + run && + sameFontAndAxes && + !this.#space && + Math.abs(lineShift) <= height && + isZeroWidth(unicode) + ) { + // Keep the mark with its base for bidi and kerning. Preserve the + // PDF advance and text-state spacing when the mark moves the cursor. + base.unicode += unicode; + base.advance += advance; + base.charSpacing += charSpacing; + return; + } + const gap = along / prevScale - base.advance; + // The cursor can move back from the end of a glyph, e.g. when a + // spacing accent is overprinted on the next glyph. Allow rounding + // errors at the cutoff so a 200-unit TJ can still be kerning. + const backwards = + along < -POSITION_TOLERANCE || + gap + 1e-6 < Math.min(base.charSpacing, 0) - MAX_GLYPH_OVERLAP; + const newLine = Math.abs(lineShift) > height * (backwards ? 0.5 : 1); + if (newLine) { + this.flush(true); + } else if ( + !run || + !sameFontAndAxes || + backwards || + Math.abs((y - run.transform[5]) * pa - (x - run.transform[4]) * pb) > + baselineLength * 0.25 + ) { + this.flush(); + // A gap to a mirrored glyph isn't measured from its edge. + if ( + !backwards && + a * pa + b * pb > 0 && + ((this.#space && gap > MIN_SPACE_GAP) || + gap - base.charSpacing > + getSpaceThreshold(prevSpaceWidth, base.advance, advance)) + ) { + leadingSpace = makeSpaceItem( + prevTransform, + base.advance, + gap * prevScale, + prevFontName, + vertical ? "ttb" : "ltr" + ); + } + } + } + + this.#run ??= { + fontName, + transform: transform.slice(), + scale, + spaceWidth, + vertical, + leadingSpace, + glyphs: [], + hasEOL: false, + }; + const { glyphs, transform: start } = this.#run; + const offset = + ((x - start[4]) * a + (y - start[5]) * b) / (1000 * scale * scale); + const glyph = { + unicode, + isUnicodeVisual, + offset, + advance, + charSpacing, + space: glyphs.length > 0 && this.#space, + trackingStart: this.#trackingStart, + }; + glyphs.push(glyph); + this.#prevRun = this.#run; + this.#prevGlyph = glyph; + this.#prevTransform.set(transform); + this.#prevTextRise = textRise; + this.#space = false; + this.#trackingStart = false; + } + + flush(hasEOL = false) { + const run = this.#run; + if (run) { + run.hasEOL = hasEOL; + this.#emit(run); + this.#run = null; + } else if (hasEOL && this.#prevRun) { + const { vertical, fontName } = this.#prevRun; + this.#emit({ + str: "", + dir: vertical ? "ttb" : "ltr", + transform: this.#prevTransform.slice(), + fontName, + width: 0, + height: 0, + hasEOL, + }); + } + } + + reset() { + this.flush(); + this.#prevRun = this.#prevGlyph = null; + this.#space = false; + } +} + +function getGap(left, right) { + return right.offset - left.offset - left.advance; +} + +function inferTracking(glyphs, start, end, threshold) { + const bins = new Map(); + let samples = 0; + for (let i = start + 1; i < end; i++) { + const left = glyphs[i - 1], + right = glyphs[i]; + if (right.space) { + continue; + } + const gap = getGap(left, right) - left.charSpacing; + const value = Math.round(gap / GAP_STEP) * GAP_STEP; + const bin = bins.get(value); + if (bin) { + bin.count++; + bin.differentPairs ||= + left.unicode !== bin.left || right.unicode !== bin.right; + } else { + bins.set(value, { + left: left.unicode, + right: right.unicode, + count: 1, + differentPairs: false, + }); + } + samples++; + } + + // Prefer the gap closest to zero when two bins are equally frequent. + let value = 0, + count = 0; + for (const [gap, { count: frequency }] of bins) { + if ( + frequency > count || + (frequency === count && Math.abs(gap) < Math.abs(value)) + ) { + value = gap; + count = frequency; + } + } + // A repeated pair alone is evidence of kerning. Repeated narrow gaps + // between different pairs are tracking. + if (!value || count < 2 || !bins.get(value).differentPairs) { + return 0; + } + if (Math.abs(value) <= threshold) { + return value; + } + // For wider gaps, look for a separate group of even wider word spaces. + const maxTracking = bins.keys().some(gap => gap > value + threshold) + ? 2.5 * threshold + : 1.5 * threshold; + return value > 0 && value < maxTracking && 2 * count >= samples ? value : 0; +} + +function inferSpaces({ glyphs, spaceWidth }, fonts, font) { + for (let start = 0, end; start < glyphs.length; start = end) { + end = start + 1; + while (end < glyphs.length && !glyphs[end].trackingStart) { + end++; + } + const tracking = + spaceWidth === null + ? 0 + : inferTracking(glyphs, start, end, getSpaceThreshold(spaceWidth)); + for (let i = Math.max(1, start); i < end; i++) { + const left = glyphs[i - 1], + right = glyphs[i]; + const gap = getGap(left, right); + // A line-positioning operator starts a new tracking measurement. There + // is no inferred tracking across the boundary between measurements. + const pairTracking = i === start ? 0 : tracking; + const adjustedGap = gap - left.charSpacing - pairTracking; + const threshold = getSpaceThreshold( + spaceWidth, + left.advance, + right.advance + ); + // Tracking also increases word spacing, but can occupy part of a word + // gap already encoded by the author. + right.space = right.space + ? gap > MIN_SPACE_GAP + : adjustedGap > (pairTracking > 0 ? 0.8 : 1) * threshold; + if (right.space && adjustedGap > 0) { + fonts.addSpaceGap(font, adjustedGap); + } + } + } +} + +function makeTextItem( + run, + first, + last, + str, + dir = run.vertical ? "ttb" : "ltr" +) { + const { glyphs, scale, fontName } = run; + const start = glyphs[first].offset; + const { offset, advance } = glyphs[last]; + const end = offset + advance; + return makeItem( + str, + dir, + transformAt(run.transform, start, run.vertical), + Math.abs(end - start) * scale, + fontName + ); +} + +function getTextParts(glyphs, first, last) { + const text = [glyphs[first].unicode]; + for (let i = first + 1; i <= last; i++) { + const { space, unicode } = glyphs[i]; + if (space) { + text.push(" "); + } + text.push(unicode); + } + return text; +} + +// Contextual shaping and mixed bidi need browser measurement. +function hasSimpleGlyphOrder({ str, dir }, parts, visualText) { + return dir === "rtl" + ? SIMPLE_RTL_TEXT.test(str) && str === parts.toReversed().join("") + : SIMPLE_TEXT.test(str) && str === visualText; +} + +function widthFittedItem(item, { advances }, visualText) { + const { str } = item; + // Even with simple glyph order, mirroring, variation selectors or NFC + // composition can change which glyphs the browser measures. + if ( + str.length > 1 && + /\S/.test(str) && + (item.dir !== "rtl" || !/\p{Bidi_Mirrored}/u.test(visualText)) && + !/\p{Variation_Selector}/u.test(visualText) && + visualText === visualText.normalize("NFC") + ) { + const width = getTextAdvance(visualText, advances); + if (width > 0) { + item.textLayerAdvance = width / 1000; + } + } + return item; +} + +function makeSpan(run, first, last, dir, metrics) { + const parts = getTextParts(run.glyphs, first, last); + const visualText = parts.join(""); + const str = dir === "rtl" ? parts.reverse().join("") : visualText; + return widthFittedItem( + makeTextItem(run, first, last, str, dir), + metrics, + visualText + ); +} + +function getBidiRun(run, onMirror) { + const { glyphs, vertical } = run; + const fullItem = makeTextItem(run, 0, glyphs.length - 1, ""); + const unmirrored = + !vertical && unmirrorTransform(fullItem.transform, fullItem.width); + // The glyphs tell bidi whether their Unicode is the shape to mirror. + const parts = []; + for (const glyph of glyphs) { + if (glyph.space) { + parts.push(" "); + } + parts.push(glyph); + } + if (unmirrored) { + parts.reverse(); + } + Object.assign(fullItem, bidi(parts, -1, vertical, onMirror)); + return { + run, + item: fullItem, + text: parts.map(part => part.unicode ?? part), + unmirrored, + }; +} + +function layoutRun({ run, item, text, unmirrored }, metrics, items) { + const visualText = text.join(""); + if (!hasSimpleGlyphOrder(item, text, visualText)) { + items.push(item); + return; + } + const { glyphs } = run; + const { dir } = item; + const start = items.length; + let first = 0; + // A wide gap, e.g. between two table cells, starts a new span. + for (let i = 1; !unmirrored && i < glyphs.length; i++) { + const left = glyphs[i - 1]; + const gap = glyphs[i].space ? getGap(left, glyphs[i]) : 0; + if (gap > MAX_INLINE_SPACE) { + items.push( + makeSpan(run, first, i - 1, dir, metrics), + makeSpaceItem( + run.transform, + left.offset + left.advance, + gap * run.scale, + run.fontName, + dir + ) + ); + first = i; + } + } + if (first === 0) { + items.push(widthFittedItem(item, metrics, visualText)); + return; + } + items.push(makeSpan(run, first, glyphs.length - 1, dir, metrics)); + if (dir === "rtl") { + for (let i = start, j = items.length - 1; i < j; i++, j--) { + const tmp = items[i]; + items[i] = items[j]; + items[j] = tmp; + } + } +} + +/** + * Infers word spaces and buffers the page to fit the spans to the advances + * of the generated fonts. + */ +class TextExtraction { + #chunks = []; + + #fonts = new Map(); + + #sink; + + constructor(sink, idFactory, debugFonts) { + this.#sink = sink; + this.fonts = new TextLayerFonts(idFactory, debugFonts); + } + + get ready() { + return this.#sink.isCancelled + ? Promise.reject(new AbortException("Text content stream cancelled.")) + : Promise.resolve(); + } + + get desiredSize() { + // The whole page is buffered to generate the fonts. + return Infinity; + } + + enqueue(chunk) { + const { fonts } = this; + const { items } = chunk; + for (let i = 0, ii = items.length; i < ii; i++) { + const run = items[i]; + if (!run.glyphs) { + continue; + } + const font = this.#fonts.get(run.fontName); + inferSpaces(run, fonts, font); + // The text has the logical characters of the mirrored glyphs, hence the + // generated font needs them too. + items[i] = getBidiRun(run, (glyph, unicode) => + fonts.addGlyph(font, unicode, glyph.advance) + ); + } + this.#chunks.push({ ...chunk }); + } + + #layoutItems(items, getMetrics) { + const result = []; + for (const entry of items) { + const { run } = entry; + if (!run) { + result.push(entry); + continue; + } + if (run.leadingSpace) { + result.push(run.leadingSpace); + } + const metrics = getMetrics(entry.item.fontName); + if (metrics) { + layoutRun(entry, metrics, result); + } else { + result.push(entry.item); + } + result.at(-1).hasEOL = run.hasEOL; + } + return result; + } + + addFont(name, font, heightScaled = false) { + this.#fonts.set(name, font); + if (heightScaled) { + this.fonts.addHeightScaledFont(font); + } + } + + send() { + const { fonts } = this; + if (this.#sink.isCancelled) { + return; + } + // The spans and the fonts use the same metrics. + const metrics = new Map(); + const computeMetrics = font => fonts.getMetrics(font); + const getFontMetrics = font => + metrics.getOrInsertComputed(font, computeMetrics); + const getMetrics = name => getFontMetrics(this.#fonts.get(name)); + for (const chunk of this.#chunks) { + chunk.items = this.#layoutItems(chunk.items, getMetrics); + } + const textLayerFonts = new Map(); + const build = font => fonts.build(font, getFontMetrics(font)); + for (const chunk of this.#chunks) { + for (const [name, style] of Object.entries(chunk.styles)) { + const textLayerFont = textLayerFonts.getOrInsertComputed( + this.#fonts.get(name), + build + ); + if (textLayerFont) { + style.textLayerFont = textLayerFont; + } + } + this.#sink.enqueue(chunk, chunk.items.length); + } + } +} + +export { TextExtraction, TextRuns, unmirrorTransform }; diff --git a/src/core/text_layer_font.js b/src/core/text_layer_font.js index 793e0755c..82020a41c 100644 --- a/src/core/text_layer_font.js +++ b/src/core/text_layer_font.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import { AbortException, BBOX_INIT, makeMap, Util } from "../shared/util.js"; +import { BBOX_INIT, makeMap, Util } from "../shared/util.js"; import { createCmapTable, createNameTable, createPostTable } from "./fonts.js"; import { DataBuilder } from "./data_builder.js"; import { OpenTypeFileBuilder } from "./opentype_file_builder.js"; @@ -26,13 +26,52 @@ const DEFAULT_SPACE_ADVANCE = 250; // The largest advance fitting in the hmtx table. const MAX_ADVANCE = (0xffff * 1000) / UNITS_PER_EM; // The browsers give no advance to these characters. -const ZERO_WIDTH_REGEXP = /^[\p{Mn}\p{Default_Ignorable_Code_Point}]$/u; +const ZERO_WIDTH_REGEXP = /^[\p{Mn}\p{Default_Ignorable_Code_Point}]+$/u; +// The browser shapes Thai and Lao SARA AM as a mark followed by SARA AA. +const SARA_AM_DECOMPOSITIONS = new Map([ + [0x0e33, [0x0e4d, 0x0e32]], + [0x0eb3, [0x0ecd, 0x0eb2]], +]); // For debugging, the glyphs can be their boxes, in font units. const DEBUG_STROKE_WIDTH = 80; let nameTable; let postTable; +function toFontUnits(advance) { + return Math.round((advance * UNITS_PER_EM) / 1000); +} + +function roundFontAdvance(advance) { + return (toFontUnits(advance) * 1000) / UNITS_PER_EM; +} + +function isZeroWidth(text) { + // No such character is below U+00AD (soft hyphen). + return text.charCodeAt(0) >= 0xad && ZERO_WIDTH_REGEXP.test(text); +} + +/** + * @param {string} text + * @param {Map} advances + * @returns {number} The advance of the text shaped by the browser, in 1/1000 + * em, or NaN if a character is missing. + */ +function getTextAdvance(text, advances) { + let width = 0; + for (const char of text) { + const codePoint = char.codePointAt(0); + if (!isZeroWidth(char)) { + width += roundFontAdvance( + advances.get(SARA_AM_DECOMPOSITIONS.get(codePoint)?.[1] ?? codePoint) + ); + } else if (!advances.has(codePoint)) { + return NaN; + } + } + return width; +} + function createStats() { return { advances: new Map(), @@ -105,6 +144,53 @@ function getMostFrequent(counts) { return best; } +function getAdvances(stats) { + const advances = new Map(); + for (const [codePoint, counts] of stats.advances) { + let advance = getMostFrequent(counts); + if (advance === 0 && counts.size > 1) { + // A nonzero glyph can be scaled to either width. + advance = counts.keys().find(width => width > 0) ?? 0; + } + advances.set(codePoint, advance); + } + // A character only drawn in ligatures gets what the others leave. + for (const [unicode, counts] of stats.ligatures) { + let known = 0; + const missing = []; + for (const char of unicode) { + const codePoint = char.codePointAt(0); + const advance = advances.get(codePoint); + if (advance === undefined) { + missing.push(codePoint); + } else { + known += advance; + } + } + if (!missing.length) { + continue; + } + const advance = + Math.max(getMostFrequent(counts) - known, 0) / missing.length; + for (const codePoint of missing) { + advances.set(codePoint, advance); + } + } + for (const [codePoint, [mark, base]] of SARA_AM_DECOMPOSITIONS) { + const advance = advances.get(codePoint); + if (advance !== undefined) { + advances.getOrInsert(mark, 0); + advances.getOrInsert(base, advance); + } + } + // Without a space glyph, e.g. with TeX fonts, a space gets the median gap. + if (!advances.has(0x20) && stats.spaceGaps.length > 0) { + const gaps = stats.spaceGaps.sort((a, b) => a - b); + advances.set(0x20, gaps[gaps.length >> 1]); + } + return advances; +} + /** * @param {number} width * @param {number} yMin @@ -278,62 +364,26 @@ function buildTextLayerFont( } /** - * Buffers the text content of a page and collects the advances of the glyphs - * of its fonts, then sends it with the text layer fonts built from them. + * Collects PDF glyph advances and builds the fonts for the text layer. */ class TextLayerFonts { - #buildBound = this.#build.bind(this); - - #chunks = []; - #drawBoxes; #heightScaled = new WeakSet(); #idFactory; - #loadedNames = new Map(); - - #sink; - #stats = new Map(); - desiredSize = Infinity; - /** - * @param {object} sink * @param {object} idFactory * @param {boolean} [drawBoxes] - Debug: draw glyph bounds. */ - constructor(sink, idFactory, drawBoxes = false) { - this.#sink = sink; + constructor(idFactory, drawBoxes = false) { this.#idFactory = idFactory; this.#drawBoxes = drawBoxes; } - get ready() { - // Stop the text extraction when the stream is cancelled. - return this.#sink.isCancelled - ? Promise.reject(new AbortException("Text content stream cancelled.")) - : Promise.resolve(); - } - - enqueue(chunk) { - // The evaluator reuses the chunk object. - this.#chunks.push({ ...chunk }); - } - - /** - * @param {string} loadedName - * @param {Font} font - */ - addFont(loadedName, font, heightScaled = false) { - this.#loadedNames.set(loadedName, font); - if (heightScaled) { - this.#heightScaled.add(font); - } - } - /** * @param {Font} font * @returns {object} The advance, ligature and space gap samples. @@ -351,88 +401,65 @@ class TextLayerFonts { if (!unicode) { return; } - const stats = this.#getStats(font); - const firstCodePoint = unicode.codePointAt(0); - if (unicode.length === (firstCodePoint > 0xffff ? 2 : 1)) { - if (firstCodePoint < 0xd800 || firstCodePoint > 0xdfff) { + const { advances, ligatures } = this.#getStats(font); + // Most PDF glyphs map to one UTF-16 code unit. + if (unicode.length === 1) { + if (unicode.isWellFormed()) { addCount( - stats.advances, - firstCodePoint, - ZERO_WIDTH_REGEXP.test(unicode) ? 0 : advance + advances, + unicode.charCodeAt(0), + isZeroWidth(unicode) ? 0 : advance ); } return; } - - const chars = []; + let text = "", + length = 0; for (const char of unicode) { - const codePoint = char.codePointAt(0); - if (codePoint >= 0xd800 && codePoint <= 0xdfff) { + if (!char.isWellFormed()) { continue; } - if (ZERO_WIDTH_REGEXP.test(char)) { - addCount(stats.advances, codePoint, 0); + if (isZeroWidth(char)) { + addCount(advances, char.codePointAt(0), 0); } else { - chars.push(char); + text += char; + length++; } } - if (chars.length === 1) { - addCount(stats.advances, chars[0].codePointAt(0), advance); - } else if (chars.length > 1) { - addCount(stats.ligatures, chars.join(""), advance); - } - } - - /** - * @param {string} loadedName - The font of the item. - * @param {number} gap - The gap replaced by a space, in 1/1000 em. - */ - addSpaceGap(loadedName, gap) { - const font = this.#loadedNames.get(loadedName); - if (font && Number.isFinite(gap)) { - this.#getStats(font).spaceGaps.push(gap); + if (length === 1) { + addCount(advances, text.codePointAt(0), advance); + } else if (length > 1) { + addCount(ligatures, text, advance); } } /** * @param {Font} font - * @returns {object|null} See `TextLayerFont` in the API. + * @param {number} gap - The gap replaced by a space, in 1/1000 em. */ - #build(font) { + addSpaceGap(font, gap) { + if (Number.isFinite(gap)) { + this.#getStats(font).spaceGaps.push(gap); + } + } + + /** + * @param {Font} font - A Type 3 font whose item height is its bbox height. + */ + addHeightScaledFont(font) { + this.#heightScaled.add(font); + } + + /** + * @param {Font} font + * @returns {object|null} The advances for fitting the spans. + */ + getMetrics(font) { const stats = this.#stats.get(font); if (!stats) { return null; } - const advances = new Map(); - for (const [codePoint, counts] of stats.advances) { - advances.set(codePoint, getMostFrequent(counts)); - } - // A character only drawn in ligatures gets what the others leave. - for (const [unicode, counts] of stats.ligatures) { - const codePoints = Array.from(unicode, char => char.codePointAt(0)); - let known = 0, - unknown = 0; - for (const codePoint of codePoints) { - const advance = advances.get(codePoint); - if (advance === undefined) { - unknown++; - } else { - known += advance; - } - } - if (!unknown) { - continue; - } - const advance = Math.max(getMostFrequent(counts) - known, 0) / unknown; - for (const codePoint of codePoints) { - advances.getOrInsert(codePoint, advance); - } - } - // Without a space glyph, e.g. with TeX fonts, a space gets the median gap. - if (!advances.has(0x20) && stats.spaceGaps.length > 0) { - const gaps = stats.spaceGaps.sort((a, b) => a - b); - advances.set(0x20, gaps[gaps.length >> 1]); - } + const advances = getAdvances(stats); // Use the smallest power of two that fits every advance in hmtx. let advanceScale = 1; for (const advance of advances.values()) { @@ -448,10 +475,35 @@ class TextLayerFonts { 0x20, Math.max(DEFAULT_SPACE_ADVANCE, (advanceScale * 1000) / UNITS_PER_EM) ); + if (advanceScale !== 1) { + // Keep the fitter in PDF units, quantized to exactly the advances the + // generated font will use. + for (const [key, value] of advances) { + const advance = roundFontAdvance(value / advanceScale) * advanceScale; + if (advance === 0 && value > 0) { + // See `buildTextLayerFont`. + return null; + } + advances.set(key, advance); + } + } + return { advances, advanceScale }; + } + + /** + * @param {Font} font + * @param {object|null} [metrics] - See `getMetrics`. + * @returns {object|null} See `TextLayerFont` in the API. + */ + build(font, metrics = this.getMetrics(font)) { + if (!metrics) { + return null; + } // Vertical glyphs are centered on their column. const ascent = font.vertical ? 0.5 : getAscentRatio(font, this.#heightScaled.has(font)); + const { advances, advanceScale } = metrics; const data = buildTextLayerFont( advances, ascent, @@ -468,25 +520,6 @@ class TextLayerFonts { advanceScale, }; } - - send() { - const sink = this.#sink; - if (sink.isCancelled) { - return; - } - // Only the fonts of the items, i.e. the ones with a style, are built. - const fonts = new Map(); - for (const chunk of this.#chunks) { - for (const [loadedName, style] of Object.entries(chunk.styles)) { - const font = this.#loadedNames.get(loadedName); - const textLayerFont = fonts.getOrInsertComputed(font, this.#buildBound); - if (textLayerFont) { - style.textLayerFont = textLayerFont; - } - } - sink.enqueue(chunk, chunk.items.length); - } - } } -export { buildTextLayerFont, TextLayerFonts }; +export { buildTextLayerFont, getTextAdvance, isZeroWidth, TextLayerFonts }; diff --git a/src/display/api.js b/src/display/api.js index 5bba5216e..571e5b697 100644 --- a/src/display/api.js +++ b/src/display/api.js @@ -1225,6 +1225,8 @@ class PDFDocumentProxy { * @property {string} fontName - Font name used by PDF.js for converted font. * @property {boolean} hasEOL - Indicating if the text content is followed by a * line-break. + * @property {number} [textLayerAdvance] - Advance of the text in the generated + * font, in em. */ /** diff --git a/src/display/text_layer.js b/src/display/text_layer.js index c3750ee8e..c570e9c69 100644 --- a/src/display/text_layer.js +++ b/src/display/text_layer.js @@ -74,6 +74,8 @@ class TextLayer { #layoutTextParams = null; + #newTextLayer = false; + #ownerDocument; #pageHeight = 0; @@ -232,6 +234,15 @@ class TextLayer { if (!this.#reader) { break; } + if ( + !this.#newTextLayer && + this.#fonts + .values() + .some(({ fontFace }) => fontFace.status === "loaded") + ) { + this.#newTextLayer = true; + this.#rootContainer.classList.add("newTextLayer"); + } } this.#processItems(value.items); } @@ -282,6 +293,7 @@ class TextLayer { } } this.#fonts.clear(); + this.#rootContainer.classList.remove("newTextLayer"); } /** @@ -388,12 +400,15 @@ class TextLayer { #appendText(geom) { // Initialize all used properties to keep the caches monomorphic. const textDiv = this.#ownerDocument.createElement("span"); + const isSpace = geom.str === " "; const textDivProperties = { angle: 0, canvasWidth: 0, hasText: geom.str !== "", hasEOL: geom.hasEOL, fontSize: 0, + fontAdvance: 0, + scaleX: 1, }; this.#textDivs.push(textDiv); @@ -404,24 +419,25 @@ class TextLayer { angle += Math.PI / 2; } - let fontFamily = - (this.#fontInspectorEnabled && style.fontSubstitution) || - style.fontFamily; - - // Workaround for bug 1922063. - fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; - let shouldScaleText = geom.str.length > 1; - let ascent; const { textLayerFont } = style; - if ( + let fontFamily, + ascent, + advanceScale = 1; + const hasTextLayerFont = textLayerFont && - this.#fonts.get(textLayerFont.name)?.fontFace.status === "loaded" - ) { - // The other fonts are only used for the characters missing in it. - fontFamily = `"${textLayerFont.name}", ${fontFamily}`; + this.#fonts.get(textLayerFont.name)?.fontFace.status === "loaded"; + if (hasTextLayerFont) { + fontFamily = textLayerFont.name; ascent = textLayerFont.ascent; - // Scaled advances need fitting even for a single character. - shouldScaleText ||= textLayerFont.advanceScale !== 1; + advanceScale = textLayerFont.advanceScale; + textDivProperties.fontAdvance = + (geom.textLayerAdvance ?? 0) / advanceScale; + } else { + fontFamily = + (this.#fontInspectorEnabled && style.fontSubstitution) || + style.fontFamily; + // Workaround for bug 1922063. + fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; } const fontHeight = Math.hypot(TX[2], TX[3]); const fontAscent = @@ -467,9 +483,14 @@ class TextLayer { if (angle !== 0) { textDivProperties.angle = angle * (180 / Math.PI); } + // Different PDF glyphs can map to the same character. The generated font + // has one advance for it, so even an isolated glyph may need width fitting. + let shouldScaleText = + geom.str.length > 1 || + (hasTextLayerFont && (!isSpace || advanceScale !== 1)); const scaleX = geom.transform[0], scaleY = geom.transform[3]; - if (!shouldScaleText && geom.str !== " " && scaleX !== scaleY) { + if (!shouldScaleText && !isSpace && scaleX !== scaleY) { // When the horizontal/vertical scaling differs significantly, also scale // even single-char text to improve highlighting (fixes issue11713.pdf). const absScaleX = Math.abs(scaleX), @@ -479,6 +500,9 @@ class TextLayer { } if (shouldScaleText) { textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; + if (!textDivProperties.canvasWidth && textDivProperties.fontAdvance > 0) { + textDivProperties.scaleX = 0; + } } // Finally, layout and append the text to the DOM. @@ -499,27 +523,32 @@ class TextLayer { #layout(params) { const { div, properties, ctx } = params; const { style } = div; - const { canvasWidth, fontSize } = properties; + const { canvasWidth, fontSize, fontAdvance } = properties; + let { scaleX } = properties; if (canvasWidth !== 0 && fontSize !== 0 && properties.hasText) { - const { fontFamily } = style; - // Firefox quantizes canvas font sizes after dividing by the device-pixel - // ratio. Measure at a quantized size, then rescale the width. - const pixelRatio = this.#pixelRatio; - const measuredSize = - TextLayer.#quantizeFontSize((fontSize * this.#scale) / pixelRatio) * - pixelRatio; + let width = fontAdvance * fontSize; + if (!width) { + // Firefox quantizes canvas font sizes after dividing by the + // device-pixel ratio. Measure at a quantized size, then rescale the + // width. + const pixelRatio = this.#pixelRatio; + const measuredSize = + TextLayer.#quantizeFontSize((fontSize * this.#scale) / pixelRatio) * + pixelRatio; - TextLayer.#ensureCtxFont(ctx, measuredSize, fontFamily); - const { width } = ctx.measureText(div.textContent); + TextLayer.#ensureCtxFont(ctx, measuredSize, style.fontFamily); + width = + (ctx.measureText(div.textContent).width * fontSize) / measuredSize; + } if (width > 0) { - style.setProperty( - "--scale-x", - (canvasWidth * measuredSize) / (width * fontSize) - ); + scaleX = canvasWidth / width; } } + if (scaleX !== 1) { + style.setProperty("--scale-x", scaleX); + } if (properties.angle !== 0) { style.setProperty("--rotate", `${properties.angle}deg`); } diff --git a/test/integration/test_utils.mjs b/test/integration/test_utils.mjs index 714ddd900..b65551b0a 100644 --- a/test/integration/test_utils.mjs +++ b/test/integration/test_utils.mjs @@ -169,7 +169,7 @@ function getTextLayerFonts(page) { .filter(isTextLayerFont); const used = new Set(); for (const span of document.querySelectorAll(".textLayer span")) { - const name = span.style.fontFamily.split(",")[0].replaceAll('"', ""); + const name = span.style.fontFamily.replaceAll('"', ""); if (isTextLayerFont(name)) { used.add(name); } diff --git a/test/integration/text_extractor_spec.mjs b/test/integration/text_extractor_spec.mjs index c665217b8..1523d8701 100644 --- a/test/integration/text_extractor_spec.mjs +++ b/test/integration/text_extractor_spec.mjs @@ -110,7 +110,7 @@ describe("PdfTextExtractor", () => { "Conference on Virtual Execution Environments, pages 83–93. ACM\nPress, 2007." ) ).toBeTrue(); - expect(text.length).toEqual(82804); + expect(text.length).toEqual(82801); expect(requestId).toEqual(2); }) ); diff --git a/test/integration/text_layer_spec.mjs b/test/integration/text_layer_spec.mjs index f551ed64f..933b77723 100644 --- a/test/integration/text_layer_spec.mjs +++ b/test/integration/text_layer_spec.mjs @@ -1626,21 +1626,30 @@ describe("Text layer", () => { const checkFonts = async debug => { await Promise.all( pages.map(async ([browserName, page]) => { - const { color, fontFamily } = await page.evaluate(() => { - const span = [ - ...document.querySelectorAll( - `.page[data-page-number = "1"] .textLayer span` - ), - ].find(({ textContent }) => textContent === "Andreas Gal"); - const style = getComputedStyle(span); - return { color: style.color, fontFamily: style.fontFamily }; - }); + const { color, fontFamily, newTextLayer } = await page.evaluate( + () => { + const span = [ + ...document.querySelectorAll( + `.page[data-page-number = "1"] .textLayer span` + ), + ].find(({ textContent }) => textContent === "Andreas Gal"); + const style = getComputedStyle(span); + return { + color: style.color, + fontFamily: style.fontFamily, + newTextLayer: span + .closest(".textLayer") + .classList.contains("newTextLayer"), + }; + } + ); expect(color) .withContext(browserName) .toEqual(debug ? "rgb(255, 0, 0)" : "rgba(0, 0, 0, 0)"); - expect(/^"?g_d\d+_tf\d+"?, /.test(fontFamily)) + expect(/^"?g_d\d+_tf\d+"?$/.test(fontFamily)) .withContext(`${browserName}: ${fontFamily}`) .toBeTrue(); + expect(newTextLayer).withContext(browserName).toBeTrue(); }) ); }; diff --git a/test/unit/api_spec.js b/test/unit/api_spec.js index 8276f4df6..1d8eb7ebb 100644 --- a/test/unit/api_spec.js +++ b/test/unit/api_spec.js @@ -35,6 +35,8 @@ import { import { assemblePdf, buildGetDocumentParams, + buildTextPdf, + buildVerticalTextPdf, CMAP_URL, DefaultBinaryDataFactory, DefaultFileReaderFactory, @@ -5202,7 +5204,7 @@ describe("api", function () { it("gets text content", async function () { const { items, styles, lang } = await page.getTextContent(); - expect(items.length).toEqual(15); + expect(items.length).toEqual(12); expect(Object.keys(styles).length).toEqual(5); expect(lang).toEqual("en"); @@ -5234,9 +5236,12 @@ page 1 / 3`); height: 18, str: "Issue 8276", transform: new Float32Array([18, 0, 0, 18, 441.81, 708.45]), - width: 77.49, + width: jasmine.any(Number), hasEOL: false, + textLayerAdvance: jasmine.any(Number), }); + expect(items[0].width).toBeCloseTo(77.49, 4); + expect(items[0].textLayerAdvance * 18).toBeCloseTo(77.49, 2); expect(styles[fontName]).toEqual({ fontFamily: "serif", ascent: 0.683, @@ -5309,7 +5314,6 @@ page 1 / 3`); expect(textLayerFont.ascent).toBeGreaterThan(0.5); expect(textLayerFont.ascent).toBeLessThan(0.95); - // The advances of the font are the ones of the PDF font. const font = new FontTestData(textLayerFont.data); let advance = 0; for (const char of item.str) { @@ -5321,62 +5325,135 @@ page 1 / 3`); await loadingTask.destroy(); }); - it("gets text content, with the gaps as spaces in the fonts of the text layer", async function () { - const content = - "BT /F1 20 Tf 10 150 Td [(A) -300 (B) -300 (A) -400 (B)] TJ ET"; - const loadingTask = getDocument({ - data: assemblePdf([ - "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", - "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n", - "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " + - "/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>\n" + - "endobj\n", - `4 0 obj\n<< /Length ${content.length} >>\nstream\n${content}\n` + - "endstream\nendobj\n", - "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica " + - "/Encoding /WinAnsiEncoding >>\nendobj\n", - ]), - }); + it("positions text after an overprinted accent in the text layer", async function () { + const loadingTask = getDocument(tracemonkeyGetDocumentParams); const pdfDoc = await loadingTask.promise; - const pdfPage = await pdfDoc.getPage(1); - const { items, styles } = await pdfPage.getTextContent(); + const pdfPage = await pdfDoc.getPage(2); + const { items } = await pdfPage.getTextContent({ + disableNormalization: true, + }); - expect(items.map(({ str }) => str)).toEqual(["A B A B"]); - // No space is drawn: the spaces get the median gap. - const font = new FontTestData( - styles[items[0].fontName].textLayerFont.data - ); - expect(font.getAdvance(0x20)).toBeCloseTo(300, 0); - expect(font.getAdvance(0x41)).toBeCloseTo(667, 0); + const index = items.findIndex(({ str }) => str === "a na\u00a8"); + const item = items[index + 1]; + expect(item.str).toMatch(/^\u0131ve implementation, inner loops/); + expect(item.transform[4]).toBeCloseTo(69.6272, 4); + expect(items[index].hasEOL).toBeFalse(); await loadingTask.destroy(); }); - it("gets text content, with the fonts of the text layer for a vertical text", async function () { - const loadingTask = getDocument( - buildGetDocumentParams("vertical.pdf", { - cMapUrl: CMAP_URL, - useWorkerFetch: false, - }) - ); - const pdfDoc = await loadingTask.promise; - const pdfPage = await pdfDoc.getPage(1); - const { items, styles } = await pdfPage.getTextContent({ - disableNormalization: true, + describe("text layer extraction", function () { + let loadingTask; + async function loadPage(params) { + loadingTask = getDocument(params); + return (await loadingTask.promise).getPage(1); + } + + afterEach(async function () { + await loadingTask?.destroy(); + loadingTask = null; }); - const item = items.find( - ({ str }) => str === "\u3042\u3044\u3046\u3048\u304a" - ); - const { vertical, textLayerFont } = styles[item.fontName]; - expect(vertical).toBeTrue(); - // Centered on the column, with the vertical advances. - expect(textLayerFont.ascent).toEqual(0.5); - expect( - new FontTestData(textLayerFont.data).getAdvance(0x3042) - ).toBeCloseTo(1000, 0); + function loadTextPage(content, fontEntries) { + return loadPage({ data: buildTextPdf(content, fontEntries) }); + } - await loadingTask.destroy(); + it("gets text content, with the gaps as spaces in the fonts of the text layer", async function () { + const content = + "BT /F1 20 Tf 10 150 Td [(A) -300 (B) -300 (A) -400 (B)] TJ ET"; + const pdfPage = await loadTextPage(content); + + const { items, styles } = await pdfPage.getTextContent(); + + expect(items.map(({ str }) => str).join("")).toEqual("A B A B"); + // No space is drawn: the spaces get the median gap. + const font = new FontTestData( + styles[items[0].fontName].textLayerFont.data + ); + expect(font.getAdvance(0x20)).toBeCloseTo(300, 0); + expect(font.getAdvance(0x41)).toBeCloseTo(667, 0); + }); + + it("gets text content, with the fonts of the text layer for a vertical text", async function () { + const pdfPage = await loadPage( + buildGetDocumentParams("vertical.pdf", { + cMapUrl: CMAP_URL, + useWorkerFetch: false, + }) + ); + + const { items, styles } = await pdfPage.getTextContent({ + disableNormalization: true, + }); + + const item = items.find( + ({ str }) => str === "\u3042\u3044\u3046\u3048\u304a" + ); + const { vertical, textLayerFont } = styles[item.fontName]; + expect(vertical).toBeTrue(); + // Centered on the column, with the vertical advances. + expect(textLayerFont.ascent).toEqual(0.5); + expect( + new FontTestData(textLayerFont.data).getAdvance(0x3042) + ).toBeCloseTo(1000, 0); + expect(item.dir).toBe("ttb"); + expect(item.height).toBeCloseTo( + 5 * Math.hypot(...item.transform.slice(2, 4)), + 1 + ); + }); + + it("fits vertical character spacing and TJ gaps along the column", async function () { + const content = + "BT /F1 20 Tf 50 Tz -2 Tc 90 180 Td " + + "[<30423044> 350 <3046>] TJ " + + "0 1 -1 0 20 80 Tm [100 <3048304a> 800 <3042>] TJ ET"; + const data = buildVerticalTextPdf(content); + const pdfPage = await loadPage({ + data, + cMapUrl: CMAP_URL, + useWorkerFetch: false, + }); + + const { items } = await pdfPage.getTextContent(); + expect(items.map(item => item.str).join("")).toEqual("あい うえお あ"); + const [first, rotated] = items; + expect(first.dir).toBe("ttb"); + expect(first.hasEOL).toBeTrue(); + expect(first.transform).toEqual( + new Float32Array([10, 0, 0, 20, 90, 180]) + ); + expect(first.width).toBe(10); + expect(first.height).toBeCloseTo(65, 6); + expect(rotated.transform).toEqual( + new Float32Array([0, 10, -20, 0, 22, 80]) + ); + // The large TJ gap splits the rotated column at x = 60. + expect(rotated.height).toBeCloseTo(38, 6); + const [, , space, last] = items; + expect(space.str).toBe(" "); + expect(space.dir).toBe("ttb"); + expect(space.transform).toEqual( + new Float32Array([0, 10, -20, 0, 60, 80]) + ); + expect(space.height).toBeCloseTo(18, 6); + expect(last.transform).toEqual( + new Float32Array([0, 10, -20, 0, 78, 80]) + ); + }); + + it("provides the generated font advance for mirrored text", async function () { + const pdfPage = await loadTextPage( + "BT /F1 20 Tf -1 0 0 1 150 150 Tm (ABC) Tj ET" + ); + + const { items } = await pdfPage.getTextContent(); + + expect(items.length).toBe(1); + const [item] = items; + expect(item.str).toBe("CBA"); + expect(item.textLayerAdvance * 20).toBeCloseTo(item.width, 1); + }); }); it("gets text content, with no extra spaces (issue 13226)", async function () { @@ -5391,6 +5468,10 @@ page 1 / 3`); expect(text).toEqual( "Mitarbeiterinnen und Mitarbeiter arbeiten in über 100 Ländern engagiert im Dienste" ); + const { items: textLayerItems } = await pdfPage.getTextContent({ + includeMarkedContent: true, + }); + expect(mergeText(textLayerItems)).toEqual(text); await loadingTask.destroy(); }); @@ -5456,9 +5537,9 @@ page 1 / 3`); expect(items).toEqual([ jasmine.objectContaining({ str: "सप्रणाम", - width: 109.12, }), ]); + expect(items[0]?.width).toBeCloseTo(109.12, 4); await loadingTask.destroy(); }); @@ -5625,9 +5706,9 @@ ABCD E`); styles[fitted[0].fontName].textLayerFont; // The rectangles extend from the baseline to the top of the font box. expect(ascent).toBe(1); - // The 80 em glyph is 0.8 of the 100 em high font box, the span's em. - expect(advanceScale).toEqual(1); - expect(new FontTestData(data).getAdvance(0x41)).toBeCloseTo(800, 0); + expect(new FontTestData(data).getAdvance(0x41) * advanceScale).toBe( + 80000 + ); await loadingTask.destroy(); }); @@ -5638,16 +5719,16 @@ ABCD E`); ); const pdfDoc = await loadingTask.promise; for (const [pageNumber, context, text, space] of [ - [1, "tall glyph bounding box", "A B", 240], - [2, "page scale canceled by the text matrix", "A B", 400], - [3, "scale change before the preceding glyph", "AB A", 480], + [1, "tall glyph bounding box", "A B", 300], + [2, "page scale canceled by the text matrix", "A B", 500], + [3, "scale change before the preceding glyph", "AB A", 600], [4, "scale change immediately before the gap", "A BA", 250], - [5, "scale change immediately after the gap", "A B\nA B", 240], - [6, "absolute positioning after a discarded move", "A B", 240], + [5, "scale change immediately after the gap", "A B\nA B", 300], + [6, "absolute positioning after a discarded move", "A B", 300], [7, "spacing moves at different scales", "A B\nA B", 250], - [8, "next line", "A B", 480], - [9, "next line and show text", "A B", 480], - [10, "set spacing, move to next line and show text", "A B", 480], + [8, "next line", "A B", 250], + [9, "next line and show text", "A B", 250], + [10, "set spacing, move to next line and show text", "A B", 250], ]) { const pdfPage = await pdfDoc.getPage(pageNumber); const { items, styles } = await pdfPage.getTextContent(); @@ -5655,8 +5736,7 @@ ABCD E`); styles[items[0].fontName].textLayerFont.data ); expect(mergeText(items)).withContext(context).toEqual(text); - // The 0.8 em wide glyphs in the 1.25 em high font box, the span's em. - expect(font.getAdvance(0x41)).withContext(context).toBeCloseTo(640, 0); + expect(font.getAdvance(0x41)).withContext(context).toBeCloseTo(800, 0); expect(font.getAdvance(0x20)) .withContext(context) .toBeCloseTo(space, 0); @@ -6045,7 +6125,7 @@ Caron Broadcasting, Inc., an Ohio corporation (“Lessee”).`) disableNormalization: true, }); - expect(items.map(i => i.str)).toEqual(["Hello ", "World"]); + expect(items.map(i => i.str)).toEqual(["Hello", " ", "World"]); await loadingTask.destroy(); }); @@ -6092,18 +6172,13 @@ Caron Broadcasting, Inc., an Ohio corporation (“Lessee”).`) const { items } = await pdfPage.getTextContent({ disableNormalization: true, }); - // The pdf has 3 different fonts but with the same underlying font data - // so we have finally one chunk. - expect(items).toEqual([ - jasmine.objectContaining({ - str: "ABCDEFGHI", - dir: "ltr", - height: 10, - transform: new Float32Array([10, 0, 0, 10, 100, 100]), - hasEOL: false, - }), + expect(items.map(({ str }) => str)).toEqual(["ABC", "DEF", "GHI"]); + expect(items.map(({ transform }) => transform[4])).toEqual([ + 100, 120, 140, ]); - expect(items[0]?.width).toBeCloseTo(57.78, 5); + expect(items.every(({ hasEOL }) => !hasEOL)).toBeTrue(); + expect(items[0].fontName).toBe(items[2].fontName); + expect(items[0].fontName).not.toBe(items[1].fontName); await loadingTask.destroy(); }); @@ -6193,20 +6268,18 @@ have written that much by now. So, here’s to squashing bugs.`); const pdfDoc = await loadingTask.promise; const pdfPage = await pdfDoc.getPage(1); const { items } = await pdfPage.getTextContent(); - const withFonts = await pdfPage.getTextContent(); - expect(withFonts.items).toEqual(items); // The same Hebrew character sequence uses normal and mirrored text - // matrices; the mirrored run ends with an LRM (U+200E). + // matrices. The trailing LRM (U+200E) is outside the visible run. expect(items.map(({ str, dir }) => ({ str, dir }))).toEqual([ { str: "רחאב", dir: "rtl" }, { str: "באחר", dir: "rtl" }, ]); const { transform, width } = items[1]; expect(transform).toBeInstanceOf(Float32Array); - [20, 0, 0, 20, 145.52, 100].forEach((value, i) => { + [20, 0, 0, 20, 156.64, 100].forEach((value, i) => { expect(transform[i]).toBeCloseTo(value, 2); }); - expect(width).toBeCloseTo(54.48, 2); + expect(width).toBeCloseTo(43.36, 2); await loadingTask.destroy(); }); @@ -6273,9 +6346,7 @@ have written that much by now. So, here’s to squashing bugs.`); ); try { const pdfPage = await (await loadingTask.promise).getPage(1); - const plainText = await pdfPage.getTextContent(); const { items, styles } = await pdfPage.getTextContent(); - expect(items).toEqual(plainText.items); expect(items.map(({ str, dir }) => ({ str, dir }))).toEqual([ { str: "[אב(", dir: "rtl" }, ]); diff --git a/test/unit/pdf_find_controller_spec.js b/test/unit/pdf_find_controller_spec.js index 47e69a503..80659d6ff 100644 --- a/test/unit/pdf_find_controller_spec.js +++ b/test/unit/pdf_find_controller_spec.js @@ -607,7 +607,7 @@ describe("pdf_find_controller", function () { pageIndex: 0, matchIndex: 0, }, - pageMatches: [[2734]], + pageMatches: [[2731]], pageMatchesLength: [[14]], }); @@ -870,7 +870,7 @@ describe("pdf_find_controller", function () { pageIndex: 0, matchIndex: 0, }, - pageMatches: [[139]], + pageMatches: [[138]], pageMatchesLength: [[8]], }); @@ -1098,7 +1098,7 @@ describe("pdf_find_controller", function () { pageIndex: 0, matchIndex: 0, }, - pageMatches: [[6, 25, 44, 63]], + pageMatches: [[18, 37, 56, 75]], pageMatchesLength: [[1, 1, 1, 1]], }); @@ -1113,7 +1113,7 @@ describe("pdf_find_controller", function () { pageIndex: 0, matchIndex: 0, }, - pageMatches: [[6, 25, 44, 63]], + pageMatches: [[18, 37, 56, 75]], pageMatchesLength: [[1, 1, 1, 1]], }); diff --git a/test/unit/test_utils.js b/test/unit/test_utils.js index dd43a541e..95e4939e1 100644 --- a/test/unit/test_utils.js +++ b/test/unit/test_utils.js @@ -98,6 +98,37 @@ function assemblePdf(objects, trailerEntries = "") { return stringToBytes(pdf); } +function buildPdfWithFont(content, fontObjects) { + return assemblePdf([ + "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", + "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n", + "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] " + + "/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>\nendobj\n", + `4 0 obj\n<< /Length ${content.length} >>\nstream\n${content}\nendstream\nendobj\n`, + ...fontObjects, + ]); +} + +function buildTextPdf(content, fontEntries = "/Encoding /WinAnsiEncoding") { + return buildPdfWithFont(content, [ + "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica " + + `${fontEntries} >>\nendobj\n`, + ]); +} + +function buildVerticalTextPdf(content) { + return buildPdfWithFont(content, [ + "5 0 obj\n<< /Type /Font /Subtype /Type0 /BaseFont /VerticalTest " + + "/Encoding /UniJIS-UTF16-V /DescendantFonts [6 0 R] >>\nendobj\n", + "6 0 obj\n<< /Type /Font /Subtype /CIDFontType0 /BaseFont /VerticalTest " + + "/CIDSystemInfo << /Registry (Adobe) /Ordering (Japan1) /Supplement 6 >> " + + "/FontDescriptor 7 0 R /DW2 [880 -900] >>\nendobj\n", + "7 0 obj\n<< /Type /FontDescriptor /FontName /VerticalTest /Flags 4 " + + "/FontBBox [0 -120 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -120 " + + "/CapHeight 700 /StemV 80 >>\nendobj\n", + ]); +} + // Builds a PDF sound object's stream dictionary (ISO 32000-1, 12.5.6.16). Pass // a key as `null` to omit it (to exercise defaults/missing entries); pass // `type: true` to add the optional `/Type /Sound` entry. @@ -341,6 +372,8 @@ export { assemblePdf, BoundedXRefMock, buildGetDocumentParams, + buildTextPdf, + buildVerticalTextPdf, CMAP_URL, createIdFactory, createSoundDict, diff --git a/test/unit/text_layer_font_spec.js b/test/unit/text_layer_font_spec.js index 0283ed266..e4691be83 100644 --- a/test/unit/text_layer_font_spec.js +++ b/test/unit/text_layer_font_spec.js @@ -19,6 +19,7 @@ import { TextLayerFonts, } from "../../src/core/text_layer_font.js"; import { FontTestData } from "./font_test_utils.js"; +import { TextExtraction } from "../../src/core/text_extraction.js"; const idFactory = { getDocId: () => "g_d0", @@ -39,18 +40,17 @@ function getTextLayerFont( spaceGaps = [], } = {} ) { - const sink = createSink(); - const textLayerFonts = new TextLayerFonts(sink, idFactory, drawBoxes); - textLayerFonts.addFont("f1", font, heightScaled); + const textLayerFonts = new TextLayerFonts(idFactory, drawBoxes); + if (heightScaled) { + textLayerFonts.addHeightScaledFont(font); + } for (const [unicode, advance] of glyphs) { textLayerFonts.addGlyph(font, unicode, advance); } for (const gap of spaceGaps) { - textLayerFonts.addSpaceGap("f1", gap); + textLayerFonts.addSpaceGap(font, gap); } - textLayerFonts.enqueue({ items: [], styles: { f1: {} } }); - textLayerFonts.send(); - return sink.chunks[0].styles.f1.textLayerFont; + return textLayerFonts.build(font); } function expectAdvances(font, advances) { @@ -173,7 +173,7 @@ describe("text layer font", function () { ["B", 1000], ["C", 40000000], ]; - expect(getTextLayerFont(glyphs, { spaceGaps: [300] })).toBeUndefined(); + expect(getTextLayerFont(glyphs, { spaceGaps: [300] })).toBeNull(); }); it("doesn't build a font with advances which don't fit", function () { @@ -185,7 +185,7 @@ describe("text layer font", function () { ["A", 1], ["B", 200000], ]) - ).toBeUndefined(); + ).toBeNull(); }); it("encodes wide advances with the smallest scale which fits them", function () { @@ -259,6 +259,22 @@ describe("text layer font", function () { ]); }); + it("includes the Thai and Lao SARA AM shaping components", function () { + const { data } = getTextLayerFont([ + ["\u0e33", 500], + ["\u0eb3", 450], + ["\u0eb2", 400], + ]); + expectAdvances(new FontTestData(data), [ + [0x0e33, 500], + [0x0e4d, 0], + [0x0e32, 500], + [0x0eb3, 450], + [0x0ecd, 0], + [0x0eb2, 400], + ]); + }); + it("gets the ascent from the font, else from its bounding box", function () { const getAscent = (font, heightScaled = false) => getTextLayerFont([["a", 500]], { font, heightScaled }).ascent; @@ -312,18 +328,18 @@ describe("text layer font", function () { it("only builds the fonts of the styles", function () { const sink = createSink(); let id = 0; - const textLayerFonts = new TextLayerFonts(sink, { + const extraction = new TextExtraction(sink, { getDocId: () => "g_d0", createFontId: () => `f${++id}`, }); const font1 = { ascent: 0.8, descent: -0.2 }; const font2 = { ascent: 0.8, descent: -0.2 }; - textLayerFonts.addFont("f1", font1); - textLayerFonts.addGlyph(font1, "a", 500); + extraction.addFont("f1", font1); + extraction.fonts.addGlyph(font1, "a", 500); // E.g. a font with the same name as the one of the current item. - textLayerFonts.addGlyph(font2, "b", 500); - textLayerFonts.enqueue({ items: [], styles: { f1: {} } }); - textLayerFonts.send(); + extraction.fonts.addGlyph(font2, "b", 500); + extraction.enqueue({ items: [], styles: { f1: {} } }); + extraction.send(); expect(sink.chunks[0].styles.f1.textLayerFont.name).toEqual("g_d0_tf1"); expect(id).toEqual(1); @@ -331,15 +347,15 @@ describe("text layer font", function () { it("stops the text content extraction when its stream is cancelled", async function () { const sink = createSink(); - const textLayerFonts = new TextLayerFonts(sink, idFactory); - await expectAsync(textLayerFonts.ready).toBeResolved(); - textLayerFonts.enqueue({ items: [], styles: {} }); + const extraction = new TextExtraction(sink, idFactory); + await expectAsync(extraction.ready).toBeResolved(); + extraction.enqueue({ items: [], styles: {} }); sink.isCancelled = true; - await expectAsync(textLayerFonts.ready).toBeRejectedWith( + await expectAsync(extraction.ready).toBeRejectedWith( jasmine.any(AbortException) ); - textLayerFonts.send(); + extraction.send(); expect(sink.chunks).toEqual([]); }); }); diff --git a/test/unit/text_layer_spec.js b/test/unit/text_layer_spec.js index 7d1f21de8..bc2945798 100644 --- a/test/unit/text_layer_spec.js +++ b/test/unit/text_layer_spec.js @@ -39,19 +39,16 @@ describe("textLayer", function () { expect(textLayer.textContentItemsStr).toEqual([ "Table Of Content", - "", "Chapter 1", " ", "..........................................................", " ", "2", - "", "Paragraph 1.1", " ", "......................................................", " ", "3", - "", "page 1 / 3", ]); @@ -75,19 +72,16 @@ describe("textLayer", function () { expect(textLayer.textContentItemsStr).toEqual([ "Table Of Content", - "", "Chapter 1", " ", "..........................................................", " ", "2", - "", "Paragraph 1.1", " ", "......................................................", " ", "3", - "", "page 1 / 3", ]); @@ -318,10 +312,10 @@ describe("textLayer", function () { ({ family }) => family.replaceAll('"', "") === name ); - function createTextLayer(ownerDocument = document) { + function createTextLayer(container = document.createElement("div")) { const textLayer = new TextLayer({ textContentSource: textContent, - container: ownerDocument.createElement("div"), + container, viewport, }); textLayers.push(textLayer); @@ -349,6 +343,30 @@ describe("textLayer", function () { await loadingTask?.destroy(); }); + it("fits isolated glyphs with the same text and different PDF widths", async function () { + const item = textContent.items.find(({ str }) => /^[A-Z]/i.test(str)); + const widths = [3, 12]; + textContent.items = widths.map(width => ({ + ...item, + str: item.str[0], + width, + textLayerAdvance: undefined, + })); + const container = document.createElement("div"); + container.className = "textLayer"; + container.style.setProperty("--total-scale-factor", "1"); + document.body.append(container); + try { + const layer = createTextLayer(container); + await layer.render(); + for (const [i, span] of layer.textDivs.entries()) { + expect(span.getBoundingClientRect().width).toBeCloseTo(widths[i], 1); + } + } finally { + container.remove(); + } + }); + it("lays out the text and shares the fonts until the last cancellation", async function () { const first = createTextLayer(); const second = createTextLayer(); @@ -361,7 +379,7 @@ describe("textLayer", function () { for (const [i, { style }] of first.textDivs.entries()) { const { name, ascent } = styles[items[i].fontName].textLayerFont; names.add(name); - expect(style.fontFamily).toMatch(new RegExp(`^"?${name}"?, `)); + expect(style.fontFamily.replaceAll('"', "")).toBe(name); // The span is moved up by the ascent of the font. const [, , , d, , f] = items[i].transform; expect(parseFloat(style.top)).toBeCloseTo( @@ -370,6 +388,13 @@ describe("textLayer", function () { ); } expect([...names].every(name => hasFont(name))).toBeTrue(); + const spaces = first.textDivs.filter( + ({ textContent: str }) => str === " " + ); + expect(spaces.length).toBeGreaterThan(0); + expect( + spaces.every(({ style }) => !style.getPropertyValue("--scale-x")) + ).toBeTrue(); first.cancel(); expect([...names].every(name => hasFont(name))).toBeTrue(); @@ -381,7 +406,7 @@ describe("textLayer", function () { const iframe = document.createElement("iframe"); document.body.append(iframe); const { contentDocument } = iframe; - const inner = createTextLayer(contentDocument); + const inner = createTextLayer(contentDocument.createElement("div")); const outer = createTextLayer(); const { name } = textContent.styles[textContent.items[0].fontName].textLayerFont; @@ -444,15 +469,15 @@ describe("textLayer", function () { }); it("removes a failed font and renders with the fallback font", async function () { - const { textLayerFont } = + const { fontFamily, textLayerFont } = textContent.styles[textContent.items[0].fontName]; textLayerFont.data = new Uint8Array(1); const textLayer = createTextLayer(); await textLayer.render(); expect(hasFont(textLayerFont.name)).toBeFalse(); - expect(textLayer.textDivs[0].style.fontFamily).not.toContain( - textLayerFont.name + expect(textLayer.textDivs[0].style.fontFamily).toBe( + TextLayer.fontFamilyMap.get(fontFamily) || fontFamily ); }); }); diff --git a/web/pdf_find_controller.js b/web/pdf_find_controller.js index d01cade39..13b914fb3 100644 --- a/web/pdf_find_controller.js +++ b/web/pdf_find_controller.js @@ -884,7 +884,10 @@ class PDFFindController { } let deferred = Promise.resolve(); - const textOptions = { disableNormalization: true }; + const textOptions = { + disableNormalization: true, + includeMarkedContent: true, + }; const pdfDoc = this._pdfDocument; for (let i = 0, ii = this._linkService.pagesCount; i < ii; i++) { const { promise, resolve } = createPromiseCapability(); diff --git a/web/text_layer_builder.css b/web/text_layer_builder.css index 0b36b85e5..a55fe8955 100644 --- a/web/text_layer_builder.css +++ b/web/text_layer_builder.css @@ -56,6 +56,10 @@ --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); + &.newTextLayer { + font-variant-ligatures: none; + } + > :not(.markedContent), .markedContent span:not(.markedContent) { z-index: 1;