Add an test to check that the text layer font passes OTS

This commit is contained in:
Calixte Denizet
2026-11-29 15:16:35 +01:00
parent 2477bb1aed
commit b4390e4220
11 changed files with 207 additions and 94 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
# The requirements below can be regenerated with the following one-liner:
# `python3 -m venv venv; source venv/bin/activate; pip install -q fonttools; pip freeze; deactivate; rm -rf venv`
# `python3 -m venv venv; source venv/bin/activate; pip install -q fonttools pyots; pip freeze; deactivate; rm -rf venv`
fonttools==4.68.0
pyots==9.3.0
+2 -2
View File
@@ -65,10 +65,10 @@ jobs:
- name: Install dependencies
run: npm ci
- name: Use Python 3.15
- name: Use Python 3.14
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.15'
python-version: '3.14'
cache: 'pip'
cache-dependency-path: '.github/font_tests_requirements.txt'
+7 -3
View File
@@ -99,12 +99,16 @@ function hasSameAxes(left, right) {
);
}
function hasReflectedBaseline({ transform: [a, b, c, d], vertical }) {
return !vertical && d > 0 && a * d - b * c < 0;
function hasReflectedBaseline({ transform, vertical }) {
const d = transform[3];
return (
!vertical && d > 0 && transform[0] * d - transform[1] * transform[2] < 0
);
}
function unmirrorTransform(transform, width) {
const [a, b] = transform;
const a = transform[0];
const b = transform[1];
// Move the origin along the baseline, then reverse the baseline direction.
const scale = width / Math.hypot(a, b);
transform[0] = -a;
+1 -1
View File
@@ -207,7 +207,7 @@ function selectKerningPairs(samples, ligaturePairs) {
(count >= 2 ||
(value < 0 && value >= -MAX_SINGLE_KERNING) ||
ligaturePairs?.has(key)) &&
count >= MIN_KERNING_SHARE * counts.values().reduce((a, b) => a + b, 0)
count >= MIN_KERNING_SHARE * Math.sumPrecise(counts.values())
) {
candidates.push({ key, value, count });
}
+8 -10
View File
@@ -9,6 +9,9 @@ if PDF.js can successfully read the font data and `ttx` can successfully read
the PDF.js-interpreted font data back, proving that PDF.js does not apply any
transformations that break the font data.
The suite also uses `pyots` to check that OpenType Sanitizer accepts the fonts
generated for the text layer without reporting any diagnostics.
## Running the font tests
The font tests are run on GitHub Actions using the workflow defined in
@@ -16,21 +19,16 @@ The font tests are run on GitHub Actions using the workflow defined in
tests locally. The current stable versions of the following dependencies are
required to be installed on the system:
- Python 3
- Python 3.10–3.14 (versions with `pyots` wheels)
- `fonttools` (see https://pypi.org/project/fonttools and https://github.com/fonttools/fonttools)
- `pyots` (see https://pypi.org/project/pyots/)
The recommended way of installing `fonttools` is using `pip` in a virtual
environment because it avoids having to do a system-wide installation and
therefore improves isolation, but any other way of installing `fonttools`
that makes `ttx` available in the `PATH` environment variable also works.
Install both packages in a virtual environment so that `python` and `ttx` on
`PATH` come from the same environment:
Using the virtual environment approach the font tests can be run locally by
creating and sourcing a virtual environment with `fonttools` installed in
it before running the font tests:
```
python3 -m venv venv
source venv/bin/activate
pip install fonttools
pip install -r .github/font_tests_requirements.txt
npx gulp fonttest
```
+70
View File
@@ -0,0 +1,70 @@
/* Copyright 2014 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 { execFile } from "child_process";
import fs from "fs/promises";
import os from "os";
import path from "path";
import { promisify } from "util";
const run = promisify(execFile);
async function withFontFile(content, callback) {
const directory = await fs.mkdtemp(
path.join(os.tmpdir(), "pdfjs-font-test-")
);
try {
const fontPath = path.join(directory, "font.otf");
await fs.writeFile(fontPath, Buffer.from(content, "base64"));
return await callback(fontPath);
} finally {
await fs.rm(directory, { recursive: true, force: true });
}
}
function translateFont(content) {
return withFontFile(content, async fontPath => {
const resultPath = path.join(path.dirname(fontPath), "font.ttx");
try {
await run("ttx", ["-q", "-o", resultPath, fontPath]);
} catch (error) {
if (error.code === "ENOENT") {
throw new Error(
"Unable to execute `ttx`; make sure the `fonttools` dependency is installed"
);
}
throw error;
}
return fs.readFile(resultPath);
});
}
const sanitize = String.raw`
import sys
import pyots
result = pyots.sanitize(sys.argv[1])
messages = "\n".join(result.messages).strip()
if messages or not result.sanitized:
sys.exit(messages or "OTS rejected the font")
`;
function sanitizeFont(content) {
return withFontFile(content, fontPath =>
run("python3", ["-c", sanitize, fontPath])
);
}
export { sanitizeFont, translateFont };
+13 -6
View File
@@ -13,16 +13,23 @@
* limitations under the License.
*/
async function ttx(data) {
const response = await fetch("/ttx", {
async function postFont(path, data) {
const response = await fetch(path, {
method: "POST",
body: data.toBase64(),
});
if (!response.ok) {
throw new Error(response.statusText);
throw new Error((await response.text()) || response.statusText);
}
return response.text();
return response;
}
async function checkSanitization(data) {
await postFont("/ots", data);
}
async function ttx(data) {
return (await postFont("/ttx", data)).text();
}
function verifyTtxOutput(output) {
@@ -32,4 +39,4 @@ function verifyTtxOutput(output) {
}
}
export { ttx, verifyTtxOutput };
export { checkSanitization, ttx, verifyTtxOutput };
+1
View File
@@ -49,6 +49,7 @@ async function initializePDFJS(callback) {
"pdfjs-test/font/font_os2_spec.js",
"pdfjs-test/font/font_post_spec.js",
"pdfjs-test/font/font_fpgm_spec.js",
"pdfjs-test/font/text_layer_font_spec.js",
].map(moduleName => import(moduleName)) // eslint-disable-line no-unsanitized/method
);
+90
View File
@@ -0,0 +1,90 @@
/* 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 { checkSanitization } from "./fontutils.js";
import { FontTestData } from "../unit/font_test_utils.js";
import { TextLayerFonts } from "../../src/core/text_layer_font.js";
describe("generated text layer fonts", function () {
const idFactory = {
getDocId: () => "g_d0",
createFontId: () => "f1",
};
const ltrGlyphs = [
["A", 667],
["V", 667],
["\u0301", 0],
["\u{1f600}", 1000],
["\u0e33", 500],
["\u0eb3", 450],
];
const rtlGlyphs = [
["\u05d0", 500],
["\u05d1", 500],
];
const ltrPairs = [
["A", "V", -150],
["V", "A", -100],
];
async function getKerningTables(glyphs, pairs = [], drawBoxes = false) {
const font = { ascent: 0.8, descent: -0.2 };
const fonts = new TextLayerFonts(idFactory, drawBoxes);
for (const [unicode, advance] of glyphs) {
fonts.addGlyph(font, unicode, advance);
}
for (const [left, right, advance] of pairs) {
fonts.addKerning(font, left, right, advance);
}
const { data } = fonts.build(font);
await expectAsync(checkSanitization(data)).toBeResolved();
const { tables } = new FontTestData(data);
return ["GPOS", "kern"].filter(tag => tables.has(tag));
}
it("passes OTS without kerning", async function () {
expect(await getKerningTables(ltrGlyphs)).toEqual([]);
});
it("passes OTS with GPOS kerning and debug glyph boxes", async function () {
expect(await getKerningTables(ltrGlyphs, ltrPairs, true)).toEqual(["GPOS"]);
});
it("passes OTS with GPOS kerning in a font with RTL glyphs", async function () {
expect(
await getKerningTables([...ltrGlyphs, ...rtlGlyphs], ltrPairs)
).toEqual(["GPOS"]);
});
it("passes OTS with a kern table for a neutral pair in a font with RTL glyphs", async function () {
expect(
await getKerningTables(
[...ltrGlyphs, ...rtlGlyphs, [".", 250], ['"', 400]],
[['"', ".", -100]]
)
).toEqual(["kern"]);
});
it("passes OTS with a kern table for mixed LTR and RTL pairs", async function () {
expect(
await getKerningTables(
[...ltrGlyphs, ...rtlGlyphs],
[...ltrPairs, ["\u05d0", "\u05d1", -100]]
)
).toEqual(["kern"]);
});
});
-70
View File
@@ -1,70 +0,0 @@
/* Copyright 2014 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 fs from "fs";
import os from "os";
import path from "path";
import { spawn } from "child_process";
let ttxTaskId = Date.now();
function runTtx(fontPath) {
return new Promise((resolve, reject) => {
const ttx = spawn("ttx", [fontPath], { stdio: "ignore" });
ttx.on("error", () => {
reject(
new Error(
"Unable to execute `ttx`; make sure the `fonttools` dependency is installed"
)
);
});
ttx.on("close", () => {
resolve();
});
});
}
async function translateFont(content) {
const buffer = Buffer.from(content, "base64");
const taskId = (ttxTaskId++).toString();
const fontPath = path.join(os.tmpdir(), `pdfjs-font-test-${taskId}.otf`);
const resultPath = path.join(os.tmpdir(), `pdfjs-font-test-${taskId}.ttx`);
// Write the font data to a temporary file on disk (because TTX only accepts
// files as input).
fs.writeFileSync(fontPath, buffer);
// Run TTX on the temporary font file.
let ttxError;
try {
await runTtx(fontPath);
} catch (error) {
ttxError = error;
}
// Remove the temporary font/result files and report on the outcome.
fs.unlinkSync(fontPath);
if (ttxError) {
throw ttxError;
}
if (!fs.existsSync(resultPath)) {
throw new Error("TTX did not generate output");
}
const xml = fs.readFileSync(resultPath);
fs.unlinkSync(resultPath);
return xml;
}
export { translateFont };
+13 -1
View File
@@ -28,6 +28,7 @@ import {
downloadManifestFiles,
verifyManifestFiles,
} from "./downloadutils.mjs";
import { sanitizeFont, translateFont } from "./font/fontdriver.mjs";
import { execSync } from "child_process";
import fs from "fs";
import istanbulCoverage from "istanbul-lib-coverage";
@@ -38,7 +39,6 @@ import { parseArgs } from "node:util";
import path from "path";
import puppeteer from "puppeteer";
import readline from "readline";
import { translateFont } from "./font/ttxdriver.mjs";
import { WebServer } from "./webserver.mjs";
const __dirname = import.meta.dirname;
@@ -1017,6 +1017,7 @@ function unitTestPostHandler(parsedUrl, req, res) {
pathname !== "/tellMeToQuit" &&
pathname !== "/info" &&
pathname !== "/ttx" &&
!(options.fontTest && pathname === "/ots") &&
pathname !== "/submit_task_results"
) {
return false;
@@ -1027,6 +1028,17 @@ function unitTestPostHandler(parsedUrl, req, res) {
body += data;
});
req.on("end", async function () {
if (pathname === "/ots") {
try {
await sanitizeFont(body);
res.writeHead(204);
res.end();
} catch (error) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end(error.stderr?.trim() || error.message);
}
return;
}
if (pathname === "/ttx") {
res.writeHead(200, { "Content-Type": "text/xml" });
try {