Merge pull request #22622 from calixteman/text_layer_zoom

Zoom the text layer with CSS and only set a transform on the spans which need one
This commit is contained in:
calixteman
2026-11-30 14:54:29 +01:00
committed by GitHub
15 changed files with 400 additions and 353 deletions
+7 -2
View File
@@ -315,6 +315,8 @@ function getColorValues(colors) {
}
/**
* Set layer dimensions using CSS scale variables. Set `--layer-zoom` to `1`
* for unzoomed layers.
* @param {HTMLDivElement} div
* @param {PageViewport} viewport
* @param {boolean} mustFlip
@@ -330,8 +332,11 @@ function setLayerDimensions(
const { pageWidth, pageHeight } = viewport.rawDims;
const { style } = div;
const widthStr = `round(down, var(--total-scale-factor) * ${pageWidth}px, var(--scale-round-x))`,
heightStr = `round(down, var(--total-scale-factor) * ${pageHeight}px, var(--scale-round-y))`;
// Round before dividing by the layer zoom to match the displayed canvas.
const dimension = (size, axis) =>
`calc(round(down, var(--total-scale-factor) * ${size}px, var(--scale-round-${axis})) / var(--layer-zoom))`;
const widthStr = dimension(pageWidth, "x");
const heightStr = dimension(pageHeight, "y");
if (!mustFlip || viewport.rotation % 180 === 0) {
style.width = widthStr;
+10 -1
View File
@@ -921,6 +921,15 @@ class DrawingEditor extends AnnotationEditor {
return target;
}
/**
* @param {AnnotationEditorLayer} _parent
* @param {HTMLElement} target
* @returns {DOMRect} Drawing bounds in viewport coordinates.
*/
static _getDrawingBox(_parent, target) {
return target.getBoundingClientRect();
}
/**
* @param {PointerEvent} event
* @param {PointerEvent} [referenceEvent]
@@ -984,7 +993,7 @@ class DrawingEditor extends AnnotationEditor {
y: boxY,
width: parentWidth,
height: parentHeight,
} = target.getBoundingClientRect();
} = this._getDrawingBox(parent, target);
const ac = (DrawingEditor.#currentDrawingAC = new AbortController());
const signal = parent.combinedSignal(ac);
+10
View File
@@ -420,6 +420,16 @@ class HighlightEditor extends DrawingEditor {
return target.closest(".textLayer");
}
/** @inheritdoc */
static _getDrawingBox(parent) {
// Safari before 26.4 and Chrome before 128 can omit CSS zoom from
// getBoundingClientRect. Use the annotation editor layer's client rect
// instead of the zoomed text layer's rect.
// https://bugs.webkit.org/show_bug.cgi?id=300474
// https://crbug.com/967097
return parent.div.getBoundingClientRect();
}
/** @inheritdoc */
static _getPointerCoords({ x, y }) {
// Child-relative offsets don't match the text layer's client box.
+106 -134
View File
@@ -62,6 +62,8 @@ class TextLayer {
#container = null;
#ctx = null;
#disableProcessItems = false;
#fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
@@ -72,8 +74,6 @@ class TextLayer {
#lang = null;
#layoutTextParams = null;
#hasTextLayerFonts = false;
#ownerDocument;
@@ -137,13 +137,8 @@ class TextLayer {
this.#imagesHandler = images;
this.#scale = viewport.scale * this.#pixelRatio;
this.#scale = viewport.scale * viewport.userUnit;
this.#rotation = viewport.rotation;
this.#layoutTextParams = {
div: null,
properties: null,
ctx: null,
};
const { pageWidth, pageHeight, pageX, pageY } = viewport.rawDims;
this.#transform = new Float32Array([
1,
@@ -157,7 +152,6 @@ class TextLayer {
this.#pageHeight = pageHeight;
TextLayer.#ensureMinFontSizeComputed();
container.style.setProperty("--min-font-size", TextLayer.#minFontSize);
setLayerDimensions(container, viewport);
@@ -165,7 +159,7 @@ class TextLayer {
this.#capability.promise
.finally(() => {
TextLayer.#pendingTextLayers.delete(this);
this.#layoutTextParams = null;
this.#ctx = null;
this.#styleCache = null;
})
.catch(noopFn);
@@ -259,17 +253,14 @@ class TextLayer {
* @returns {undefined}
*/
update({ viewport }) {
const scale = viewport.scale * OutputScale.pixelRatio;
const rotation = viewport.rotation;
if (rotation !== this.#rotation) {
this.#rotation = rotation;
setLayerDimensions(this.#rootContainer, { rotation });
}
if (scale !== this.#scale) {
this.#scale = scale;
this.#pixelRatio = OutputScale.pixelRatio;
}
this.#scale = viewport.scale * viewport.userUnit;
this.#pixelRatio = OutputScale.pixelRatio;
}
/**
@@ -354,11 +345,6 @@ class TextLayer {
if (this.#disableProcessItems) {
return;
}
this.#layoutTextParams.ctx ??= TextLayer.#getCtx(
this.#ownerDocument,
this.#lang
);
const textDivs = this.#textDivs,
textContentItemsStr = this.#textContentItemsStr;
@@ -398,30 +384,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);
Util.transform(this.#transform, geom.transform, TX);
let angle = Math.atan2(TX[1], TX[0]);
const style = this.#styleCache[geom.fontName];
if (style.vertical) {
angle += Math.PI / 2;
}
const { textLayerFont } = style;
const { str, fontName } = geom;
const style = this.#styleCache[fontName];
const { textLayerFont, vertical } = style;
let fontFamily,
ascent,
fontAdvance = 0,
advanceScale = 1;
const hasTextLayerFont =
textLayerFont &&
@@ -430,8 +401,7 @@ class TextLayer {
fontFamily = textLayerFont.name;
ascent = textLayerFont.ascent;
advanceScale = textLayerFont.advanceScale;
textDivProperties.fontAdvance =
(geom.textLayerAdvance ?? 0) / advanceScale;
fontAdvance = (geom.textLayerAdvance ?? 0) / advanceScale;
} else {
fontFamily =
(this.#fontInspectorEnabled && style.fontSubstitution) ||
@@ -439,124 +409,121 @@ class TextLayer {
// Workaround for bug 1922063.
fontFamily = TextLayer.fontFamilyMap.get(fontFamily) || fontFamily;
}
Util.transform(this.#transform, geom.transform, TX);
const baselineLength = Math.hypot(TX[0], TX[1]);
const fontHeight = Math.hypot(TX[2], TX[3]);
const fontAscent =
fontHeight *
(ascent ??
TextLayer.#getAscent(fontFamily, style, this.#layoutTextParams.ctx));
let left, top;
if (angle === 0) {
left = TX[4];
top = TX[5] - fontAscent;
} else {
left = TX[4] + fontAscent * Math.sin(angle);
top = TX[5] - fontAscent * Math.cos(angle);
const baselineX = baselineLength ? TX[0] / baselineLength : 1;
const baselineY = baselineLength ? TX[1] / baselineLength : 0;
const a = vertical ? -baselineY : baselineX;
const b = vertical ? baselineX : baselineY;
// Negating the second axis of TX gives a non-mirrored CSS basis only
// when TX has a negative determinant.
const isMirrored = TX[0] * TX[3] >= TX[1] * TX[2];
let c = -b,
d = a;
if (!vertical && !isMirrored) {
c = -TX[2] / fontHeight;
d = -TX[3] / fontHeight;
}
const fontAscent =
fontHeight *
(ascent ?? TextLayer.#getAscent(fontFamily, style, this.#getCtx()));
const left = TX[4] - fontAscent * c;
const top = TX[5] - fontAscent * d;
const divStyle = textDiv.style;
// Setting the style properties individually, rather than all at once,
// should be OK since the `textDiv` isn't appended to the document yet.
// Percentages align span origins with the rounded canvas box.
divStyle.left = `${((100 * left) / this.#pageWidth).toFixed(3)}%`;
divStyle.top = `${((100 * top) / this.#pageHeight).toFixed(3)}%`;
// The text is laid out with the rounded value, hence keep it around in
// order to measure the text with the very same size, see `#layout`.
const roundedFontHeight = Math.round(fontHeight * 100) / 100;
divStyle.setProperty("--font-height", `${roundedFontHeight}px`);
const fontSize = Math.round(fontHeight * 100) / 100;
// Increase the CSS font size to compensate for the browser minimum and
// undo the multiplier in the span transform.
const fontSizeScale = TextLayer.#minFontSize;
divStyle.fontSize = `${fontSize * fontSizeScale}px`;
divStyle.fontFamily = fontFamily;
textDivProperties.fontSize = roundedFontHeight;
// Keeps screen readers from pausing on every new text span.
textDiv.setAttribute("role", "presentation");
textDiv.textContent = geom.str;
textDiv.textContent = str;
// geom.dir may be 'ttb' for vertical texts.
textDiv.dir = geom.dir;
// `fontName` is only used by the FontInspector, and we only use `dataset`
// here to make the font name available in the debugger.
if (this.#fontInspectorEnabled) {
textDiv.dataset.fontName =
style.fontSubstitutionLoadedName || geom.fontName;
textDiv.dataset.fontName = style.fontSubstitutionLoadedName || fontName;
}
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 && !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),
absScaleY = Math.abs(scaleY);
shouldScaleText =
Math.max(absScaleX, absScaleY) > 1.5 * Math.min(absScaleX, absScaleY);
}
if (shouldScaleText) {
textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width;
if (!textDivProperties.canvasWidth && textDivProperties.fontAdvance > 0) {
textDivProperties.scaleX = 0;
if (str) {
// Different PDF glyphs can map to one character in the generated font
// and share a single advance.
// Also fit single non-space glyphs when horizontal and vertical scaling
// differ significantly, to improve highlighting (see issue11713.pdf).
const shouldFitWidth =
str.length > 1 ||
(str === " "
? hasTextLayerFont && advanceScale !== 1
: hasTextLayerFont ||
Math.max(baselineLength, fontHeight) >
1.5 * Math.min(baselineLength, fontHeight));
const scaleX = shouldFitWidth
? this.#getWidthScale(
str,
fontFamily,
fontSize,
vertical ? geom.height : geom.width,
fontAdvance
)
: 1;
if (
a !== 1 ||
b !== 0 ||
c !== 0 ||
d !== 1 ||
scaleX !== 1 ||
fontSizeScale !== 1
) {
const sx = scaleX / fontSizeScale;
divStyle.transform = `matrix(${a * sx},${b * sx},${c / fontSizeScale},${d / fontSizeScale},0,0)`;
}
}
// Finally, layout and append the text to the DOM.
this.#layoutTextParams.div = textDiv;
this.#layoutTextParams.properties = textDivProperties;
this.#layout(this.#layoutTextParams);
if (textDivProperties.hasText) {
this.#container.append(textDiv);
}
if (textDivProperties.hasEOL) {
if (geom.hasEOL) {
const br = this.#ownerDocument.createElement("br");
br.setAttribute("role", "presentation");
this.#container.append(br);
}
}
#layout(params) {
const { div, properties, ctx } = params;
const { style } = div;
const { canvasWidth, fontSize, fontAdvance } = properties;
let { scaleX } = properties;
#getWidthScale(text, fontFamily, fontSize, targetWidth, fontAdvance) {
if (targetWidth === 0) {
return fontAdvance > 0 ? 0 : 1;
}
if (fontSize === 0) {
return 1;
}
if (canvasWidth !== 0 && fontSize !== 0 && properties.hasText) {
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;
// Match the layer's kerning setting on the shared measurement canvas.
const kerning = this.#hasTextLayerFonts ? "normal" : "auto";
if (ctx.fontKerning !== kerning) {
ctx.fontKerning = kerning;
}
TextLayer.#ensureCtxFont(ctx, measuredSize, style.fontFamily);
width =
(ctx.measureText(div.textContent).width * fontSize) / measuredSize;
let width = fontAdvance * fontSize;
if (!width) {
// Firefox quantizes canvas font sizes in CSS pixels.
const measuredSize =
TextLayer.#quantizeFontSize(fontSize * this.#scale) * this.#pixelRatio;
const ctx = this.#getCtx();
// Text layers sharing this canvas can use different kerning modes.
const kerning = this.#hasTextLayerFonts ? "normal" : "auto";
if (ctx.fontKerning !== kerning) {
ctx.fontKerning = kerning;
}
TextLayer.#ensureCtxFont(ctx, measuredSize, fontFamily);
width = (ctx.measureText(text).width * fontSize) / measuredSize;
}
if (width > 0) {
scaleX = canvasWidth / width;
}
}
if (scaleX !== 1) {
style.setProperty("--scale-x", scaleX);
}
if (properties.angle !== 0) {
style.setProperty("--rotate", `${properties.angle}deg`);
}
// The endpoint tolerance is an absolute distance in page units.
return width > 0 && Math.abs(targetWidth - width) > 0.01
? targetWidth / width
: 1;
}
/**
@@ -575,12 +542,17 @@ class TextLayer {
this.#canvasContexts.clear();
}
static #getCtx(ownerDocument, lang = null) {
const contexts = this.#canvasContexts.getOrInsertComputed(
#getCtx() {
if (this.#ctx) {
return this.#ctx;
}
const ownerDocument = this.#ownerDocument;
const lang = this.#lang || "";
const contexts = TextLayer.#canvasContexts.getOrInsertComputed(
ownerDocument,
makeMap
);
let ctx = contexts.get((lang ||= ""));
let ctx = contexts.get(lang);
if (!ctx) {
// We don't use an OffscreenCanvas here because we use serif/sans serif
// fonts with it and they depends on the locale.
@@ -606,13 +578,13 @@ class TextLayer {
// Also, initialize state for the `#ensureCtxFont` method.
// Resizing the canvas resets ctx.font but leaves this cache stale.
this.#canvasCtxFonts.set(ctx, {
TextLayer.#canvasCtxFonts.set(ctx, {
size: 0,
family: "",
ascents: new Map(),
});
}
return ctx;
return (this.#ctx = ctx);
}
// Match Firefox's 7-bit `QuantizeFontSize` implementation:
+1
View File
@@ -250,6 +250,7 @@ class Rasterize {
return [
":root {",
" --scale-round-x: 1px; --scale-round-y: 1px;",
" --layer-zoom: 1;",
` --scale-factor: ${scale};`,
` --user-unit: ${userUnit};`,
` --total-scale-factor: ${scale * userUnit};`,
+30 -5
View File
@@ -245,7 +245,7 @@ describe("accessibility", () => {
let pages;
beforeEach(async () => {
pages = await loadAndWait("bug1708040.pdf", ".structTree");
pages = await loadAndWait("bug1708040.pdf", ".structTree", 150);
});
afterEach(async () => {
@@ -268,14 +268,39 @@ describe("accessibility", () => {
expect(spanId).withContext(`In ${browserName}`).not.toBeNull();
const ariaLabel = await page.evaluate(id => {
const img = document.querySelector(`#${id} > span[role="img"]`);
return img.getAttribute("aria-label");
}, spanId);
const { ariaLabel, bounds } = await page.$eval(
`#${spanId} > span[role="img"]`,
img => {
const rect = img.getBoundingClientRect();
const { canvas, viewport } =
window.PDFViewerApplication.pdfViewer.getPageView(0);
const { left, top, width, height } =
canvas.getBoundingClientRect();
// The displayed canvas dimensions are rounded.
const toPdfPoint = (x, y) =>
viewport.convertToPdfPoint(
((x - left) * viewport.width) / width,
((y - top) * viewport.height) / height
);
return {
ariaLabel: img.getAttribute("aria-label"),
bounds: [
...toPdfPoint(rect.left, rect.bottom),
...toPdfPoint(rect.right, rect.top),
],
};
}
);
expect(ariaLabel)
.withContext(`In ${browserName}`)
.toEqual("A logo of a fox and a globe");
const bbox = [72, 287.782, 456, 695.032];
for (const [i, edge] of bounds.entries()) {
expect(edge)
.withContext(`In ${browserName}`)
.toBeCloseTo(bbox[i], 1);
}
})
);
});
+21 -5
View File
@@ -1445,7 +1445,7 @@ describe("Highlight Editor", () => {
pages = await loadAndWait(
"tracemonkey.pdf",
".annotationEditorLayer",
null,
60,
null,
{ locale: "ar" }
);
@@ -1468,13 +1468,29 @@ describe("Highlight Editor", () => {
delay: 100,
});
const toolbarRect = await getRect(page, ".textLayer .editToolbar");
const toolbar = await page.waitForSelector(
".textLayer .editToolbar",
{ visible: true }
);
const {
left,
height: actualHeight,
offsetHeight,
} = await toolbar.evaluate(el => {
const rect = el.getBoundingClientRect();
return {
left: rect.left,
height: rect.height,
offsetHeight: el.offsetHeight,
};
});
expect(actualHeight)
.withContext(`Toolbar height in ${browserName}`)
.toBeCloseTo(offsetHeight, 0);
// In RTL, the left edge of the toolbar is aligned on the left edge
// of the selection (bug 2060032).
expect(toolbarRect.x)
.withContext(`In ${browserName}`)
.toBeCloseTo(x, 0);
expect(left).withContext(`In ${browserName}`).toBeCloseTo(x, 0);
})
);
});
+1 -1
View File
@@ -26,7 +26,7 @@
position: absolute;
white-space: pre;
transform-origin: 0% 0%;
border: solid 1px rgb(255 0 0 / 0.5);
border: solid var(--text-layer-screen-px, 1px) rgb(255 0 0 / 0.5);
background-color: rgb(255 255 32 / 0.1);
box-sizing: border-box;
}
+147 -146
View File
@@ -21,11 +21,59 @@ import { getDocument } from "../../src/display/api.js";
import { OutputScale } from "../../src/display/output_scale.js";
import { PageViewport } from "../../src/display/page_viewport.js";
function getTextLayout({ textDivs }) {
return textDivs.map(({ style: { fontSize, transform } }) => ({
fontSize,
transform,
}));
}
function getTextMatrix({ style }) {
return new DOMMatrix(style.transform || undefined);
}
function createViewport({ scale = 1, userUnit = 1 } = {}) {
return new PageViewport({
viewBox: [0, 0, 800, 800],
userUnit,
scale,
rotation: 0,
});
}
function createSyntheticTextLayer(
items,
{
viewport = createViewport(),
container = document.createElement("div"),
style,
} = {}
) {
return new TextLayer({
textContentSource: {
items: items.map(item => ({
str: "A",
dir: "ltr",
hasEOL: false,
fontName: "f1",
...item,
})),
styles: { f1: { fontFamily: "sans-serif", vertical: false, ...style } },
lang: "en",
},
container,
viewport,
});
}
describe("textLayer", function () {
it("creates textLayer from ReadableStream", async function () {
beforeEach(function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
});
it("creates textLayer from ReadableStream", async function () {
const loadingTask = getDocument(buildGetDocumentParams("basicapi.pdf"));
const pdfDocument = await loadingTask.promise;
const page = await pdfDocument.getPage(1);
@@ -56,9 +104,6 @@ describe("textLayer", function () {
});
it("creates textLayer from TextContent", async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
const loadingTask = getDocument(buildGetDocumentParams("basicapi.pdf"));
const pdfDocument = await loadingTask.promise;
const page = await pdfDocument.getPage(1);
@@ -89,25 +134,9 @@ describe("textLayer", function () {
});
it("creates textLayers in parallel, from ReadableStream", async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
if (typeof ReadableStream.from !== "function") {
pending("ReadableStream.from is not supported.");
}
const getTransform = container => {
const transform = [];
for (const { style } of container.childNodes) {
transform.push({
fontHeight: style.getPropertyValue("--font-height"),
scaleX: style.getPropertyValue("--scale-x"),
rotate: style.getPropertyValue("--rotate"),
});
}
return transform;
};
const loadingTask = getDocument(buildGetDocumentParams("basicapi.pdf"));
const pdfDocument = await loadingTask.promise;
const [page1, page2] = await Promise.all([
@@ -191,11 +220,11 @@ describe("textLayer", function () {
});
await serialTextLayer2.render();
const serialTransform1 = getTransform(serialContainer1),
serialTransform2 = getTransform(serialContainer2);
const serialLayout1 = getTextLayout(serialTextLayer1),
serialLayout2 = getTextLayout(serialTextLayer2);
expect(serialTransform1.length).toEqual(2);
expect(serialTransform2.length).toEqual(2);
expect(serialLayout1.length).toEqual(2);
expect(serialLayout2.length).toEqual(2);
// Reset any global textLayer-state before rendering in parallel.
TextLayer.cleanup();
@@ -240,58 +269,32 @@ describe("textLayer", function () {
expect(textLayer2.textContentItemsStr).toEqual(["Chapter B", "page 2"]);
// Ensure that the transforms are identical when parsing in series/parallel.
const transform1 = getTransform(container1),
transform2 = getTransform(container2);
expect(transform1).toEqual(serialTransform1);
expect(transform2).toEqual(serialTransform2);
expect(getTextLayout(textLayer1)).toEqual(serialLayout1);
expect(getTextLayout(textLayer2)).toEqual(serialLayout2);
await loadingTask.destroy();
});
it("fits a single glyph of a font with scaled advances", async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
const container = document.createElement("div");
container.className = "textLayer";
container.style.setProperty("--total-scale-factor", "1");
document.body.append(container);
// The 80 em advance of A is encoded with a scale in the font.
const textLayer = new TextLayer({
textContentSource: {
items: [
{
str: "A",
dir: "ltr",
width: 40,
height: 0.5,
transform: [0.5, 0, 0, 0.5, 50, 700],
fontName: "f1",
hasEOL: false,
},
],
styles: {
f1: {
fontFamily: "sans-serif",
vertical: false,
textLayerFont: {
name: "scaled_advances",
data: buildTextLayerFont(new Map([[0x41, 80000]]), 1, false, 4),
ascent: 1,
advanceScale: 4,
},
const textLayer = createSyntheticTextLayer(
[{ width: 40, height: 0.5, transform: [0.5, 0, 0, 0.5, 50, 700] }],
{
container,
style: {
textLayerFont: {
name: "scaled_advances",
data: buildTextLayerFont(new Map([[0x41, 80000]]), 1, false, 4),
ascent: 1,
advanceScale: 4,
},
},
},
container,
viewport: new PageViewport({
viewBox: [0, 0, 800, 800],
userUnit: 1,
scale: 1,
rotation: 0,
}),
});
}
);
try {
await textLayer.render();
expect(textLayer.textDivs[0].getBoundingClientRect().width).toBeCloseTo(
@@ -323,9 +326,6 @@ describe("textLayer", function () {
}
beforeEach(async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
textLayers = [];
loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf"));
const pdfDocument = await loadingTask.promise;
@@ -343,6 +343,29 @@ describe("textLayer", function () {
await loadingTask?.destroy();
});
it("only scales width-fitted spans when the endpoint moves appreciably", async function () {
const item = textContent.items.find(({ str }) => str);
const { advanceScale } = textContent.styles[item.fontName].textLayerFont;
const fontSize = 20;
const scale = 1.00005;
// The same relative error moves the endpoint farther in a longer span.
textContent.items = [1, 100].map(count => {
const advance = count * 0.5;
return {
...item,
str: "A".repeat(count),
transform: [fontSize, 0, 0, fontSize, 10, 100],
width: advance * fontSize * scale,
textLayerAdvance: advance * advanceScale,
};
});
const layer = createTextLayer();
await layer.render();
const [short, long] = layer.textDivs;
expect(short.style.transform).toBe("");
expect(getTextMatrix(long).a).toBeCloseTo(scale, 6);
});
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];
@@ -392,9 +415,7 @@ describe("textLayer", function () {
({ textContent: str }) => str === " "
);
expect(spaces.length).toBeGreaterThan(0);
expect(
spaces.every(({ style }) => !style.getPropertyValue("--scale-x"))
).toBeTrue();
expect(spaces.every(({ style }) => style.transform === "")).toBeTrue();
first.cancel();
expect([...names].every(name => hasFont(name))).toBeTrue();
@@ -418,9 +439,7 @@ describe("textLayer", function () {
await outer.render();
expect(hasFont(name)).toBeTrue();
const getScales = ({ textDivs }) =>
textDivs.map(({ style }) => style.getPropertyValue("--scale-x"));
expect(getScales(inner)).toEqual(getScales(outer));
expect(getTextLayout(inner)).toEqual(getTextLayout(outer));
inner.cancel();
expect(hasFont(name, contentDocument)).toBeFalse();
@@ -483,101 +502,83 @@ describe("textLayer", function () {
});
it("measures the text with the correct font after computing the ascent", async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
const loadingTask = getDocument(buildGetDocumentParams("basicapi.pdf"));
const pdfDocument = await loadingTask.promise;
const page = await pdfDocument.getPage(1);
// Proportional widths should produce the same horizontal scale.
const items = [10, 11].map(fontSize => ({
str: "Hello World",
dir: "ltr",
width: 5 * fontSize,
height: fontSize,
transform: [fontSize, 0, 0, fontSize, 50, 700],
fontName: "g_d0_f1",
hasEOL: false,
}));
const styles = {
g_d0_f1: {
ascent: 0.75,
descent: -0.25,
fontFamily: "sans-serif",
vertical: false,
},
};
const scale = 1.5;
const userUnit = 2;
const pageScale = scale * userUnit;
const measuredSizes = [DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE + 3];
const items = measuredSizes.map(size => {
const fontSize = size / pageScale;
return {
str: "Hello World",
width: 5 * fontSize,
height: fontSize,
transform: [fontSize, 0, 0, fontSize, 50, 700],
};
});
// Force the ascent to be computed for this font.
TextLayer.cleanup();
// Use DPR 1 to avoid rounding the first measurement away from 30px.
// Use DPR 1 so the first run and the ascent use the same canvas font.
spyOnProperty(OutputScale, "pixelRatio", "get").and.returnValue(1);
// Ensure that 30px is still the font size used to compute the ascent.
expect(DEFAULT_FONT_SIZE).toEqual(30);
const textLayer = new TextLayer({
textContentSource: { items, styles, lang: "en" },
container: document.createElement("div"),
// Measure the first run at the 30px size used to compute the ascent.
viewport: page.getViewport({ scale: 3 }),
const setFont = spyOnProperty(
CanvasRenderingContext2D.prototype,
"font",
"set"
).and.callThrough();
const textLayer = createSyntheticTextLayer(items, {
viewport: createViewport({ scale, userUnit }),
});
await textLayer.render();
const [scaleX1, scaleX2] = textLayer.textDivs.map(({ style }) =>
parseFloat(style.getPropertyValue("--scale-x"))
const [first, second] = textLayer.textDivs.map(getTextMatrix);
expect(first.a / second.a).toBeCloseTo(1, 1);
// The family can be mapped (e.g. Calibri on Windows), see fontFamilyMap.
expect(setFont).toHaveBeenCalledWith(
jasmine.stringMatching(new RegExp(`^${measuredSizes[1]}px `))
);
expect(scaleX1 / scaleX2).toBeCloseTo(1, 1);
await loadingTask.destroy();
});
it("positions the text precisely", async function () {
if (isNodeJS) {
pending("document.createElement is not supported in Node.js.");
}
const loadingTask = getDocument(buildGetDocumentParams("basicapi.pdf"));
const pdfDocument = await loadingTask.promise;
const page = await pdfDocument.getPage(1);
const viewport = page.getViewport({ scale: 1 });
const viewport = createViewport();
const { pageWidth, pageX } = viewport.rawDims;
// Badly rounded with two decimals: 10.00% instead of 10.0045%.
const left = (pageWidth * 10.0045) / 100;
const textLayer = new TextLayer({
textContentSource: {
items: [
{
str: "Hello",
dir: "ltr",
width: 30,
height: 10,
transform: [10, 0, 0, 10, pageX + left, 100],
fontName: "f1",
hasEOL: false,
},
],
styles: {
f1: {
fontFamily: "sans-serif",
ascent: 0.8,
descent: -0.2,
vertical: false,
},
},
lang: "en",
},
container: document.createElement("div"),
viewport,
});
const textLayer = createSyntheticTextLayer(
[{ width: 10, height: 10, transform: [10, 0, 0, 10, pageX + left, 100] }],
{ viewport }
);
await textLayer.render();
const { style } = textLayer.textDivs[0];
expect(
Math.abs((parseFloat(style.left) * pageWidth) / 100 - left)
).toBeLessThan(5e-3);
});
await loadingTask.destroy();
it("preserves the orientation of rotated and skewed text", async function () {
const textLayer = createSyntheticTextLayer([
{ transform: [6, 8, -8, 6, 50, 100], width: 10, height: 10 },
{ transform: [10, 0, 2, 10, 50, 100], width: 10, height: 10 },
]);
await textLayer.render();
const [rotated, skewed] = textLayer.textDivs.map(getTextMatrix);
expect(rotated.b / rotated.a).toBeCloseTo(-4 / 3, 6);
expect(rotated.c / rotated.d).toBeCloseTo(4 / 3, 6);
expect(skewed.b).toBe(0);
expect(skewed.c / skewed.d).toBeCloseTo(-0.2, 6);
});
it("fits isolated stretched glyphs regardless of baseline orientation", async function () {
const textLayer = createSyntheticTextLayer([
{ transform: [50, 0, 0, 30, 50, 100], width: 50, height: 30 },
{ transform: [30, 40, 0, 30, 50, 100], width: 50, height: 30 },
]);
await textLayer.render();
const [horizontal, angled] = textLayer.textDivs.map(getTextMatrix);
expect(Math.hypot(angled.a, angled.b) / horizontal.a).toBeCloseTo(1, 5);
});
});
+30 -12
View File
@@ -36,29 +36,47 @@
--resizer-border-radius: 2px;
--editorFreeText-editing-cursor: text;
--editorInk-editing-cursor: url(images/cursor-editorInk.svg) 0 16, pointer;
--editorHighlight-editing-cursor:
url(images/cursor-editorTextHighlight.svg) 24 24, text;
--editorFreeHighlight-editing-cursor:
url(images/cursor-editorFreeHighlight.svg) 1 18, pointer;
--new-alt-text-warning-image: url(images/altText_warning.svg);
}
.textLayer {
/* Keep the floating toolbar size independent of PDF zoom. */
> .editToolbar {
zoom: calc(1 / var(--layer-zoom));
}
&.highlighting {
cursor: var(--editorFreeHighlight-editing-cursor);
--highlight-cursor-resolution: 1dppx;
&:not(.free) span {
cursor: var(--editorHighlight-editing-cursor);
&[role="img"] {
cursor: var(--editorFreeHighlight-editing-cursor);
}
/* Cancel Firefox's CSS zoom adjustment to the cursor image resolution.
https://searchfox.org/firefox-main/rev/f6fd4acd62d41edb115e8ba4c55660d241a67d5d/layout/style/nsStyleStruct.cpp#1778-1780 */
@supports (-moz-appearance: none) {
--highlight-cursor-resolution: calc(var(--layer-zoom) * 1dppx);
}
&.free span {
--editorFreeHighlight-editing-cursor:
image-set(
url(images/cursor-editorFreeHighlight.svg)
var(--highlight-cursor-resolution)
)
1 18,
pointer;
&,
& span {
cursor: var(--editorFreeHighlight-editing-cursor);
}
&:not(.free) span:not([role="img"]) {
cursor:
image-set(
url(images/cursor-editorTextHighlight.svg)
var(--highlight-cursor-resolution)
)
24 24,
text;
}
}
}
+4 -1
View File
@@ -179,6 +179,9 @@
gap: 12px;
}
#canvas-wrapper {
--scale-round-x: 1px;
--scale-round-y: 1px;
position: relative;
display: inline-block;
line-height: 0;
@@ -201,7 +204,7 @@
}
&.show-span-borders .textLayer :is(span, br) {
outline: 1px solid
outline: var(--text-layer-screen-px, 1px) solid
color-mix(in srgb, var(--text-layer-color, #c03030) 60%, black);
}
}
+10 -17
View File
@@ -644,19 +644,12 @@ class PageView {
this.#textLayerEl = null;
}
async #buildTextLayer(scale) {
async #buildTextLayer(viewport) {
const container = document.createElement("div");
container.className = "textLayer";
// --total-scale-factor is required by text_layer_builder.css to compute
// font sizes. setLayerDimensions (called inside TextLayer) consumes it but
// never sets it, so we must provide it here.
container.style.setProperty("--total-scale-factor", scale);
container.style.setProperty("--scale-round-x", "1px");
container.style.setProperty("--scale-round-y", "1px");
document.getElementById("canvas-wrapper").append(container);
this.#textLayerEl = container;
const viewport = this.#renderedPage.getViewport({ scale });
const textLayer = new TextLayer({
textContentSource: this.#renderedPage.streamTextContent(),
container,
@@ -766,19 +759,19 @@ class PageView {
oldCanvas.replaceWith(newCanvas);
}
// In text-only mode, overlay the text layer on the finished canvas.
// If a layer already exists (e.g. after a zoom/resize), rescale it in place
// by updating the CSS variable and calling update() — no rebuild needed.
// If the filter is now off, discard any existing layer.
if (this.#textFilter) {
const textViewport = viewport.clone({ scale });
document
.getElementById("canvas-wrapper")
.style.setProperty(
"--total-scale-factor",
scale * textViewport.userUnit
);
if (this.#textLayerInstance) {
this.#textLayerEl.style.setProperty("--total-scale-factor", scale);
this.#textLayerInstance.update({
viewport: this.#renderedPage.getViewport({ scale }),
});
this.#textLayerInstance.update({ viewport: textViewport });
this.#textLayerEl.style.visibility = "";
} else {
await this.#buildTextLayer(scale);
await this.#buildTextLayer(textViewport);
}
} else {
this.#cancelTextLayer();
+1
View File
@@ -182,6 +182,7 @@
.pdfViewer .page {
--user-unit: 1;
--layer-zoom: 1;
--total-scale-factor: calc(var(--scale-factor) * var(--user-unit));
--scale-round-x: 1px;
--scale-round-y: 1px;
+8 -6
View File
@@ -491,13 +491,15 @@ class StructTreeLayerBuilder {
img.setAttribute("role", "img");
img.setAttribute("aria-label", removeNullCharacters(alt));
const { pageHeight, pageX, pageY } = this.#rawDims;
const calc = "calc(var(--total-scale-factor) *";
const { pageWidth, pageHeight, pageX, pageY } = this.#rawDims;
const [left, bottom, right, top] = bbox;
const xPercent = 100 / pageWidth,
yPercent = 100 / pageHeight;
const { style } = img;
style.width = `${calc}${bbox[2] - bbox[0]}px)`;
style.height = `${calc}${bbox[3] - bbox[1]}px)`;
style.left = `${calc}${bbox[0] - pageX}px)`;
style.top = `${calc}${pageHeight - bbox[3] + pageY}px)`;
style.width = `${(right - left) * xPercent}%`;
style.height = `${(top - bottom) * yPercent}%`;
style.left = `${(left - pageX) * xPercent}%`;
style.top = `${(pageY + pageHeight - top) * yPercent}%`;
return true;
}
+14 -23
View File
@@ -14,7 +14,12 @@
*/
.textLayer {
--layer-zoom: var(--total-scale-factor, 1);
/* Keep highlight decorations and debug borders independent of PDF zoom. */
--text-layer-screen-px: calc(1px / var(--layer-zoom));
color-scheme: only light;
zoom: var(--layer-zoom);
position: absolute;
text-align: initial;
@@ -48,14 +53,6 @@
color: red;
}
/* We multiply the font size by --min-font-size, and then scale the text
* elements by 1/--min-font-size. This allows us to effectively ignore the
* minimum font size enforced by the browser, so that the text layer <span>s
* can always match the size of the text in the canvas. */
--min-font-size: 1;
--text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
--min-font-size-inv: calc(1 / var(--min-font-size));
&.textLayerFonts {
font-kerning: normal;
font-variant-ligatures: none;
@@ -64,14 +61,6 @@
> :not(.markedContent),
.markedContent span:not(.markedContent) {
z-index: 1;
--font-height: 0; /* set by text_layer.js */
font-size: calc(var(--text-scale-factor) * var(--font-height));
--scale-x: 1;
--rotate: 0deg;
transform: rotate(var(--rotate)) scaleX(var(--scale-x))
scale(var(--min-font-size-inv));
}
.markedContent {
@@ -99,22 +88,24 @@
);
}
margin: -1px;
padding: 1px;
--highlight-radius: calc(4 * var(--text-layer-screen-px));
margin: calc(-1 * var(--text-layer-screen-px));
padding: var(--text-layer-screen-px);
background-color: var(--highlight-color);
backdrop-filter: var(--highlight-backdrop-filter);
border-radius: 4px;
border-radius: var(--highlight-radius);
&.appended {
position: initial;
}
&.begin {
border-radius: 4px 0 0 4px;
border-radius: var(--highlight-radius) 0 0 var(--highlight-radius);
}
&.end {
border-radius: 0 4px 4px 0;
border-radius: 0 var(--highlight-radius) var(--highlight-radius) 0;
}
&.middle {
@@ -125,7 +116,7 @@
--highlight-color: var(--highlight-selected-bg-color);
backdrop-filter: var(--highlight-selected-backdrop-filter);
scroll-margin-top: 50px;
scroll-margin-top: calc(50 * var(--text-layer-screen-px));
}
}
@@ -133,7 +124,7 @@
&.textLayerFonts .highlight {
margin: 0;
padding: 0;
box-shadow: 0 0 0 1px var(--highlight-color);
box-shadow: 0 0 0 var(--text-layer-screen-px) var(--highlight-color);
}
::selection {