Update Prettier to version 2.0

Please note that these changes were done automatically, using `gulp lint --fix`.

Given that the major version number was increased, there's a fair number of (primarily whitespace) changes; please see https://prettier.io/blog/2020/03/21/2.0.0.html
In order to reduce the size of these changes somewhat, this patch maintains the old "arrowParens" style for now (once mozilla-central updates Prettier we can simply choose the same formatting, assuming it will differ here).
This commit is contained in:
Jonas Jenwald 2020-04-14 12:28:14 +02:00
parent a4dd081d7b
commit 426945b480
145 changed files with 2005 additions and 2009 deletions

View File

@ -1,4 +1,5 @@
{
"arrowParens": "avoid",
"endOfLine": "lf",
"printWidth": 80,
"semi": true,

View File

@ -27,14 +27,14 @@ var eventBus = new pdfjsViewer.EventBus();
// Fetch the PDF document from the URL using promises.
var loadingTask = pdfjsLib.getDocument(DEFAULT_URL);
loadingTask.promise.then(function(doc) {
loadingTask.promise.then(function (doc) {
// Use a promise to fetch and render the next page.
var promise = Promise.resolve();
for (var i = 1; i <= doc.numPages; i++) {
promise = promise.then(
function(pageNum) {
return doc.getPage(pageNum).then(function(pdfPage) {
function (pageNum) {
return doc.getPage(pageNum).then(function (pdfPage) {
// Create the page view.
var pdfPageView = new pdfjsViewer.PDFPageView({
container: container,

View File

@ -8,7 +8,7 @@ var source = require("vinyl-source-stream");
var OUTPUT_PATH = "../../build/browserify";
var TMP_FILE_PREFIX = "../../build/browserify_";
gulp.task("build-bundle", function() {
gulp.task("build-bundle", function () {
return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" })
.ignore(require.resolve("pdfjs-dist/build/pdf.worker")) // Reducing size
.bundle()
@ -18,7 +18,7 @@ gulp.task("build-bundle", function() {
.pipe(gulp.dest(OUTPUT_PATH));
});
gulp.task("build-worker", function() {
gulp.task("build-worker", function () {
// We can create our own viewer (see worker.js) or use already defined one.
var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry");
return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" })

View File

@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise
.then(function(pdfDocument) {
.then(function (pdfDocument) {
// Request a first page
return pdfDocument.getPage(1).then(function(pdfPage) {
return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas");
@ -30,6 +30,6 @@ loadingTask.promise
return renderTask.promise;
});
})
.catch(function(reason) {
.catch(function (reason) {
console.error("Error: " + reason);
});

View File

@ -43,9 +43,9 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED,
});
loadingTask.promise.then(function(pdfDocument) {
loadingTask.promise.then(function (pdfDocument) {
// Document loaded, retrieving the page.
return pdfDocument.getPage(PAGE_TO_VIEW).then(function(pdfPage) {
return pdfDocument.getPage(PAGE_TO_VIEW).then(function (pdfPage) {
// Creating the page view with default parameters.
var pdfPageView = new pdfjsViewer.PDFPageView({
container: container,

View File

@ -55,7 +55,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({
});
pdfLinkService.setViewer(pdfViewer);
eventBus.on("pagesinit", function() {
eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = "page-width";
@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED,
});
loadingTask.promise.then(function(pdfDocument) {
loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and
// the (optional) linkService.
pdfViewer.setDocument(pdfDocument);

View File

@ -55,7 +55,7 @@ var pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({
});
pdfLinkService.setViewer(pdfSinglePageViewer);
eventBus.on("pagesinit", function() {
eventBus.on("pagesinit", function () {
// We can use pdfSinglePageViewer now, e.g. let's change default scale.
pdfSinglePageViewer.currentScaleValue = "page-width";
@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED,
});
loadingTask.promise.then(function(pdfDocument) {
loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and
// the (optional) linkService.
pdfSinglePageViewer.setDocument(pdfDocument);

View File

@ -47,11 +47,11 @@ var PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when document
* is opened.
*/
open: function(params) {
open: function (params) {
if (this.pdfLoadingTask) {
// We need to destroy already opened document
return this.close().then(
function() {
function () {
// ... and repeat the open() call.
return this.open(params);
}.bind(this)
@ -71,12 +71,12 @@ var PDFViewerApplication = {
});
this.pdfLoadingTask = loadingTask;
loadingTask.onProgress = function(progressData) {
loadingTask.onProgress = function (progressData) {
self.progress(progressData.loaded / progressData.total);
};
return loadingTask.promise.then(
function(pdfDocument) {
function (pdfDocument) {
// Document loaded, specifying document for the viewer.
self.pdfDocument = pdfDocument;
self.pdfViewer.setDocument(pdfDocument);
@ -86,7 +86,7 @@ var PDFViewerApplication = {
self.loadingBar.hide();
self.setTitleUsingMetadata(pdfDocument);
},
function(exception) {
function (exception) {
var message = exception && exception.message;
var l10n = self.l10n;
var loadingErrorMessage;
@ -119,7 +119,7 @@ var PDFViewerApplication = {
);
}
loadingErrorMessage.then(function(msg) {
loadingErrorMessage.then(function (msg) {
self.error(msg, { message: message });
});
self.loadingBar.hide();
@ -132,7 +132,7 @@ var PDFViewerApplication = {
* @returns {Promise} - Returns the promise, which is resolved when all
* destruction is completed.
*/
close: function() {
close: function () {
var errorWrapper = document.getElementById("errorWrapper");
errorWrapper.setAttribute("hidden", "true");
@ -175,9 +175,9 @@ var PDFViewerApplication = {
this.setTitle(title);
},
setTitleUsingMetadata: function(pdfDocument) {
setTitleUsingMetadata: function (pdfDocument) {
var self = this;
pdfDocument.getMetadata().then(function(data) {
pdfDocument.getMetadata().then(function (data) {
var info = data.info,
metadata = data.metadata;
self.documentInfo = info;
@ -275,27 +275,27 @@ var PDFViewerApplication = {
errorMessage.textContent = message;
var closeButton = document.getElementById("errorClose");
closeButton.onclick = function() {
closeButton.onclick = function () {
errorWrapper.setAttribute("hidden", "true");
};
var errorMoreInfo = document.getElementById("errorMoreInfo");
var moreInfoButton = document.getElementById("errorShowMore");
var lessInfoButton = document.getElementById("errorShowLess");
moreInfoButton.onclick = function() {
moreInfoButton.onclick = function () {
errorMoreInfo.removeAttribute("hidden");
moreInfoButton.setAttribute("hidden", "true");
lessInfoButton.removeAttribute("hidden");
errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px";
};
lessInfoButton.onclick = function() {
lessInfoButton.onclick = function () {
errorMoreInfo.setAttribute("hidden", "true");
moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true");
};
moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true");
Promise.all(moreInfoText).then(function(parts) {
Promise.all(moreInfoText).then(function (parts) {
errorMoreInfo.value = parts.join("\n");
});
},
@ -369,29 +369,31 @@ var PDFViewerApplication = {
});
linkService.setHistory(this.pdfHistory);
document.getElementById("previous").addEventListener("click", function() {
document.getElementById("previous").addEventListener("click", function () {
PDFViewerApplication.page--;
});
document.getElementById("next").addEventListener("click", function() {
document.getElementById("next").addEventListener("click", function () {
PDFViewerApplication.page++;
});
document.getElementById("zoomIn").addEventListener("click", function() {
document.getElementById("zoomIn").addEventListener("click", function () {
PDFViewerApplication.zoomIn();
});
document.getElementById("zoomOut").addEventListener("click", function() {
document.getElementById("zoomOut").addEventListener("click", function () {
PDFViewerApplication.zoomOut();
});
document.getElementById("pageNumber").addEventListener("click", function() {
this.select();
});
document
.getElementById("pageNumber")
.addEventListener("change", function() {
.addEventListener("click", function () {
this.select();
});
document
.getElementById("pageNumber")
.addEventListener("change", function () {
PDFViewerApplication.page = this.value | 0;
// Ensure that the page number input displays the correct value,
@ -402,14 +404,14 @@ var PDFViewerApplication = {
}
});
eventBus.on("pagesinit", function() {
eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
});
eventBus.on(
"pagechanging",
function(evt) {
function (evt) {
var page = evt.pageNumber;
var numPages = PDFViewerApplication.pagesCount;
@ -424,7 +426,7 @@ var PDFViewerApplication = {
document.addEventListener(
"DOMContentLoaded",
function() {
function () {
PDFViewerApplication.initUI();
},
true
@ -433,13 +435,15 @@ document.addEventListener(
(function animationStartedClosure() {
// The offsetParent is not set until the PDF.js iframe or object is visible.
// Waiting for first animation.
PDFViewerApplication.animationStartedPromise = new Promise(function(resolve) {
PDFViewerApplication.animationStartedPromise = new Promise(function (
resolve
) {
window.requestAnimationFrame(resolve);
});
})();
// We need to delay opening until all HTML is loaded.
PDFViewerApplication.animationStartedPromise.then(function() {
PDFViewerApplication.animationStartedPromise.then(function () {
PDFViewerApplication.open({
url: DEFAULT_URL,
});

View File

@ -58,7 +58,7 @@ function DOMElement(name) {
if (name === "style") {
this.sheet = {
cssRules: [],
insertRule: function(rule) {
insertRule: function (rule) {
this.cssRules.push(rule);
},
};
@ -226,16 +226,16 @@ const document = {
return this;
},
createElementNS: function(NS, element) {
createElementNS: function (NS, element) {
var elObject = new DOMElement(element);
return elObject;
},
createElement: function(element) {
createElement: function (element) {
return this.createElementNS("", element);
},
getElementsByTagName: function(element) {
getElementsByTagName: function (element) {
if (element === "head") {
return [this.head || (this.head = new DOMElement("head"))];
}
@ -264,14 +264,14 @@ exports.Image = Image;
var exported_symbols = Object.keys(exports);
exports.setStubs = function(namespace) {
exported_symbols.forEach(function(key) {
exports.setStubs = function (namespace) {
exported_symbols.forEach(function (key) {
console.assert(!(key in namespace), "property should not be set: " + key);
namespace[key] = exports[key];
});
};
exports.unsetStubs = function(namespace) {
exported_symbols.forEach(function(key) {
exports.unsetStubs = function (namespace) {
exported_symbols.forEach(function (key) {
console.assert(key in namespace, "property should be set: " + key);
delete namespace[key];
});

View File

@ -17,14 +17,14 @@ var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";
// callback.
var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise
.then(function(doc) {
.then(function (doc) {
var numPages = doc.numPages;
console.log("# Document Loaded");
console.log("Number of Pages: " + numPages);
console.log();
var lastPromise; // will be used to chain promises
lastPromise = doc.getMetadata().then(function(data) {
lastPromise = doc.getMetadata().then(function (data) {
console.log("# Metadata Is Loaded");
console.log("## Info");
console.log(JSON.stringify(data.info, null, 2));
@ -36,24 +36,24 @@ loadingTask.promise
}
});
var loadPage = function(pageNum) {
return doc.getPage(pageNum).then(function(page) {
var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height);
console.log();
return page
.getTextContent()
.then(function(content) {
.then(function (content) {
// Content contains lots of information about the text layout and
// styles, but we need only strings at the moment
var strings = content.items.map(function(item) {
var strings = content.items.map(function (item) {
return item.str;
});
console.log("## Text Content");
console.log(strings.join(" "));
})
.then(function() {
.then(function () {
console.log();
});
});
@ -66,10 +66,10 @@ loadingTask.promise
return lastPromise;
})
.then(
function() {
function () {
console.log("# End of Document");
},
function(err) {
function (err) {
console.error("Error: " + err);
}
);

View File

@ -59,11 +59,11 @@ var rawData = new Uint8Array(fs.readFileSync(pdfURL));
// Load the PDF file.
var loadingTask = pdfjsLib.getDocument(rawData);
loadingTask.promise
.then(function(pdfDocument) {
.then(function (pdfDocument) {
console.log("# PDF document loaded.");
// Get the first page.
pdfDocument.getPage(1).then(function(page) {
pdfDocument.getPage(1).then(function (page) {
// Render the page on a Node canvas with 100% scale.
var viewport = page.getViewport({ scale: 1.0 });
var canvasFactory = new NodeCanvasFactory();
@ -78,10 +78,10 @@ loadingTask.promise
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function() {
renderTask.promise.then(function () {
// Convert the canvas to an image buffer.
var image = canvasAndContext.canvas.toBuffer();
fs.writeFile("output.png", image, function(error) {
fs.writeFile("output.png", image, function (error) {
if (error) {
console.error("Error: " + error);
} else {
@ -93,6 +93,6 @@ loadingTask.promise
});
});
})
.catch(function(reason) {
.catch(function (reason) {
console.log(reason);
});

View File

@ -54,7 +54,7 @@ function ReadableSVGStream(options) {
}
util.inherits(ReadableSVGStream, stream.Readable);
// Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1
ReadableSVGStream.prototype._read = function() {
ReadableSVGStream.prototype._read = function () {
var chunk;
while ((chunk = this.serializer.getNext()) !== null) {
if (!this.push(chunk)) {
@ -70,12 +70,12 @@ function writeSvgToFile(svgElement, filePath) {
svgElement: svgElement,
});
var writableStream = fs.createWriteStream(filePath);
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
readableSvgStream.once("error", reject);
writableStream.once("error", reject);
writableStream.once("finish", resolve);
readableSvgStream.pipe(writableStream);
}).catch(function(err) {
}).catch(function (err) {
readableSvgStream = null; // Explicitly null because of v8 bug 6512.
writableStream.end();
throw err;
@ -91,29 +91,29 @@ var loadingTask = pdfjsLib.getDocument({
nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY,
});
loadingTask.promise
.then(function(doc) {
.then(function (doc) {
var numPages = doc.numPages;
console.log("# Document Loaded");
console.log("Number of Pages: " + numPages);
console.log();
var lastPromise = Promise.resolve(); // will be used to chain promises
var loadPage = function(pageNum) {
return doc.getPage(pageNum).then(function(page) {
var loadPage = function (pageNum) {
return doc.getPage(pageNum).then(function (page) {
console.log("# Page " + pageNum);
var viewport = page.getViewport({ scale: 1.0 });
console.log("Size: " + viewport.width + "x" + viewport.height);
console.log();
return page.getOperatorList().then(function(opList) {
return page.getOperatorList().then(function (opList) {
var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs);
svgGfx.embedFonts = true;
return svgGfx.getSVG(opList, viewport).then(function(svg) {
return svgGfx.getSVG(opList, viewport).then(function (svg) {
return writeSvgToFile(svg, getFilePathForPage(pageNum)).then(
function() {
function () {
console.log("Page: " + pageNum);
},
function(err) {
function (err) {
console.log("Error: " + err);
}
);
@ -128,10 +128,10 @@ loadingTask.promise
return lastPromise;
})
.then(
function() {
function () {
console.log("# End of Document");
},
function(err) {
function (err) {
console.error("Error: " + err);
}
);

View File

@ -49,7 +49,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({
});
pdfLinkService.setViewer(pdfViewer);
eventBus.on("pagesinit", function() {
eventBus.on("pagesinit", function () {
// We can use pdfViewer now, e.g. let's change default scale.
pdfViewer.currentScaleValue = "page-width";
});
@ -60,7 +60,7 @@ var loadingTask = pdfjsLib.getDocument({
cMapUrl: CMAP_URL,
cMapPacked: CMAP_PACKED,
});
loadingTask.promise.then(function(pdfDocument) {
loadingTask.promise.then(function (pdfDocument) {
// Document loaded, specifying document for the viewer and
// the (optional) linkService.
pdfViewer.setDocument(pdfDocument);

View File

@ -30,7 +30,7 @@ function buildSVG(viewport, textContent) {
svg.setAttribute("font-size", 1);
// processing all items
textContent.items.forEach(function(textItem) {
textContent.items.forEach(function (textItem) {
// we have to take in account viewport transform, which includes scale,
// rotation and Y-axis flip, and not forgetting to flip text.
var tx = pdfjsLib.Util.transform(
@ -51,10 +51,10 @@ function buildSVG(viewport, textContent) {
function pageLoaded() {
// Loading document and page text content
var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH });
loadingTask.promise.then(function(pdfDocument) {
pdfDocument.getPage(PAGE_NUMBER).then(function(page) {
loadingTask.promise.then(function (pdfDocument) {
pdfDocument.getPage(PAGE_NUMBER).then(function (page) {
var viewport = page.getViewport({ scale: PAGE_SCALE });
page.getTextContent().then(function(textContent) {
page.getTextContent().then(function (textContent) {
// building SVG and adding that to the DOM
var svg = buildSVG(viewport, textContent);
document.getElementById("pageContainer").appendChild(svg);
@ -63,7 +63,7 @@ function pageLoaded() {
});
}
document.addEventListener("DOMContentLoaded", function() {
document.addEventListener("DOMContentLoaded", function () {
if (typeof pdfjsLib === "undefined") {
alert(
"Built version of PDF.js was not found.\n" +

View File

@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc =
// Loading a document.
var loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise
.then(function(pdfDocument) {
.then(function (pdfDocument) {
// Request a first page
return pdfDocument.getPage(1).then(function(pdfPage) {
return pdfDocument.getPage(1).then(function (pdfPage) {
// Display page on the existing canvas with 100% scale.
var viewport = pdfPage.getViewport({ scale: 1.0 });
var canvas = document.getElementById("theCanvas");
@ -30,6 +30,6 @@ loadingTask.promise
return renderTask.promise;
});
})
.catch(function(reason) {
.catch(function (reason) {
console.error("Error: " + reason);
});

View File

@ -61,7 +61,7 @@ limitations under the License.
// (or rewrite the query string parser in viewer.js to get it to
// recognize the non-URL-encoded PDF URL.)
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
function (details) {
// This listener converts chrome-extension://.../http://...pdf to
// chrome-extension://.../content/web/viewer.html?file=http%3A%2F%2F...pdf
var url = parseExtensionURL(details.url);
@ -78,7 +78,7 @@ limitations under the License.
},
{
types: ["main_frame", "sub_frame"],
urls: schemes.map(function(scheme) {
urls: schemes.map(function (scheme) {
// Format: "chrome-extension://[EXTENSIONID]/<scheme>*"
return CRX_BASE_URL + scheme + "*";
}),
@ -94,7 +94,7 @@ limitations under the License.
{
url: CRX_BASE_URL + "*:*",
},
function(tabsFromLastSession) {
function (tabsFromLastSession) {
for (var i = 0; i < tabsFromLastSession.length; ++i) {
chrome.tabs.reload(tabsFromLastSession[i].id);
}
@ -102,7 +102,7 @@ limitations under the License.
);
console.log("Set up extension URL router.");
Object.keys(localStorage).forEach(function(key) {
Object.keys(localStorage).forEach(function (key) {
// The localStorage item is set upon unload by chromecom.js.
var parsedKey = /^unload-(\d+)-(true|false)-(.+)/.exec(key);
if (parsedKey) {

View File

@ -15,7 +15,7 @@ limitations under the License.
*/
/* eslint strict: ["error", "function"] */
(function() {
(function () {
"use strict";
var storageLocal = chrome.storage.local;
var storageSync = chrome.storage.sync;
@ -25,8 +25,8 @@ limitations under the License.
return;
}
getStorageNames(function(storageKeys) {
storageLocal.get(storageKeys, function(values) {
getStorageNames(function (storageKeys) {
storageLocal.get(storageKeys, function (values) {
if (!values || !Object.keys(values).length) {
// No local storage - nothing to migrate.
// ... except possibly for a renamed preference name.
@ -41,7 +41,7 @@ limitations under the License.
var x = new XMLHttpRequest();
var schema_location = chrome.runtime.getManifest().storage.managed_schema;
x.open("get", chrome.runtime.getURL(schema_location));
x.onload = function() {
x.onload = function () {
var storageKeys = Object.keys(x.response.properties);
callback(storageKeys);
};
@ -52,7 +52,7 @@ limitations under the License.
// Save |values| to storage.sync and delete the values with that key from
// storage.local.
function migrateToSyncStorage(values) {
storageSync.set(values, function() {
storageSync.set(values, function () {
if (chrome.runtime.lastError) {
console.error(
"Failed to migrate settings due to an error: " +
@ -61,7 +61,7 @@ limitations under the License.
return;
}
// Migration successful. Delete local settings.
storageLocal.remove(Object.keys(values), function() {
storageLocal.remove(Object.keys(values), function () {
// In theory remove() could fail (e.g. if the browser's storage
// backend is corrupt), but since storageSync.set succeeded, consider
// the migration successful.
@ -89,7 +89,7 @@ limitations under the License.
"disablePageMode",
"viewOnLoad",
],
function(items) {
function (items) {
// Migration code for https://github.com/mozilla/pdf.js/pull/7635.
if (typeof items.enableHandToolOnLoad === "boolean") {
if (items.enableHandToolOnLoad) {
@ -97,7 +97,7 @@ limitations under the License.
{
cursorToolOnLoad: 1,
},
function() {
function () {
if (!chrome.runtime.lastError) {
storageSync.remove("enableHandToolOnLoad");
}
@ -121,7 +121,7 @@ limitations under the License.
{
textLayerMode: textLayerMode,
},
function() {
function () {
if (!chrome.runtime.lastError) {
storageSync.remove([
"disableTextLayer",
@ -141,7 +141,7 @@ limitations under the License.
{
viewOnLoad: 1,
},
function() {
function () {
if (!chrome.runtime.lastError) {
storageSync.remove([
"showPreviousViewOnLoad",

View File

@ -25,13 +25,13 @@ Promise.all([
return;
}
// Get preferences as set by the system administrator.
chrome.storage.managed.get(null, function(prefs) {
chrome.storage.managed.get(null, function (prefs) {
// Managed storage may be disabled, e.g. in Opera.
resolve(prefs || {});
});
}),
new Promise(function getUserPrefs(resolve) {
storageArea.get(null, function(prefs) {
storageArea.get(null, function (prefs) {
resolve(prefs || {});
});
}),
@ -40,14 +40,14 @@ Promise.all([
var x = new XMLHttpRequest();
var schema_location = chrome.runtime.getManifest().storage.managed_schema;
x.open("get", chrome.runtime.getURL(schema_location));
x.onload = function() {
x.onload = function () {
resolve(x.response.properties);
};
x.responseType = "json";
x.send();
}),
])
.then(function(values) {
.then(function (values) {
var managedPrefs = values[0];
var userPrefs = values[1];
var schema = values[2];
@ -62,7 +62,7 @@ Promise.all([
var prefNames = Object.keys(schema);
var renderPreferenceFunctions = {};
// Render options
prefNames.forEach(function(prefName) {
prefNames.forEach(function (prefName) {
var prefSchema = schema[prefName];
if (!prefSchema.title) {
// Don't show preferences if the title is missing.
@ -102,17 +102,17 @@ Promise.all([
var renderedPrefNames = Object.keys(renderPreferenceFunctions);
// Reset button to restore default settings.
document.getElementById("reset-button").onclick = function() {
document.getElementById("reset-button").onclick = function () {
userPrefs = {};
storageArea.remove(prefNames, function() {
renderedPrefNames.forEach(function(prefName) {
storageArea.remove(prefNames, function () {
renderedPrefNames.forEach(function (prefName) {
renderPreferenceFunctions[prefName](getPrefValue(prefName));
});
});
};
// Automatically update the UI when the preferences were changed elsewhere.
chrome.storage.onChanged.addListener(function(changes, areaName) {
chrome.storage.onChanged.addListener(function (changes, areaName) {
var prefs = null;
if (areaName === storageAreaName) {
prefs = userPrefs;
@ -120,7 +120,7 @@ Promise.all([
prefs = managedPrefs;
}
if (prefs) {
renderedPrefNames.forEach(function(prefName) {
renderedPrefNames.forEach(function (prefName) {
var prefChanges = changes[prefName];
if (prefChanges) {
if ("newValue" in prefChanges) {
@ -149,7 +149,7 @@ function renderBooleanPref(shortDescription, description, prefName) {
wrapper.title = description;
var checkbox = wrapper.querySelector('input[type="checkbox"]');
checkbox.onchange = function() {
checkbox.onchange = function () {
var pref = {};
pref[prefName] = this.checked;
storageArea.set(pref);
@ -166,7 +166,7 @@ function renderBooleanPref(shortDescription, description, prefName) {
function renderEnumPref(shortDescription, prefName) {
var wrapper = importTemplate(prefName + "-template");
var select = wrapper.querySelector("select");
select.onchange = function() {
select.onchange = function () {
var pref = {};
pref[prefName] = parseInt(this.value);
storageArea.set(pref);
@ -183,7 +183,7 @@ function renderEnumPref(shortDescription, prefName) {
function renderDefaultZoomValue(shortDescription) {
var wrapper = importTemplate("defaultZoomValue-template");
var select = wrapper.querySelector("select");
select.onchange = function() {
select.onchange = function () {
storageArea.set({
defaultZoomValue: this.value,
});

View File

@ -37,7 +37,7 @@ limitations under the License.
}
}
chrome.runtime.onMessage.addListener(function(message, sender) {
chrome.runtime.onMessage.addListener(function (message, sender) {
if (message === "showPageAction" && sender.tab) {
showPageAction(sender.tab.id, sender.tab.url);
}

View File

@ -16,7 +16,7 @@ limitations under the License.
/* eslint strict: ["error", "function"] */
/* import-globals-from pdfHandler.js */
(function() {
(function () {
"use strict";
if (!chrome.fileBrowserHandler) {
@ -41,12 +41,12 @@ limitations under the License.
// the other Chrome APIs that use "tabId" (http://crbug.com/179767)
var tabId = details.tab_id || details.tabId;
if (tabId > 0) {
chrome.tabs.get(tabId, function(tab) {
chrome.tabs.get(tabId, function (tab) {
openViewer(tab && tab.windowId, fileEntries);
});
} else {
// Re-use existing window, if available.
chrome.windows.getLastFocused(function(chromeWindow) {
chrome.windows.getLastFocused(function (chromeWindow) {
var windowId = chromeWindow && chromeWindow.id;
if (windowId) {
chrome.windows.update(windowId, { focused: true });
@ -82,7 +82,7 @@ limitations under the License.
active: true,
url: url,
},
function() {
function () {
openViewer(windowId, fileEntries);
}
);
@ -93,7 +93,7 @@ limitations under the License.
focused: true,
url: url,
},
function(chromeWindow) {
function (chromeWindow) {
openViewer(chromeWindow.id, fileEntries);
}
);

View File

@ -73,10 +73,7 @@ function getHeaderFromHeaders(headers, headerName) {
function isPdfFile(details) {
var header = getHeaderFromHeaders(details.responseHeaders, "content-type");
if (header) {
var headerValue = header.value
.toLowerCase()
.split(";", 1)[0]
.trim();
var headerValue = header.value.toLowerCase().split(";", 1)[0].trim();
if (headerValue === "application/pdf") {
return true;
}
@ -120,7 +117,7 @@ function getHeadersWithContentDispositionAttachment(details) {
}
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
function (details) {
if (details.method !== "GET") {
// Don't intercept POST requests until http://crbug.com/104058 is fixed.
return undefined;
@ -148,7 +145,7 @@ chrome.webRequest.onHeadersReceived.addListener(
);
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
function (details) {
if (isPdfDownloadable(details)) {
return undefined;
}
@ -176,7 +173,7 @@ chrome.webRequest.onBeforeRequest.addListener(
["blocking"]
);
chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) {
chrome.extension.isAllowedFileSchemeAccess(function (isAllowedAccess) {
if (isAllowedAccess) {
return;
}
@ -186,7 +183,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) {
// The viewer will detect that it has no access to file:-URLs, and prompt the
// user to activate file permissions.
chrome.webNavigation.onBeforeNavigate.addListener(
function(details) {
function (details) {
if (details.frameId === 0 && !isPdfDownloadable(details)) {
chrome.tabs.update(details.tabId, {
url: getViewerURL(details.url),
@ -208,7 +205,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) {
);
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message && message.action === "getParentOrigin") {
// getParentOrigin is used to determine whether it is safe to embed a
// sensitive (local) file in a frame.

View File

@ -43,7 +43,7 @@ var g_referrers = {};
var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders']
(function() {
(function () {
var requestFilter = {
urls: ["*://*/*"],
types: ["main_frame", "sub_frame"],
@ -52,7 +52,7 @@ var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders']
extraInfoSpecWithHeaders = extraInfoSpec;
// May throw if the given extraInfoSpec is unsupported.
chrome.webRequest.onSendHeaders.addListener(
function(details) {
function (details) {
g_requestHeaders[details.requestId] = details.requestHeaders;
},
requestFilter,
@ -87,7 +87,7 @@ function saveReferer(details) {
g_referrers[details.tabId][details.frameId] = referer;
}
chrome.tabs.onRemoved.addListener(function(tabId) {
chrome.tabs.onRemoved.addListener(function (tabId) {
delete g_referrers[tabId];
});
@ -108,7 +108,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) {
// If the PDF is viewed for the first time, then the referer will be set here.
var referer = (g_referrers[tabId] && g_referrers[tabId][frameId]) || "";
port.onMessage.addListener(function(data) {
port.onMessage.addListener(function (data) {
// If the viewer was opened directly (without opening a PDF URL first), then
// the background script does not know about g_referrers, but the viewer may
// know about the referer if stored in the history state (see chromecom.js).
@ -133,7 +133,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) {
});
// The port is only disconnected when the other end reloads.
port.onDisconnect.addListener(function() {
port.onDisconnect.addListener(function () {
if (g_referrers[tabId]) {
delete g_referrers[tabId][frameId];
}

View File

@ -19,7 +19,7 @@ limitations under the License.
// Do not reload the extension when an update becomes available, UNLESS the PDF
// viewer is not displaying any PDF files. Otherwise the tabs would close, which
// is quite disruptive (crbug.com/511670).
chrome.runtime.onUpdateAvailable.addListener(function() {
chrome.runtime.onUpdateAvailable.addListener(function () {
if (chrome.extension.getViews({ type: "tab" }).length === 0) {
chrome.runtime.reload();
}

View File

@ -15,7 +15,7 @@ limitations under the License.
*/
/* eslint strict: ["error", "function"] */
(function() {
(function () {
"use strict";
// This module sends the browser and extension version to a server, to
// determine whether it is safe to drop support for old Chrome versions in
@ -46,7 +46,7 @@ limitations under the License.
setInterval(maybeSendPing, 36e5);
function maybeSendPing() {
getLoggingPref(function(didOptOut) {
getLoggingPref(function (didOptOut) {
if (didOptOut) {
// Respect the user's decision to not send statistics.
return;
@ -154,7 +154,7 @@ limitations under the License.
return;
}
chrome.storage[storageAreaName].get("disableTelemetry", function(items) {
chrome.storage[storageAreaName].get("disableTelemetry", function (items) {
next(items && items.disableTelemetry);
});
}

View File

@ -1,7 +1,7 @@
"use strict";
// Small subset of the webL10n API by Fabien Cazenave for PDF.js extension.
(function(window) {
(function (window) {
var gLanguage = "";
var gExternalLocalizerServices = null;
var gReadyState = "loading";
@ -21,7 +21,7 @@
if (!args) {
return text;
}
return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function(all, name) {
return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function (all, name) {
return name in args ? args[name] : "{{" + name + "}}";
});
}

View File

@ -34,10 +34,7 @@ var fs = require("fs"),
*/
function preprocess(inFilename, outFilename, defines) {
// TODO make this really read line by line.
var lines = fs
.readFileSync(inFilename)
.toString()
.split("\n");
var lines = fs.readFileSync(inFilename).toString().split("\n");
var totalLines = lines.length;
var out = "";
var i = 0;
@ -50,7 +47,7 @@ function preprocess(inFilename, outFilename, defines) {
var writeLine =
typeof outFilename === "function"
? outFilename
: function(line) {
: function (line) {
out += line + "\n";
};
function evaluateCondition(code) {
@ -95,7 +92,7 @@ function preprocess(inFilename, outFilename, defines) {
}
}
function expand(line) {
line = line.replace(/__[\w]+__/g, function(variable) {
line = line.replace(/__[\w]+__/g, function (variable) {
variable = variable.substring(2, variable.length - 2);
if (variable in defines) {
return defines[variable];
@ -122,7 +119,7 @@ function preprocess(inFilename, outFilename, defines) {
var stack = [];
var control = /^(?:\/\/|<!--)\s*#(if|elif|else|endif|expand|include|error)\b(?:\s+(.*?)(?:-->)?$)?/;
var lineNumber = 0;
var loc = function() {
var loc = function () {
return fs.realpathSync(inFilename) + ":" + lineNumber;
};
while ((line = readLine()) !== null) {
@ -215,7 +212,7 @@ function preprocessCSS(mode, source, destination) {
}
function expandImports(content, baseUrl) {
return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function(
return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function (
all,
url
) {

View File

@ -294,7 +294,7 @@ function traverseTree(ctx, node) {
node[i] = result;
}
} else if (Array.isArray(child)) {
child.forEach(function(childItem, index) {
child.forEach(function (childItem, index) {
if (
typeof childItem === "object" &&
childItem !== null &&

View File

@ -9,13 +9,13 @@ var errors = 0;
var baseDir = path.join(__dirname, "fixtures");
var files = fs
.readdirSync(baseDir)
.filter(function(name) {
.filter(function (name) {
return /-expected\./.test(name);
})
.map(function(name) {
.map(function (name) {
return path.join(baseDir, name);
});
files.forEach(function(expectationFilename) {
files.forEach(function (expectationFilename) {
var inFilename = expectationFilename.replace("-expected", "");
var expectation = fs
.readFileSync(expectationFilename)
@ -24,7 +24,7 @@ files.forEach(function(expectationFilename) {
.replace(/__filename/g, fs.realpathSync(inFilename));
var outLines = [];
var outFilename = function(line) {
var outFilename = function (line) {
outLines.push(line);
};
var defines = {

View File

@ -9,13 +9,13 @@ var errors = 0;
var baseDir = path.join(__dirname, "fixtures_esprima");
var files = fs
.readdirSync(baseDir)
.filter(function(name) {
.filter(function (name) {
return /-expected\./.test(name);
})
.map(function(name) {
.map(function (name) {
return path.join(baseDir, name);
});
files.forEach(function(expectationFilename) {
files.forEach(function (expectationFilename) {
var inFilename = expectationFilename.replace("-expected", "");
var expectation = fs
.readFileSync(expectationFilename)

View File

@ -36,15 +36,15 @@ function downloadLanguageCodes() {
var ALL_LOCALES =
"https://hg.mozilla.org/mozilla-central/raw-file/tip/browser/locales/all-locales";
return new Promise(function(resolve) {
https.get(ALL_LOCALES, function(response) {
return new Promise(function (resolve) {
https.get(ALL_LOCALES, function (response) {
if (response.statusCode === 200) {
var content = "";
response.setEncoding("utf8");
response.on("data", function(chunk) {
response.on("data", function (chunk) {
content += chunk;
});
response.on("end", function() {
response.on("end", function () {
content = content.trim(); // Remove any leading/trailing white-space.
var langCodes = normalizeText(content).split("\n");
// Remove all locales that we don't want to download below.
@ -80,22 +80,22 @@ function downloadLanguageFiles(root, langCode) {
fs.mkdirSync(outputDir);
}
return new Promise(function(resolve) {
return new Promise(function (resolve) {
// Download the necessary files for this language.
files.forEach(function(fileName) {
files.forEach(function (fileName) {
var outputPath = path.join(outputDir, fileName);
var url = MOZ_CENTRAL_ROOT + langCode + MOZ_CENTRAL_PDFJS_DIR + fileName;
https.get(url, function(response) {
https.get(url, function (response) {
// Not all files exist for each language. Files without translations
// have been removed (https://bugzilla.mozilla.org/show_bug.cgi?id=1443175).
if (response.statusCode === 200) {
var content = "";
response.setEncoding("utf8");
response.on("data", function(chunk) {
response.on("data", function (chunk) {
content += chunk;
});
response.on("end", function() {
response.on("end", function () {
fs.writeFileSync(outputPath, normalizeText(content), "utf8");
if (--downloadsLeft === 0) {
resolve();

View File

@ -22,17 +22,17 @@ var dbPromise;
function getDb() {
if (!dbPromise) {
dbPromise = new Promise(function(resolve, reject) {
dbPromise = new Promise(function (resolve, reject) {
var request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = function() {
request.onupgradeneeded = function () {
var db = request.result;
db.createObjectStore(dbCacheTable, { keyPath: "address" });
};
request.onsuccess = function() {
request.onsuccess = function () {
var db = request.result;
resolve(db);
};
request.onerror = function() {
request.onerror = function () {
console.warn("getDb: " + request.error);
reject(request.error);
};
@ -42,7 +42,7 @@ function getDb() {
}
function storeCache(address, hashCode, translated, format) {
return getDb().then(function(db) {
return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readwrite");
var store = tx.objectStore(dbCacheTable);
store.put({
@ -52,11 +52,11 @@ function storeCache(address, hashCode, translated, format) {
expires: Date.now() + cacheExpiration,
format: format,
});
return new Promise(function(resolve, reject) {
tx.oncomplete = function() {
return new Promise(function (resolve, reject) {
tx.oncomplete = function () {
resolve();
};
tx.onerror = function() {
tx.onerror = function () {
resolve();
};
});
@ -64,12 +64,12 @@ function storeCache(address, hashCode, translated, format) {
}
function loadCache(address, hashCode) {
return getDb().then(function(db) {
return getDb().then(function (db) {
var tx = db.transaction(dbCacheTable, "readonly");
var store = tx.objectStore(dbCacheTable);
var getAddress = store.get(address);
return new Promise(function(resolve, reject) {
tx.oncomplete = function() {
return new Promise(function (resolve, reject) {
tx.oncomplete = function () {
var found = getAddress.result;
var isValid =
found && found.hashCode === hashCode && Date.now() < found.expires;
@ -82,7 +82,7 @@ function loadCache(address, hashCode) {
: null
);
};
tx.onerror = function() {
tx.onerror = function () {
resolve(null);
};
});
@ -92,7 +92,7 @@ function loadCache(address, hashCode) {
var encoder = new TextEncoder("utf-8");
function sha256(str) {
var buffer = encoder.encode(str);
return crypto.subtle.digest("SHA-256", buffer).then(function(hash) {
return crypto.subtle.digest("SHA-256", buffer).then(function (hash) {
var data = new Int32Array(hash);
return (
data[0].toString(36) +
@ -106,38 +106,38 @@ function sha256(str) {
});
}
exports.translate = function(load, opt) {
exports.translate = function (load, opt) {
var savedHashCode, babelTranslateError;
return sha256(load.source)
.then(function(hashCode) {
.then(function (hashCode) {
savedHashCode = hashCode;
return loadCache(load.address, hashCode);
})
.then(
function(cache) {
function (cache) {
if (cache) {
load.metadata.format = cache.format;
return cache.translated;
}
return babel.translate.call(this, load, opt).then(
function(translated) {
function (translated) {
return storeCache(
load.address,
savedHashCode,
translated,
load.metadata.format
).then(function() {
).then(function () {
return translated;
});
},
function(reason) {
function (reason) {
throw (babelTranslateError = reason);
}
);
}.bind(this)
)
.catch(
function(reason) {
function (reason) {
if (babelTranslateError) {
throw babelTranslateError;
}

View File

@ -19,7 +19,7 @@
var preprocessor2 = require("../builder/preprocessor2.js");
var path = require("path");
module.exports = function(source) {
module.exports = function (source) {
// Options must be specified, ignoring request if not.
if (!this.query || typeof this.query !== "object") {
return source;
@ -28,10 +28,7 @@ module.exports = function(source) {
var filePath = this.resourcePath;
var context = this.rootContext;
var sourcePath = path
.relative(context, filePath)
.split(path.sep)
.join("/");
var sourcePath = path.relative(context, filePath).split(path.sep).join("/");
var ctx = Object.create(this.query);
ctx.sourceMap = true;

View File

@ -105,7 +105,7 @@ var DEFINES = {
};
function transform(charEncoding, transformFunction) {
return through.obj(function(vinylFile, enc, done) {
return through.obj(function (vinylFile, enc, done) {
var transformedFile = vinylFile.clone();
transformedFile.contents = Buffer.from(
transformFunction(transformedFile.contents),
@ -154,7 +154,7 @@ function startNode(args, options) {
function createStringSource(filename, content) {
var source = stream.Readable({ objectMode: true });
source._read = function() {
source._read = function () {
this.push(
new Vinyl({
path: filename,
@ -253,7 +253,7 @@ function getVersionJSON() {
function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) {
var chromePrefs = JSON.parse(fs.readFileSync(chromePrefsPath).toString());
var chromePrefsKeys = Object.keys(chromePrefs.properties);
chromePrefsKeys = chromePrefsKeys.filter(function(key) {
chromePrefsKeys = chromePrefsKeys.filter(function (key) {
var description = chromePrefs.properties[key].description;
// Deprecated keys are allowed in the managed preferences file.
// The code maintained is responsible for adding migration logic to
@ -274,7 +274,7 @@ function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) {
if (webPrefsKeys.length !== chromePrefsKeys.length) {
return false;
}
return webPrefsKeys.every(function(value, index) {
return webPrefsKeys.every(function (value, index) {
return (
chromePrefsKeys[index] === value &&
chromePrefs.properties[value].default === webPrefs[value]
@ -402,9 +402,7 @@ function replaceInFile(filePath, find, replacement) {
function getTempFile(prefix, suffix) {
mkdirp.sync(BUILD_DIR + "tmp/");
var bytes = require("crypto")
.randomBytes(6)
.toString("hex");
var bytes = require("crypto").randomBytes(6).toString("hex");
var filePath = BUILD_DIR + "tmp/" + prefix + bytes + suffix;
fs.writeFileSync(filePath, "");
return filePath;
@ -412,7 +410,7 @@ function getTempFile(prefix, suffix) {
function createTestSource(testsName, bot) {
var source = stream.Readable({ objectMode: true });
source._read = function() {
source._read = function () {
console.log();
console.log("### Running " + testsName + " tests");
@ -456,7 +454,7 @@ function createTestSource(testsName, bot) {
}
var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function(code) {
testProcess.on("close", function (code) {
source.push(null);
});
return undefined;
@ -489,26 +487,26 @@ function makeRef(done, bot) {
}
args.push("--browserManifestFile=" + PDF_BROWSERS);
var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" });
testProcess.on("close", function(code) {
testProcess.on("close", function (code) {
done();
});
}
gulp.task("default", function(done) {
gulp.task("default", function (done) {
console.log("Available tasks:");
var tasks = Object.keys(gulp.registry().tasks());
tasks.sort();
tasks.forEach(function(taskName) {
tasks.forEach(function (taskName) {
console.log(" " + taskName);
});
done();
});
gulp.task("buildnumber", function(done) {
gulp.task("buildnumber", function (done) {
console.log();
console.log("### Getting extension build number");
exec("git log --format=oneline " + config.baseVersion + "..", function(
exec("git log --format=oneline " + config.baseVersion + "..", function (
err,
stdout,
stderr
@ -525,7 +523,7 @@ gulp.task("buildnumber", function(done) {
var version = config.versionPrefix + buildNumber;
exec('git log --format="%h" -n 1', function(err2, stdout2, stderr2) {
exec('git log --format="%h" -n 1', function (err2, stdout2, stderr2) {
var buildCommit = "";
if (!err2) {
buildCommit = stdout2.replace("\n", "");
@ -549,7 +547,7 @@ gulp.task("buildnumber", function(done) {
});
});
gulp.task("default_preferences-pre", function() {
gulp.task("default_preferences-pre", function () {
console.log();
console.log("### Building `default_preferences.json`");
@ -610,7 +608,7 @@ gulp.task("default_preferences-pre", function() {
gulp.task(
"default_preferences",
gulp.series("default_preferences-pre", function(done) {
gulp.series("default_preferences-pre", function (done) {
var AppOptionsLib = require("./" +
DEFAULT_PREFERENCES_DIR +
"lib/web/app_options.js");
@ -626,7 +624,7 @@ gulp.task(
})
);
gulp.task("locale", function() {
gulp.task("locale", function () {
var VIEWER_LOCALE_OUTPUT = "web/locale/";
console.log();
@ -677,7 +675,7 @@ gulp.task("locale", function() {
]);
});
gulp.task("cmaps", function(done) {
gulp.task("cmaps", function (done) {
var CMAP_INPUT = "external/cmaps";
var VIEWER_CMAP_OUTPUT = "external/bcmaps";
@ -692,7 +690,7 @@ gulp.task("cmaps", function(done) {
}
// Remove old bcmap files.
fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function(file) {
fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function (file) {
if (/\.bcmap$/i.test(file)) {
fs.unlinkSync(VIEWER_CMAP_OUTPUT + "/" + file);
}
@ -706,7 +704,7 @@ gulp.task("cmaps", function(done) {
gulp.task(
"bundle",
gulp.series("buildnumber", function() {
gulp.series("buildnumber", function () {
return createBundle(DEFINES).pipe(gulp.dest(BUILD_DIR));
})
);
@ -775,7 +773,7 @@ function buildGeneric(defines, dir) {
// HTML5 browsers, which implement modern ECMAScript features.
gulp.task(
"generic",
gulp.series("buildnumber", "default_preferences", "locale", function() {
gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log();
console.log("### Creating generic viewer");
var defines = builder.merge(DEFINES, { GENERIC: true });
@ -788,7 +786,7 @@ gulp.task(
// older HTML5 browsers.
gulp.task(
"generic-es5",
gulp.series("buildnumber", "default_preferences", "locale", function() {
gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log();
console.log("### Creating generic (ES5) viewer");
var defines = builder.merge(DEFINES, { GENERIC: true, SKIP_BABEL: false });
@ -824,7 +822,7 @@ function buildComponents(defines, dir) {
gulp.task(
"components",
gulp.series("buildnumber", function() {
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating generic components");
var defines = builder.merge(DEFINES, { COMPONENTS: true, GENERIC: true });
@ -835,7 +833,7 @@ gulp.task(
gulp.task(
"components-es5",
gulp.series("buildnumber", function() {
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating generic (ES5) components");
var defines = builder.merge(DEFINES, {
@ -850,7 +848,7 @@ gulp.task(
gulp.task(
"image_decoders",
gulp.series("buildnumber", function() {
gulp.series("buildnumber", function () {
console.log();
console.log("### Creating image decoders");
var defines = builder.merge(DEFINES, {
@ -866,7 +864,7 @@ gulp.task(
gulp.task(
"minified-pre",
gulp.series("buildnumber", "default_preferences", "locale", function() {
gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log();
console.log("### Creating minified viewer");
var defines = builder.merge(DEFINES, { MINIFIED: true, GENERIC: true });
@ -916,7 +914,7 @@ gulp.task(
gulp.task(
"minified-post",
gulp.series("minified-pre", function(done) {
gulp.series("minified-pre", function (done) {
var pdfFile = fs.readFileSync(MINIFIED_DIR + "/build/pdf.js").toString();
var pdfWorkerFile = fs
.readFileSync(MINIFIED_DIR + "/build/pdf.worker.js")
@ -1008,7 +1006,7 @@ function preprocessDefaultPreferences(content) {
gulp.task(
"mozcentral-pre",
gulp.series("buildnumber", "default_preferences", function() {
gulp.series("buildnumber", "default_preferences", function () {
console.log();
console.log("### Building mozilla-central extension");
var defines = builder.merge(DEFINES, { MOZCENTRAL: true });
@ -1075,7 +1073,7 @@ gulp.task("mozcentral", gulp.series("mozcentral-pre"));
gulp.task(
"chromium-pre",
gulp.series("buildnumber", "default_preferences", "locale", function() {
gulp.series("buildnumber", "default_preferences", "locale", function () {
console.log();
console.log("### Building Chromium extension");
var defines = builder.merge(DEFINES, { CHROME: true, SKIP_BABEL: false });
@ -1138,14 +1136,14 @@ gulp.task(
gulp.task("chromium", gulp.series("chromium-pre"));
gulp.task("jsdoc", function(done) {
gulp.task("jsdoc", function (done) {
console.log();
console.log("### Generating documentation (JSDoc)");
var JSDOC_FILES = ["src/doc_helper.js", "src/display/api.js"];
rimraf(JSDOC_BUILD_DIR, function() {
mkdirp(JSDOC_BUILD_DIR).then(function() {
rimraf(JSDOC_BUILD_DIR, function () {
mkdirp(JSDOC_BUILD_DIR).then(function () {
var command =
'"node_modules/.bin/jsdoc" -d ' +
JSDOC_BUILD_DIR +
@ -1238,7 +1236,7 @@ function buildLib(defines, dir) {
gulp.task(
"lib",
gulp.series("buildnumber", "default_preferences", function() {
gulp.series("buildnumber", "default_preferences", function () {
var defines = builder.merge(DEFINES, { GENERIC: true, LIB: true });
return buildLib(defines, "build/lib/");
@ -1247,7 +1245,7 @@ gulp.task(
gulp.task(
"lib-es5",
gulp.series("buildnumber", "default_preferences", function() {
gulp.series("buildnumber", "default_preferences", function () {
var defines = builder.merge(DEFINES, {
GENERIC: true,
LIB: true,
@ -1263,14 +1261,14 @@ function compressPublish(targetName, dir) {
.src(dir + "**")
.pipe(zip(targetName))
.pipe(gulp.dest(BUILD_DIR))
.on("end", function() {
.on("end", function () {
console.log("Built distribution file: " + targetName);
});
}
gulp.task(
"publish",
gulp.series("generic", "generic-es5", function(done) {
gulp.series("generic", "generic-es5", function (done) {
var version = JSON.parse(
fs.readFileSync(BUILD_DIR + "version.json").toString()
).version;
@ -1288,14 +1286,14 @@ gulp.task(
})
);
gulp.task("testing-pre", function(done) {
gulp.task("testing-pre", function (done) {
process.env["TESTING"] = "true";
done();
});
gulp.task(
"test",
gulp.series("testing-pre", "generic", "components", function() {
gulp.series("testing-pre", "generic", "components", function () {
return streamqueue(
{ objectMode: true },
createTestSource("unit"),
@ -1306,7 +1304,7 @@ gulp.task(
gulp.task(
"bottest",
gulp.series("testing-pre", "generic", "components", function() {
gulp.series("testing-pre", "generic", "components", function () {
return streamqueue(
{ objectMode: true },
createTestSource("unit", true),
@ -1318,40 +1316,40 @@ gulp.task(
gulp.task(
"browsertest",
gulp.series("testing-pre", "generic", "components", function() {
gulp.series("testing-pre", "generic", "components", function () {
return createTestSource("browser");
})
);
gulp.task(
"unittest",
gulp.series("testing-pre", "generic", "components", function() {
gulp.series("testing-pre", "generic", "components", function () {
return createTestSource("unit");
})
);
gulp.task(
"fonttest",
gulp.series("testing-pre", function() {
gulp.series("testing-pre", function () {
return createTestSource("font");
})
);
gulp.task(
"makeref",
gulp.series("testing-pre", "generic", "components", function(done) {
gulp.series("testing-pre", "generic", "components", function (done) {
makeRef(done);
})
);
gulp.task(
"botmakeref",
gulp.series("testing-pre", "generic", "components", function(done) {
gulp.series("testing-pre", "generic", "components", function (done) {
makeRef(done, true);
})
);
gulp.task("baseline", function(done) {
gulp.task("baseline", function (done) {
console.log();
console.log("### Creating baseline environment");
@ -1368,13 +1366,13 @@ gulp.task("baseline", function(done) {
}
var workingDirectory = path.resolve(process.cwd(), BASELINE_DIR);
exec(initializeCommand, { cwd: workingDirectory }, function(error) {
exec(initializeCommand, { cwd: workingDirectory }, function (error) {
if (error) {
done(new Error("Baseline clone/fetch failed."));
return;
}
exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function(
exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function (
error2
) {
if (error2) {
@ -1390,13 +1388,13 @@ gulp.task("baseline", function(done) {
gulp.task(
"unittestcli",
gulp.series("testing-pre", "lib-es5", function(done) {
gulp.series("testing-pre", "lib-es5", function (done) {
var options = [
"node_modules/jasmine/bin/jasmine",
"JASMINE_CONFIG_PATH=test/unit/clitests.json",
];
var jasmineProcess = startNode(options, { stdio: "inherit" });
jasmineProcess.on("close", function(code) {
jasmineProcess.on("close", function (code) {
if (code !== 0) {
done(new Error("Unit tests failed."));
return;
@ -1406,7 +1404,7 @@ gulp.task(
})
);
gulp.task("lint", function(done) {
gulp.task("lint", function (done) {
console.log();
console.log("### Linting JS files");
@ -1422,7 +1420,7 @@ gulp.task("lint", function(done) {
options.push("--fix");
}
var esLintProcess = startNode(options, { stdio: "inherit" });
esLintProcess.on("close", function(code) {
esLintProcess.on("close", function (code) {
if (code !== 0) {
done(new Error("ESLint failed."));
return;
@ -1434,7 +1432,7 @@ gulp.task("lint", function(done) {
gulp.task(
"lint-chromium",
gulp.series("default_preferences", function(done) {
gulp.series("default_preferences", function (done) {
console.log();
console.log("### Checking supplemental Chromium files");
@ -1451,7 +1449,7 @@ gulp.task(
})
);
gulp.task("server", function() {
gulp.task("server", function () {
console.log();
console.log("### Starting local server");
@ -1461,14 +1459,14 @@ gulp.task("server", function() {
server.start();
});
gulp.task("clean", function(done) {
gulp.task("clean", function (done) {
console.log();
console.log("### Cleaning up project builds");
rimraf(BUILD_DIR, done);
});
gulp.task("makefile", function() {
gulp.task("makefile", function () {
var makefileContent = "help:\n\tgulp\n\n";
var targetsNames = [];
for (var i in target) {
@ -1479,7 +1477,7 @@ gulp.task("makefile", function() {
return createStringSource("Makefile", makefileContent).pipe(gulp.dest("."));
});
gulp.task("importl10n", function(done) {
gulp.task("importl10n", function (done) {
var locales = require("./external/importL10n/locales.js");
console.log();
@ -1491,7 +1489,7 @@ gulp.task("importl10n", function(done) {
locales.downloadL10n(L10N_DIR, done);
});
gulp.task("gh-pages-prepare", function() {
gulp.task("gh-pages-prepare", function () {
console.log();
console.log("### Creating web site");
@ -1514,10 +1512,10 @@ gulp.task("gh-pages-prepare", function() {
]);
});
gulp.task("wintersmith", function(done) {
gulp.task("wintersmith", function (done) {
var wintersmith = require("wintersmith");
var env = wintersmith("docs/config.json");
env.build(GH_PAGES_DIR, function(error) {
env.build(GH_PAGES_DIR, function (error) {
if (error) {
done(error);
return;
@ -1552,7 +1550,7 @@ gulp.task("wintersmith", function(done) {
});
});
gulp.task("gh-pages-git", function(done) {
gulp.task("gh-pages-git", function (done) {
var VERSION = getVersionJSON().version;
var reason = process.env["PDFJS_UPDATE_REASON"];
@ -1601,7 +1599,7 @@ gulp.task(
"image_decoders",
"lib",
"minified",
function() {
function () {
var VERSION = getVersionJSON().version;
console.log();
@ -1719,7 +1717,7 @@ gulp.task(
gulp.task(
"dist-install",
gulp.series("dist-pre", function(done) {
gulp.series("dist-pre", function (done) {
var distPath = DIST_DIR;
var opts = {};
var installPath = process.env["PDFJS_INSTALL_PATH"];
@ -1734,7 +1732,7 @@ gulp.task(
gulp.task(
"dist-repo-git",
gulp.series("dist-pre", function(done) {
gulp.series("dist-pre", function (done) {
var VERSION = getVersionJSON().version;
console.log();
@ -1777,7 +1775,7 @@ gulp.task("dist", gulp.series("dist-repo-git"));
gulp.task(
"mozcentralbaseline",
gulp.series("baseline", function(done) {
gulp.series("baseline", function (done) {
console.log();
console.log("### Creating mozcentral baseline environment");
@ -1798,7 +1796,7 @@ gulp.task(
gulp
.src([BASELINE_DIR + BUILD_DIR + "mozcentral/**/*"])
.pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR))
.on("end", function() {
.on("end", function () {
// Commit the mozcentral baseline.
safeSpawnSync("git", ["init"], { cwd: MOZCENTRAL_BASELINE_DIR });
safeSpawnSync("git", ["add", "."], { cwd: MOZCENTRAL_BASELINE_DIR });
@ -1812,7 +1810,7 @@ gulp.task(
gulp.task(
"mozcentraldiff",
gulp.series("mozcentral", "mozcentralbaseline", function(done) {
gulp.series("mozcentral", "mozcentralbaseline", function (done) {
console.log();
console.log("### Creating mozcentral diff");
@ -1826,7 +1824,7 @@ gulp.task(
gulp
.src([BUILD_DIR + "mozcentral/**/*"])
.pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR))
.on("end", function() {
.on("end", function () {
safeSpawnSync("git", ["add", "-A"], { cwd: MOZCENTRAL_BASELINE_DIR });
var diff = safeSpawnSync(
"git",
@ -1836,7 +1834,7 @@ gulp.task(
createStringSource(MOZCENTRAL_DIFF_FILE, diff)
.pipe(gulp.dest(BUILD_DIR))
.on("end", function() {
.on("end", function () {
console.log(
"Result diff can be found at " + BUILD_DIR + MOZCENTRAL_DIFF_FILE
);
@ -1846,7 +1844,7 @@ gulp.task(
})
);
gulp.task("externaltest", function(done) {
gulp.task("externaltest", function (done) {
fancylog("Running test-fixtures.js");
safeSpawnSync("node", ["external/builder/test-fixtures.js"], {
stdio: "inherit",

6
package-lock.json generated
View File

@ -11310,9 +11310,9 @@
"dev": true
},
"prettier": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz",
"integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==",
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz",
"integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==",
"dev": true
},
"prettier-linter-helpers": {

View File

@ -37,7 +37,7 @@
"mkdirp": "^1.0.3",
"postcss-calc": "^7.0.2",
"postcss-css-variables": "^0.14.0",
"prettier": "^1.19.1",
"prettier": "^2.0.4",
"rimraf": "^2.7.1",
"streamqueue": "^1.1.2",
"systemjs": "^0.21.6",

View File

@ -503,7 +503,7 @@ class Annotation {
}
const objectLoader = new ObjectLoader(resources, keys, resources.xref);
return objectLoader.load().then(function() {
return objectLoader.load().then(function () {
return resources;
});
});
@ -941,7 +941,7 @@ class TextWidgetAnnotation extends WidgetAnnotation {
resources: this.fieldResources,
operatorList,
})
.then(function() {
.then(function () {
return operatorList;
});
}

View File

@ -47,7 +47,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {
CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);
CCITTFaxStream.prototype.readBlock = function() {
CCITTFaxStream.prototype.readBlock = function () {
while (!this.eof) {
const c = this.ccittFaxDecoder.readNextChar();
if (c === -1) {

View File

@ -280,7 +280,7 @@ class ChunkedStream {
function ChunkedStreamSubstream() {}
ChunkedStreamSubstream.prototype = Object.create(this);
ChunkedStreamSubstream.prototype.getMissingChunks = function() {
ChunkedStreamSubstream.prototype.getMissingChunks = function () {
const chunkSize = this.chunkSize;
const beginChunk = Math.floor(this.start / chunkSize);
const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
@ -292,7 +292,7 @@ class ChunkedStream {
}
return missingChunks;
};
ChunkedStreamSubstream.prototype.allChunksLoaded = function() {
ChunkedStreamSubstream.prototype.allChunksLoaded = function () {
if (this.numChunksLoaded === this.numChunks) {
return true;
}
@ -454,7 +454,7 @@ class ChunkedStreamManager {
}
}
chunksToRequest.sort(function(a, b) {
chunksToRequest.sort(function (a, b) {
return a - b;
});
return this._requestChunks(chunksToRequest);

View File

@ -530,7 +530,7 @@ var BinaryCMapReader = (function BinaryCMapReaderClosure() {
};
function processBinaryCMap(data, cMap, extend) {
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
var stream = new BinaryCMapStream(data);
var header = stream.readByte();
cMap.vertical = !!(header & 1);
@ -934,7 +934,9 @@ var CMapFactory = (function CMapFactoryClosure() {
}
function extendCMap(cMap, fetchBuiltInCMap, useCMap) {
return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function(newCMap) {
return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function (
newCMap
) {
cMap.useCMap = newCMap;
// If there aren't any code space ranges defined clone all the parent ones
// into this cMap.
@ -947,7 +949,7 @@ var CMapFactory = (function CMapFactoryClosure() {
}
// Merge the map into the current one, making sure not to override
// any previously defined entries.
cMap.useCMap.forEach(function(key, value) {
cMap.useCMap.forEach(function (key, value) {
if (!cMap.contains(key)) {
cMap.mapOne(key, cMap.useCMap.lookup(key));
}
@ -972,13 +974,13 @@ var CMapFactory = (function CMapFactoryClosure() {
);
}
return fetchBuiltInCMap(name).then(function(data) {
return fetchBuiltInCMap(name).then(function (data) {
var cMapData = data.cMapData,
compressionType = data.compressionType;
var cMap = new CMap(true);
if (compressionType === CMapCompressionType.BINARY) {
return new BinaryCMapReader().process(cMapData, cMap, function(
return new BinaryCMapReader().process(cMapData, cMap, function (
useCMap
) {
return extendCMap(cMap, fetchBuiltInCMap, useCMap);
@ -1007,7 +1009,7 @@ var CMapFactory = (function CMapFactoryClosure() {
} else if (isStream(encoding)) {
var cMap = new CMap();
var lexer = new Lexer(encoding);
return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function(
return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function (
parsedCMap
) {
if (parsedCMap.isIdentityCMap) {

View File

@ -18,7 +18,7 @@ import { assert, BaseException, warn } from "../shared/util.js";
function getLookupTableFactory(initializer) {
let lookup;
return function() {
return function () {
if (initializer) {
lookup = Object.create(null);
initializer(lookup);

View File

@ -282,7 +282,7 @@ class Page {
resources: this.resources,
operatorList: opList,
})
.then(function() {
.then(function () {
return opList;
});
});
@ -290,7 +290,7 @@ class Page {
// Fetch the page's annotations and add their operator lists to the
// page's operator list to render them.
return Promise.all([pageListPromise, this._parsedAnnotations]).then(
function([pageOpList, annotations]) {
function ([pageOpList, annotations]) {
if (annotations.length === 0) {
pageOpList.flush(true);
return { length: pageOpList.totalLength };
@ -311,7 +311,7 @@ class Page {
}
}
return Promise.all(opListPromises).then(function(opLists) {
return Promise.all(opListPromises).then(function (opLists) {
pageOpList.addOp(OPS.beginAnnotations, []);
for (const opList of opLists) {
pageOpList.addOpList(opList);
@ -366,7 +366,7 @@ class Page {
}
getAnnotationsData(intent) {
return this._parsedAnnotations.then(function(annotations) {
return this._parsedAnnotations.then(function (annotations) {
const annotationsData = [];
for (let i = 0, ii = annotations.length; i < ii; i++) {
if (!intent || isAnnotationRenderable(annotations[i], intent)) {
@ -403,12 +403,12 @@ class Page {
}
return Promise.all(annotationPromises).then(
function(annotations) {
function (annotations) {
return annotations.filter(function isDefined(annotation) {
return !!annotation;
});
},
function(reason) {
function (reason) {
warn(`_parsedAnnotations: "${reason}".`);
return [];
}

View File

@ -127,9 +127,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
});
const reader = readableStream.getReader();
const data = await new Promise(function(resolve, reject) {
const data = await new Promise(function (resolve, reject) {
function pump() {
reader.read().then(function({ value, done }) {
reader.read().then(function ({ value, done }) {
if (done) {
return;
}
@ -432,7 +432,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
resources: dict.get("Resources") || resources,
operatorList,
initialState,
}).then(function() {
}).then(function () {
operatorList.addOp(OPS.paintFormXObjectEnd, []);
if (group) {
@ -566,7 +566,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
image.getIR(this.options.forceDataSchema),
])
.then(
function() {
function () {
// Only add the dependency once we know that the native JPEG
// decoding succeeded, to ensure that rendering will always
// complete.
@ -738,7 +738,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
resources: patternResources,
operatorList: tilingOpList,
})
.then(function() {
.then(function () {
return getTilingPatternIR(
{
fnArray: tilingOpList.fnArray,
@ -749,7 +749,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
);
})
.then(
function(tilingPatternIR) {
function (tilingPatternIR) {
// Add the dependencies to the parent operator list so they are
// resolved before the sub operator list is executed synchronously.
operatorList.addDependencies(tilingOpList.dependencies);
@ -795,7 +795,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}
return translated
.loadType3Data(this, resources, operatorList, task)
.then(function() {
.then(function () {
return translated;
})
.catch(reason => {
@ -896,7 +896,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
operatorList,
task,
stateManager.state
).then(function(loadedName) {
).then(function (loadedName) {
operatorList.addDependency(loadedName);
gStateObj.push([key, [loadedName, value[1]]]);
});
@ -950,7 +950,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
break;
}
}
return promise.then(function() {
return promise.then(function () {
if (gStateObj.length > 0) {
operatorList.addOp(OPS.setGState, [gStateObj]);
}
@ -985,8 +985,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}
}
if (!fontRef) {
const partialMsg = `Font "${fontName ||
(font && font.toString())}" is not available`;
const partialMsg = `Font "${
fontName || (font && font.toString())
}" is not available`;
if (!this.options.ignoreErrors && !this.parsingType3Font) {
warn(`${partialMsg}.`);
@ -1275,8 +1276,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}
return new Promise(function promiseBody(resolve, reject) {
const next = function(promise) {
Promise.all([promise, operatorList.ready]).then(function() {
const next = function (promise) {
Promise.all([promise, operatorList.ready]).then(function () {
try {
promiseBody(resolve, reject);
} catch (ex) {
@ -1314,7 +1315,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}
next(
new Promise(function(resolveXObject, rejectXObject) {
new Promise(function (resolveXObject, rejectXObject) {
if (!name) {
throw new FormatError(
"XObject must be referred to by name."
@ -1347,7 +1348,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
task,
stateManager.state.clone()
)
.then(function() {
.then(function () {
stateManager.restore();
resolveXObject();
}, rejectXObject);
@ -1373,7 +1374,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
);
}
resolveXObject();
}).catch(function(reason) {
}).catch(function (reason) {
if (reason instanceof AbortException) {
return;
}
@ -1403,7 +1404,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
task,
stateManager.state
)
.then(function(loadedName) {
.then(function (loadedName) {
operatorList.addDependency(loadedName);
operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
})
@ -1497,7 +1498,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
cs: args[0],
resources,
})
.then(function(colorSpace) {
.then(function (colorSpace) {
if (colorSpace) {
stateManager.state.fillColorSpace = colorSpace;
}
@ -1511,7 +1512,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
cs: args[0],
resources,
})
.then(function(colorSpace) {
.then(function (colorSpace) {
if (colorSpace) {
stateManager.state.strokeColorSpace = colorSpace;
}
@ -1875,7 +1876,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
function handleSetFont(fontName, fontRef) {
return self
.loadFont(fontName, fontRef, resources)
.then(function(translated) {
.then(function (translated) {
textState.font = translated.font;
textState.fontMatrix =
translated.font.fontMatrix || FONT_IDENTITY_MATRIX;
@ -1983,9 +1984,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
var timeSlotManager = new TimeSlotManager();
return new Promise(function promiseBody(resolve, reject) {
const next = function(promise) {
const next = function (promise) {
enqueueChunk();
Promise.all([promise, sink.ready]).then(function() {
Promise.all([promise, sink.ready]).then(function () {
try {
promiseBody(resolve, reject);
} catch (ex) {
@ -2236,7 +2237,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
}
next(
new Promise(function(resolveXObject, rejectXObject) {
new Promise(function (resolveXObject, rejectXObject) {
if (!name) {
throw new FormatError(
"XObject must be referred to by name."
@ -2307,13 +2308,13 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
sink: sinkWrapper,
seenStyles,
})
.then(function() {
.then(function () {
if (!sinkWrapper.enqueueInvoked) {
skipEmptyXObjs[name] = true;
}
resolveXObject();
}, rejectXObject);
}).catch(function(reason) {
}).catch(function (reason) {
if (reason instanceof AbortException) {
return;
}
@ -2673,10 +2674,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: ucs2CMapName,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function(ucs2CMap) {
}).then(function (ucs2CMap) {
const cMap = properties.cMap;
const toUnicode = [];
cMap.forEach(function(charcode, cid) {
cMap.forEach(function (charcode, cid) {
if (cid > 0xffff) {
throw new FormatError("Max size of CID is 65,535");
}
@ -2706,7 +2707,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: cmapObj,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function(cmap) {
}).then(function (cmap) {
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xffff);
}
@ -2718,7 +2719,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(
function(cmap) {
function (cmap) {
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xffff);
}
@ -2726,7 +2727,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// Convert UTF-16BE
// NOTE: cmap can be a sparse array, so use forEach instead of
// `for(;;)` to iterate over all keys.
cmap.forEach(function(charCode, token) {
cmap.forEach(function (charCode, token) {
var str = [];
for (var k = 0; k < token.length; k += 2) {
var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
@ -3212,7 +3213,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
encoding: cidEncoding,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function(cMap) {
}).then(function (cMap) {
properties.cMap = cMap;
properties.vertical = properties.cMap.vertical;
});
@ -3235,7 +3236,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
},
};
PartialEvaluator.buildFontPaths = function(font, glyphs, handler) {
PartialEvaluator.buildFontPaths = function (font, glyphs, handler) {
function buildPath(fontChar) {
if (font.renderer.hasBuiltPath(fontChar)) {
return;
@ -3261,7 +3262,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
// TODO: Change this to a `static` getter, using shadowing, once
// `PartialEvaluator` is converted to a proper class.
PartialEvaluator.getFallbackFontDict = function() {
PartialEvaluator.getFallbackFontDict = function () {
if (this._fallbackFontDict) {
return this._fallbackFontDict;
}
@ -3346,7 +3347,7 @@ class TranslatedFont {
for (var i = 0, n = charProcKeys.length; i < n; ++i) {
const key = charProcKeys[i];
loadCharProcsPromise = loadCharProcsPromise.then(function() {
loadCharProcsPromise = loadCharProcsPromise.then(function () {
var glyphStream = charProcs.get(key);
var operatorList = new OperatorList();
return type3Evaluator
@ -3356,21 +3357,21 @@ class TranslatedFont {
resources: fontResources,
operatorList,
})
.then(function() {
.then(function () {
charProcOperatorList[key] = operatorList.getIR();
// Add the dependencies to the parent operator list so they are
// resolved before sub operator list is executed synchronously.
parentOperatorList.addDependencies(operatorList.dependencies);
})
.catch(function(reason) {
.catch(function (reason) {
warn(`Type3 font resource "${key}" is not available.`);
const dummyOperatorList = new OperatorList();
charProcOperatorList[key] = dummyOperatorList.getIR();
});
});
}
this.type3Loaded = loadCharProcsPromise.then(function() {
this.type3Loaded = loadCharProcsPromise.then(function () {
translatedFont.charProcOperatorList = charProcOperatorList;
});
return this.type3Loaded;
@ -3530,7 +3531,7 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
//
// If variableArgs === true: [0, `numArgs`] expected
// If variableArgs === false: exactly `numArgs` expected
var getOPMap = getLookupTableFactory(function(t) {
var getOPMap = getLookupTableFactory(function (t) {
// Graphic state
t["w"] = { id: OPS.setLineWidth, numArgs: 1, variableArgs: false };
t["J"] = { id: OPS.setLineCap, numArgs: 1, variableArgs: false };

View File

@ -283,7 +283,7 @@ var Glyph = (function GlyphClosure() {
this.isInFont = isInFont;
}
Glyph.prototype.matchesForCache = function(
Glyph.prototype.matchesForCache = function (
fontChar,
unicode,
accent,
@ -694,7 +694,7 @@ var Font = (function FontClosure() {
this.seacMap = properties.seacMap;
}
Font.getFontID = (function() {
Font.getFontID = (function () {
var ID = 1;
return function Font_getFontID() {
return String(ID++);
@ -1367,7 +1367,7 @@ var Font = (function FontClosure() {
var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
if (!isIdentityUnicode) {
this.toUnicode.forEach(function(charCode, unicodeCharCode) {
this.toUnicode.forEach(function (charCode, unicodeCharCode) {
map[+charCode] = unicodeCharCode;
});
}
@ -1775,7 +1775,7 @@ var Font = (function FontClosure() {
}
// removing duplicate entries
mappings.sort(function(a, b) {
mappings.sort(function (a, b) {
return a.charCode - b.charCode;
});
for (i = 1; i < mappings.length; i++) {
@ -2764,7 +2764,7 @@ var Font = (function FontClosure() {
var cidToGidMap = properties.cidToGidMap || [];
var isCidToGidMapEmpty = cidToGidMap.length === 0;
properties.cMap.forEach(function(charCode, cid) {
properties.cMap.forEach(function (charCode, cid) {
if (cid > 0xffff) {
throw new FormatError("Max size of CID is 65,535");
}

View File

@ -159,7 +159,7 @@ var PDFFunction = (function PDFFunctionClosure() {
this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) })
);
}
return function(src, srcOffset, dest, destOffset) {
return function (src, srcOffset, dest, destOffset) {
for (var i = 0, ii = fnArray.length; i < ii; i++) {
fnArray[i](src, srcOffset, dest, destOffset + i);
}
@ -873,7 +873,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
function AstNode(type) {
this.type = type;
}
AstNode.prototype.visit = function(visitor) {
AstNode.prototype.visit = function (visitor) {
unreachable("abstract method");
};
@ -884,7 +884,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max;
}
AstArgument.prototype = Object.create(AstNode.prototype);
AstArgument.prototype.visit = function(visitor) {
AstArgument.prototype.visit = function (visitor) {
visitor.visitArgument(this);
};
@ -895,7 +895,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = number;
}
AstLiteral.prototype = Object.create(AstNode.prototype);
AstLiteral.prototype.visit = function(visitor) {
AstLiteral.prototype.visit = function (visitor) {
visitor.visitLiteral(this);
};
@ -908,7 +908,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max;
}
AstBinaryOperation.prototype = Object.create(AstNode.prototype);
AstBinaryOperation.prototype.visit = function(visitor) {
AstBinaryOperation.prototype.visit = function (visitor) {
visitor.visitBinaryOperation(this);
};
@ -919,7 +919,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max;
}
AstMin.prototype = Object.create(AstNode.prototype);
AstMin.prototype.visit = function(visitor) {
AstMin.prototype.visit = function (visitor) {
visitor.visitMin(this);
};
@ -930,7 +930,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.max = max;
}
AstVariable.prototype = Object.create(AstNode.prototype);
AstVariable.prototype.visit = function(visitor) {
AstVariable.prototype.visit = function (visitor) {
visitor.visitVariable(this);
};
@ -940,7 +940,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
this.arg = arg;
}
AstVariableDefinition.prototype = Object.create(AstNode.prototype);
AstVariableDefinition.prototype.visit = function(visitor) {
AstVariableDefinition.prototype.visit = function (visitor) {
visitor.visitVariableDefinition(this);
};
@ -1245,12 +1245,12 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() {
}
var result = [];
instructions.forEach(function(instruction) {
instructions.forEach(function (instruction) {
var statementBuilder = new ExpressionBuilderVisitor();
instruction.visit(statementBuilder);
result.push(statementBuilder.toString());
});
stack.forEach(function(expr, i) {
stack.forEach(function (expr, i) {
var statementBuilder = new ExpressionBuilderVisitor();
expr.visit(statementBuilder);
var min = range[i * 2],

View File

@ -16,7 +16,7 @@
var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory;
var getGlyphsUnicode = getLookupTableFactory(function(t) {
var getGlyphsUnicode = getLookupTableFactory(function (t) {
t["A"] = 0x0041;
t["AE"] = 0x00c6;
t["AEacute"] = 0x01fc;
@ -4343,7 +4343,7 @@ var getGlyphsUnicode = getLookupTableFactory(function(t) {
t["vextendsingle"] = 0x2223;
});
var getDingbatsGlyphsUnicode = getLookupTableFactory(function(t) {
var getDingbatsGlyphsUnicode = getLookupTableFactory(function (t) {
t["space"] = 0x0020;
t["a1"] = 0x2701;
t["a2"] = 0x2702;

View File

@ -265,7 +265,7 @@ var PDFImage = (function PDFImageClosure() {
* Handles processing of image data and returns the Promise that is resolved
* with a PDFImage when the image is ready to be used.
*/
PDFImage.buildImage = function({
PDFImage.buildImage = function ({
handler,
xref,
res,
@ -300,7 +300,7 @@ var PDFImage = (function PDFImageClosure() {
}
}
return Promise.all([imagePromise, smaskPromise, maskPromise]).then(
function([imageData, smaskData, maskData]) {
function ([imageData, smaskData, maskData]) {
return new PDFImage({
xref,
res,
@ -314,7 +314,7 @@ var PDFImage = (function PDFImageClosure() {
);
};
PDFImage.createMask = function({
PDFImage.createMask = function ({
imgArray,
width,
height,

View File

@ -62,7 +62,7 @@ class NativeImageDecoder {
image.getIR(this.forceDataSchema),
colorSpace.numComps,
])
.then(function({ data, width, height }) {
.then(function ({ data, width, height }) {
return new Stream(data, 0, data.length, dict);
});
}

View File

@ -371,7 +371,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {
// Sorting is non-standard, and it is not required. But sorting increases
// the number of template bits that can be reused from the previous
// contextLabel in the main loop.
template.sort(function(a, b) {
template.sort(function (a, b) {
return a.y - b.y || a.x - b.x;
});

View File

@ -43,12 +43,12 @@ const Jbig2Stream = (function Jbig2StreamClosure() {
configurable: true,
});
Jbig2Stream.prototype.ensureBuffer = function(requested) {
Jbig2Stream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`.
};
Jbig2Stream.prototype.readBlock = function() {
Jbig2Stream.prototype.readBlock = function () {
if (this.eof) {
return;
}

View File

@ -56,12 +56,12 @@ const JpegStream = (function JpegStreamClosure() {
configurable: true,
});
JpegStream.prototype.ensureBuffer = function(requested) {
JpegStream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`.
};
JpegStream.prototype.readBlock = function() {
JpegStream.prototype.readBlock = function () {
if (this.eof) {
return;
}
@ -250,7 +250,7 @@ const JpegStream = (function JpegStreamClosure() {
configurable: true,
});
JpegStream.prototype.getIR = function(forceDataSchema = false) {
JpegStream.prototype.getIR = function (forceDataSchema = false) {
return createObjectURL(this.bytes, "image/jpeg", forceDataSchema);
};

View File

@ -42,12 +42,12 @@ const JpxStream = (function JpxStreamClosure() {
configurable: true,
});
JpxStream.prototype.ensureBuffer = function(requested) {
JpxStream.prototype.ensureBuffer = function (requested) {
// No-op, since `this.readBlock` will always parse the entire image and
// directly insert all of its data into `this.buffer`.
};
JpxStream.prototype.readBlock = function() {
JpxStream.prototype.readBlock = function () {
if (this.eof) {
return;
}

View File

@ -18,13 +18,13 @@ import { getLookupTableFactory } from "./core_utils.js";
// The Metrics object contains glyph widths (in glyph space units).
// As per PDF spec, for most fonts (Type 3 being an exception) a glyph
// space unit corresponds to 1/1000th of text space unit.
var getMetrics = getLookupTableFactory(function(t) {
var getMetrics = getLookupTableFactory(function (t) {
t["Courier"] = 600;
t["Courier-Bold"] = 600;
t["Courier-BoldOblique"] = 600;
t["Courier-Oblique"] = 600;
// eslint-disable-next-line no-shadow
t["Helvetica"] = getLookupTableFactory(function(t) {
t["Helvetica"] = getLookupTableFactory(function (t) {
t["space"] = 278;
t["exclam"] = 278;
t["quotedbl"] = 355;
@ -342,7 +342,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556;
});
// eslint-disable-next-line no-shadow
t["Helvetica-Bold"] = getLookupTableFactory(function(t) {
t["Helvetica-Bold"] = getLookupTableFactory(function (t) {
t["space"] = 278;
t["exclam"] = 333;
t["quotedbl"] = 474;
@ -660,7 +660,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556;
});
// eslint-disable-next-line no-shadow
t["Helvetica-BoldOblique"] = getLookupTableFactory(function(t) {
t["Helvetica-BoldOblique"] = getLookupTableFactory(function (t) {
t["space"] = 278;
t["exclam"] = 333;
t["quotedbl"] = 474;
@ -978,7 +978,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556;
});
// eslint-disable-next-line no-shadow
t["Helvetica-Oblique"] = getLookupTableFactory(function(t) {
t["Helvetica-Oblique"] = getLookupTableFactory(function (t) {
t["space"] = 278;
t["exclam"] = 278;
t["quotedbl"] = 355;
@ -1296,7 +1296,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 556;
});
// eslint-disable-next-line no-shadow
t["Symbol"] = getLookupTableFactory(function(t) {
t["Symbol"] = getLookupTableFactory(function (t) {
t["space"] = 250;
t["exclam"] = 333;
t["universal"] = 713;
@ -1489,7 +1489,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["apple"] = 790;
});
// eslint-disable-next-line no-shadow
t["Times-Roman"] = getLookupTableFactory(function(t) {
t["Times-Roman"] = getLookupTableFactory(function (t) {
t["space"] = 250;
t["exclam"] = 333;
t["quotedbl"] = 408;
@ -1807,7 +1807,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500;
});
// eslint-disable-next-line no-shadow
t["Times-Bold"] = getLookupTableFactory(function(t) {
t["Times-Bold"] = getLookupTableFactory(function (t) {
t["space"] = 250;
t["exclam"] = 333;
t["quotedbl"] = 555;
@ -2125,7 +2125,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500;
});
// eslint-disable-next-line no-shadow
t["Times-BoldItalic"] = getLookupTableFactory(function(t) {
t["Times-BoldItalic"] = getLookupTableFactory(function (t) {
t["space"] = 250;
t["exclam"] = 389;
t["quotedbl"] = 555;
@ -2443,7 +2443,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500;
});
// eslint-disable-next-line no-shadow
t["Times-Italic"] = getLookupTableFactory(function(t) {
t["Times-Italic"] = getLookupTableFactory(function (t) {
t["space"] = 250;
t["exclam"] = 333;
t["quotedbl"] = 420;
@ -2761,7 +2761,7 @@ var getMetrics = getLookupTableFactory(function(t) {
t["Euro"] = 500;
});
// eslint-disable-next-line no-shadow
t["ZapfDingbats"] = getLookupTableFactory(function(t) {
t["ZapfDingbats"] = getLookupTableFactory(function (t) {
t["space"] = 278;
t["a1"] = 974;
t["a2"] = 961;

View File

@ -271,7 +271,7 @@ class Catalog {
dests[name] = fetchDestination(names[name]);
}
} else if (obj instanceof Dict) {
obj.forEach(function(key, value) {
obj.forEach(function (key, value) {
if (value) {
dests[key] = fetchDestination(value);
}
@ -693,7 +693,7 @@ class Catalog {
fontFallback(id, handler) {
const promises = [];
this.fontCache.forEach(function(promise) {
this.fontCache.forEach(function (promise) {
promises.push(promise);
});
@ -712,7 +712,7 @@ class Catalog {
this.pageKidsCountCache.clear();
const promises = [];
this.fontCache.forEach(function(promise) {
this.fontCache.forEach(function (promise) {
promises.push(promise);
});
@ -754,7 +754,7 @@ class Catalog {
}
visitedNodes.put(currentNode);
xref.fetchAsync(currentNode).then(function(obj) {
xref.fetchAsync(currentNode).then(function (obj) {
if (isDict(obj, "Page") || (isDict(obj) && !obj.has("Kids"))) {
if (pageIndex === currentPageIndex) {
// Cache the Page reference, since it can *greatly* improve
@ -849,7 +849,7 @@ class Catalog {
return xref
.fetchAsync(kidRef)
.then(function(node) {
.then(function (node) {
if (
isRefsEqual(kidRef, pageRef) &&
!isDict(node, "Page") &&
@ -868,7 +868,7 @@ class Catalog {
parentRef = node.getRaw("Parent");
return node.getAsync("Parent");
})
.then(function(parent) {
.then(function (parent) {
if (!parent) {
return null;
}
@ -877,7 +877,7 @@ class Catalog {
}
return parent.getAsync("Kids");
})
.then(function(kids) {
.then(function (kids) {
if (!kids) {
return null;
}
@ -894,7 +894,7 @@ class Catalog {
break;
}
kidPromises.push(
xref.fetchAsync(kid).then(function(obj) {
xref.fetchAsync(kid).then(function (obj) {
if (!isDict(obj)) {
throw new FormatError("Kid node must be a dictionary.");
}
@ -910,7 +910,7 @@ class Catalog {
if (!found) {
throw new FormatError("Kid reference not found in parent's kids.");
}
return Promise.all(kidPromises).then(function() {
return Promise.all(kidPromises).then(function () {
return [total, parentRef];
});
});
@ -918,7 +918,7 @@ class Catalog {
let total = 0;
function next(ref) {
return pagesBeforeRef(ref).then(function(args) {
return pagesBeforeRef(ref).then(function (args) {
if (!args) {
return total;
}
@ -1069,9 +1069,7 @@ class Catalog {
const URL_OPEN_METHODS = ["app.launchURL", "window.open"];
const regex = new RegExp(
"^\\s*(" +
URL_OPEN_METHODS.join("|")
.split(".")
.join("\\.") +
URL_OPEN_METHODS.join("|").split(".").join("\\.") +
")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))",
"i"
);
@ -2186,7 +2184,7 @@ var FileSpec = (function FileSpecClosure() {
* that have references to the catalog or other pages since that will cause the
* entire PDF document object graph to be traversed.
*/
const ObjectLoader = (function() {
const ObjectLoader = (function () {
function mayHaveChildren(value) {
return (
value instanceof Ref ||

View File

@ -304,7 +304,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
addState(
InitialState,
[OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
function(context) {
function (context) {
var argsArray = context.argsArray;
var iFirstTransform = context.iCurr - 2;
return (
@ -351,7 +351,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
}
throw new Error(`iterateImageGroup - invalid pos: ${pos}`);
},
function(context, i) {
function (context, i) {
var MIN_IMAGES_IN_BLOCK = 3;
var MAX_IMAGES_IN_BLOCK = 1000;
@ -436,7 +436,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() {
}
throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`);
},
function(context, i) {
function (context, i) {
var MIN_CHARS_IN_BLOCK = 3;
var MAX_CHARS_IN_BLOCK = 1000;

View File

@ -51,7 +51,7 @@ var Pattern = (function PatternClosure() {
},
};
Pattern.parseShading = function(
Pattern.parseShading = function (
shading,
matrix,
xref,

View File

@ -34,7 +34,7 @@ var Name = (function NameClosure() {
return nameValue ? nameValue : (nameCache[name] = new Name(name));
};
Name._clearCache = function() {
Name._clearCache = function () {
nameCache = Object.create(null);
};
@ -57,7 +57,7 @@ var Cmd = (function CmdClosure() {
return cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd));
};
Cmd._clearCache = function() {
Cmd._clearCache = function () {
cmdCache = Object.create(null);
};
@ -164,7 +164,7 @@ var Dict = (function DictClosure() {
Dict.empty = new Dict(null);
Dict.merge = function(xref, dictArray) {
Dict.merge = function (xref, dictArray) {
const mergedDict = new Dict(xref);
for (let i = 0, ii = dictArray.length; i < ii; i++) {
@ -205,14 +205,14 @@ var Ref = (function RefClosure() {
},
};
Ref.get = function(num, gen) {
Ref.get = function (num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
const refValue = refCache[key];
// eslint-disable-next-line no-restricted-syntax
return refValue ? refValue : (refCache[key] = new Ref(num, gen));
};
Ref._clearCache = function() {
Ref._clearCache = function () {
refCache = Object.create(null);
};

View File

@ -20,7 +20,7 @@ import { getLookupTableFactory } from "./core_utils.js";
* Hold a map of decoded fonts and of the standard fourteen Type1
* fonts and their acronyms.
*/
const getStdFontMap = getLookupTableFactory(function(t) {
const getStdFontMap = getLookupTableFactory(function (t) {
t["ArialNarrow"] = "Helvetica";
t["ArialNarrow-Bold"] = "Helvetica-Bold";
t["ArialNarrow-BoldItalic"] = "Helvetica-BoldOblique";
@ -82,7 +82,7 @@ const getStdFontMap = getLookupTableFactory(function(t) {
* Holds the map of the non-standard fonts that might be included as
* a standard fonts without glyph data.
*/
const getNonStdFontMap = getLookupTableFactory(function(t) {
const getNonStdFontMap = getLookupTableFactory(function (t) {
t["Calibri"] = "Helvetica";
t["Calibri-Bold"] = "Helvetica-Bold";
t["Calibri-BoldItalic"] = "Helvetica-BoldOblique";
@ -122,7 +122,7 @@ const getNonStdFontMap = getLookupTableFactory(function(t) {
t["Wingdings-Regular"] = "ZapfDingbats";
});
const getSerifFonts = getLookupTableFactory(function(t) {
const getSerifFonts = getLookupTableFactory(function (t) {
t["Adobe Jenson"] = true;
t["Adobe Text"] = true;
t["Albertus"] = true;
@ -258,7 +258,7 @@ const getSerifFonts = getLookupTableFactory(function(t) {
t["XITS"] = true;
});
const getSymbolsFonts = getLookupTableFactory(function(t) {
const getSymbolsFonts = getLookupTableFactory(function (t) {
t["Dingbats"] = true;
t["Symbol"] = true;
t["ZapfDingbats"] = true;
@ -267,7 +267,7 @@ const getSymbolsFonts = getLookupTableFactory(function(t) {
// Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID
// fonts, but does not embed the CID to GID mapping. The mapping is incomplete
// for all glyphs, but common for some set of the standard fonts.
const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) {
const getGlyphMapForStandardFonts = getLookupTableFactory(function (t) {
t[2] = 10;
t[3] = 32;
t[4] = 33;
@ -666,7 +666,9 @@ const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) {
// The glyph map for ArialBlack differs slightly from the glyph map used for
// other well-known standard fonts. Hence we use this (incomplete) CID to GID
// mapping to adjust the glyph map for non-embedded ArialBlack fonts.
const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) {
const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function (
t
) {
t[227] = 322;
t[264] = 261;
t[291] = 346;
@ -675,7 +677,7 @@ const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) {
// The glyph map for Calibri (a Windows font) differs from the glyph map used
// in the standard fonts. Hence we use this (incomplete) CID to GID mapping to
// adjust the glyph map for non-embedded Calibri fonts.
const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function(t) {
const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function (t) {
t[1] = 32;
t[4] = 65;
t[17] = 66;

View File

@ -19,7 +19,7 @@ var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory;
// Some characters, e.g. copyrightserif, are mapped to the private use area
// and might not be displayed using standard fonts. Mapping/hacking well-known
// chars to the similar equivalents in the normal characters range.
var getSpecialPUASymbols = getLookupTableFactory(function(t) {
var getSpecialPUASymbols = getLookupTableFactory(function (t) {
t[63721] = 0x00a9; // copyrightsans (0xF8E9) => copyright
t[63193] = 0x00a9; // copyrightserif (0xF6D9) => copyright
t[63720] = 0x00ae; // registersans (0xF8E8) => registered
@ -241,7 +241,7 @@ function isRTLRangeFor(value) {
// The normalization table is obtained by filtering the Unicode characters
// database with <compat> entries.
var getNormalizedUnicodes = getLookupTableFactory(function(t) {
var getNormalizedUnicodes = getLookupTableFactory(function (t) {
t["\u00A8"] = "\u0020\u0308";
t["\u00AF"] = "\u0020\u0304";
t["\u00B4"] = "\u0020\u0301";

View File

@ -230,7 +230,7 @@ var WorkerMessageHandler = {
var fullRequest = pdfStream.getFullReader();
fullRequest.headersReady
.then(function() {
.then(function () {
if (!fullRequest.isRangeSupported) {
return;
}
@ -262,13 +262,13 @@ var WorkerMessageHandler = {
pdfManagerCapability.resolve(newPdfManager);
cancelXHRs = null;
})
.catch(function(reason) {
.catch(function (reason) {
pdfManagerCapability.reject(reason);
cancelXHRs = null;
});
var loaded = 0;
var flushChunks = function() {
var flushChunks = function () {
var pdfFile = arraysToBytes(cachedChunks);
if (source.length && pdfFile.length !== source.length) {
warn("reported HTTP length is different from actual");
@ -288,8 +288,8 @@ var WorkerMessageHandler = {
}
cachedChunks = [];
};
var readPromise = new Promise(function(resolve, reject) {
var readChunk = function({ value, done }) {
var readPromise = new Promise(function (resolve, reject) {
var readChunk = function ({ value, done }) {
try {
ensureNotTerminated();
if (done) {
@ -321,12 +321,12 @@ var WorkerMessageHandler = {
};
fullRequest.read().then(readChunk, reject);
});
readPromise.catch(function(e) {
readPromise.catch(function (e) {
pdfManagerCapability.reject(e);
cancelXHRs = null;
});
cancelXHRs = function(reason) {
cancelXHRs = function (reason) {
pdfStream.cancelAllRequests(reason);
};
@ -348,12 +348,12 @@ var WorkerMessageHandler = {
handler
.sendWithPromise("PasswordRequest", ex)
.then(function({ password }) {
.then(function ({ password }) {
finishWorkerTask(task);
pdfManager.updatePassword(password);
pdfManagerReady();
})
.catch(function() {
.catch(function () {
finishWorkerTask(task);
handler.send("DocException", ex);
});
@ -386,7 +386,7 @@ var WorkerMessageHandler = {
return;
}
pdfManager.requestLoadedStream();
pdfManager.onLoadedStream().then(function() {
pdfManager.onLoadedStream().then(function () {
ensureNotTerminated();
loadDocument(true).then(onSuccess, onFailure);
@ -409,7 +409,7 @@ var WorkerMessageHandler = {
};
getPdfManager(data, evaluatorOptions)
.then(function(newPdfManager) {
.then(function (newPdfManager) {
if (terminated) {
// We were in a process of setting up the manager, but it got
// terminated in the middle.
@ -420,7 +420,7 @@ var WorkerMessageHandler = {
}
pdfManager = newPdfManager;
pdfManager.onLoadedStream().then(function(stream) {
pdfManager.onLoadedStream().then(function (stream) {
handler.send("DataLoaded", { length: stream.bytes.byteLength });
});
})
@ -428,13 +428,13 @@ var WorkerMessageHandler = {
}
handler.on("GetPage", function wphSetupGetPage(data) {
return pdfManager.getPage(data.pageIndex).then(function(page) {
return pdfManager.getPage(data.pageIndex).then(function (page) {
return Promise.all([
pdfManager.ensure(page, "rotate"),
pdfManager.ensure(page, "ref"),
pdfManager.ensure(page, "userUnit"),
pdfManager.ensure(page, "view"),
]).then(function([rotate, ref, userUnit, view]) {
]).then(function ([rotate, ref, userUnit, view]) {
return {
rotate,
ref,
@ -471,11 +471,11 @@ var WorkerMessageHandler = {
return pdfManager.ensureCatalog("pageMode");
});
handler.on("GetViewerPreferences", function(data) {
handler.on("GetViewerPreferences", function (data) {
return pdfManager.ensureCatalog("viewerPreferences");
});
handler.on("GetOpenAction", function(data) {
handler.on("GetOpenAction", function (data) {
return pdfManager.ensureCatalog("openAction");
});
@ -491,7 +491,7 @@ var WorkerMessageHandler = {
return pdfManager.ensureCatalog("documentOutline");
});
handler.on("GetPermissions", function(data) {
handler.on("GetPermissions", function (data) {
return pdfManager.ensureCatalog("permissions");
});
@ -504,7 +504,7 @@ var WorkerMessageHandler = {
handler.on("GetData", function wphSetupGetData(data) {
pdfManager.requestLoadedStream();
return pdfManager.onLoadedStream().then(function(stream) {
return pdfManager.onLoadedStream().then(function (stream) {
return stream.bytes;
});
});
@ -513,8 +513,8 @@ var WorkerMessageHandler = {
return pdfManager.pdfDocument.xref.stats;
});
handler.on("GetAnnotations", function({ pageIndex, intent }) {
return pdfManager.getPage(pageIndex).then(function(page) {
handler.on("GetAnnotations", function ({ pageIndex, intent }) {
return pdfManager.getPage(pageIndex).then(function (page) {
return page.getAnnotationsData(intent);
});
});
@ -523,7 +523,7 @@ var WorkerMessageHandler = {
"GetOperatorList",
function wphSetupRenderPage(data, sink) {
var pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function(page) {
pdfManager.getPage(pageIndex).then(function (page) {
var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
startWorkerTask(task);
@ -540,7 +540,7 @@ var WorkerMessageHandler = {
renderInteractiveForms: data.renderInteractiveForms,
})
.then(
function(operatorListInfo) {
function (operatorListInfo) {
finishWorkerTask(task);
if (start) {
@ -551,7 +551,7 @@ var WorkerMessageHandler = {
}
sink.close();
},
function(reason) {
function (reason) {
finishWorkerTask(task);
if (task.terminated) {
return; // ignoring errors from the terminated thread
@ -576,10 +576,10 @@ var WorkerMessageHandler = {
handler.on("GetTextContent", function wphExtractText(data, sink) {
var pageIndex = data.pageIndex;
sink.onPull = function(desiredSize) {};
sink.onCancel = function(reason) {};
sink.onPull = function (desiredSize) {};
sink.onCancel = function (reason) {};
pdfManager.getPage(pageIndex).then(function(page) {
pdfManager.getPage(pageIndex).then(function (page) {
var task = new WorkerTask("GetTextContent: page " + pageIndex);
startWorkerTask(task);
@ -595,7 +595,7 @@ var WorkerMessageHandler = {
combineTextItems: data.combineTextItems,
})
.then(
function() {
function () {
finishWorkerTask(task);
if (start) {
@ -606,7 +606,7 @@ var WorkerMessageHandler = {
}
sink.close();
},
function(reason) {
function (reason) {
finishWorkerTask(task);
if (task.terminated) {
return; // ignoring errors from the terminated thread
@ -620,7 +620,7 @@ var WorkerMessageHandler = {
});
});
handler.on("FontFallback", function(data) {
handler.on("FontFallback", function (data) {
return pdfManager.fontFallback(data.id, handler);
});
@ -646,12 +646,12 @@ var WorkerMessageHandler = {
cancelXHRs(new AbortException("Worker was terminated."));
}
WorkerTasks.forEach(function(task) {
WorkerTasks.forEach(function (task) {
waitOn.push(task.finished);
task.terminate();
});
return Promise.all(waitOn).then(function() {
return Promise.all(waitOn).then(function () {
// Notice that even if we destroying handler, resolved response promise
// must be sent back.
handler.destroy();

View File

@ -42,7 +42,7 @@ class PDFWorkerStream {
this._fullRequestReader.cancel(reason);
}
const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) {
readers.forEach(function (reader) {
reader.cancel(reason);
});
}

View File

@ -309,12 +309,12 @@ function getDocument(src) {
}
const docId = task.docId;
worker.promise
.then(function() {
.then(function () {
if (task.destroyed) {
throw new Error("Loading aborted");
}
return _fetchDocument(worker, params, rangeTransport, docId).then(
function(workerId) {
function (workerId) {
if (task.destroyed) {
throw new Error("Loading aborted");
}
@ -411,7 +411,7 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
isEvalSupported: source.isEvalSupported,
fontExtraProperties: source.fontExtraProperties,
})
.then(function(workerId) {
.then(function (workerId) {
if (worker.destroyed) {
throw new Error("Worker was destroyed");
}
@ -679,7 +679,7 @@ class PDFDocumentProxy {
getOpenActionDestination() {
deprecated("getOpenActionDestination, use getOpenAction instead.");
return this.getOpenAction().then(function(openAction) {
return this.getOpenAction().then(function (openAction) {
return openAction && openAction.dest ? openAction.dest : null;
});
}
@ -1214,9 +1214,9 @@ class PDFPageProxy {
getTextContent(params = {}) {
const readableStream = this.streamTextContent(params);
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
function pump() {
reader.read().then(function({ value, done }) {
reader.read().then(function ({ value, done }) {
if (done) {
resolve(textContent);
return;
@ -1257,9 +1257,9 @@ class PDFPageProxy {
// Avoid errors below, since the renderTasks are just stubs.
return;
}
intentState.renderTasks.forEach(function(renderTask) {
intentState.renderTasks.forEach(function (renderTask) {
const renderCompleted = renderTask.capability.promise.catch(
function() {}
function () {}
); // ignoring failures
waitOn.push(renderCompleted);
renderTask.cancel();
@ -1629,7 +1629,7 @@ const PDFWorker = (function PDFWorkerClosure() {
}
fakeWorkerCapability = createPromiseCapability();
const loader = async function() {
const loader = async function () {
const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
if (mainWorkerMessageHandler) {
@ -1734,7 +1734,7 @@ const PDFWorker = (function PDFWorkerClosure() {
_initializeFromPort(port) {
this._port = port;
this._messageHandler = new MessageHandler("main", "worker", port);
this._messageHandler.on("ready", function() {
this._messageHandler.on("ready", function () {
// Ignoring 'ready' event -- MessageHandler shall be already initialized
// and ready to accept the messages.
});
@ -1991,7 +1991,7 @@ class WorkerTransport {
const waitOn = [];
// We need to wait for all renderings to be completed, e.g.
// timeout/rAF can take a long time.
this.pageCache.forEach(function(page) {
this.pageCache.forEach(function (page) {
if (page) {
waitOn.push(page._destroy());
}
@ -2033,7 +2033,7 @@ class WorkerTransport {
sink.onPull = () => {
this._fullReader
.read()
.then(function({ value, done }) {
.then(function ({ value, done }) {
if (done) {
sink.close();
return;
@ -2108,7 +2108,7 @@ class WorkerTransport {
sink.onPull = () => {
rangeReader
.read()
.then(function({ value, done }) {
.then(function ({ value, done }) {
if (done) {
sink.close();
return;
@ -2131,7 +2131,7 @@ class WorkerTransport {
loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
});
messageHandler.on("DocException", function(ex) {
messageHandler.on("DocException", function (ex) {
let reason;
switch (ex.name) {
case "PasswordException":
@ -2283,10 +2283,10 @@ class WorkerTransport {
case "JpegStream":
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function() {
img.onload = function () {
resolve(img);
};
img.onerror = function() {
img.onerror = function () {
// Note that when the browser image loading/decoding fails,
// we'll fallback to the built-in PDF.js JPEG decoder; see
// `PartialEvaluator.buildPaintImageXObject` in the
@ -2354,9 +2354,9 @@ class WorkerTransport {
);
}
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
const img = new Image();
img.onload = function() {
img.onload = function () {
const { width, height } = img;
const size = width * height;
const rgbaLength = size * 4;
@ -2390,7 +2390,7 @@ class WorkerTransport {
tmpCanvas = null;
tmpCtx = null;
};
img.onerror = function() {
img.onerror = function () {
reject(new Error("JpegDecode failed to load image"));
// Always remember to release the image data if errors occurred.
@ -2415,10 +2415,10 @@ class WorkerTransport {
fetched = true;
this.CMapReaderFactory.fetch(data)
.then(function(builtInCMap) {
.then(function (builtInCMap) {
sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]);
})
.catch(function(reason) {
.catch(function (reason) {
sink.error(reason);
});
};
@ -2477,7 +2477,7 @@ class WorkerTransport {
.sendWithPromise("GetPageIndex", {
ref,
})
.catch(function(reason) {
.catch(function (reason) {
return Promise.reject(new Error(reason));
});
}
@ -2856,9 +2856,7 @@ const InternalRenderTask = (function InternalRenderTaskClosure() {
this._nextBound().catch(this.cancel.bind(this));
});
} else {
Promise.resolve()
.then(this._nextBound)
.catch(this.cancel.bind(this));
Promise.resolve().then(this._nextBound).catch(this.cancel.bind(this));
}
}

View File

@ -362,7 +362,7 @@ function compileType3Glyph(imgData) {
--i;
}
var drawOutline = function(c) {
var drawOutline = function (c) {
c.save();
// the path shall be painted in [0..1]x[0..1] space
c.scale(1 / width, -1 / height);

View File

@ -85,7 +85,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
}
try {
const decoder = new TextDecoder(encoding, { fatal: true });
const bytes = Array.from(value, function(ch) {
const bytes = Array.from(value, function (ch) {
return ch.charCodeAt(0) & 0xff;
});
value = decoder.decode(new Uint8Array(bytes));
@ -205,11 +205,11 @@ function getFilenameFromContentDispositionHeader(contentDisposition) {
// ... but Firefox permits ? and space.
return value.replace(
/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,
function(matches, charset, encoding, text) {
function (matches, charset, encoding, text) {
if (encoding === "q" || encoding === "Q") {
// RFC 2047 section 4.2.
text = text.replace(/_/g, " ");
text = text.replace(/=([0-9a-fA-F]{2})/g, function(match, hex) {
text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
return String.fromCharCode(parseInt(hex, 16));
});
return textdecode(charset, text);

View File

@ -502,7 +502,7 @@ function loadScript(src) {
script.src = src;
script.onload = resolve;
script.onerror = function() {
script.onerror = function () {
reject(new Error(`Cannot load script at: ${script.src}`));
};
(document.head || document.documentElement).appendChild(script);

View File

@ -84,7 +84,7 @@ class PDFFetchStream {
this._fullRequestReader.cancel(reason);
}
const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) {
readers.forEach(function (reader) {
reader.cancel(reason);
});
}

View File

@ -56,7 +56,7 @@ class BaseFontLoader {
}
clear() {
this.nativeFontFaces.forEach(function(nativeFontFace) {
this.nativeFontFaces.forEach(function (nativeFontFace) {
document.fonts.delete(nativeFontFace);
});
this.nativeFontFaces.length = 0;
@ -198,7 +198,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
}
get _loadTestFont() {
const getLoadTestFont = function() {
const getLoadTestFont = function () {
// This is a CFF font with 1 glyph for '.' that fills its entire width
// and height.
return atob(
@ -328,7 +328,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
}
document.body.appendChild(div);
isFontReady(loadTestFontId, function() {
isFontReady(loadTestFontId, function () {
document.body.removeChild(div);
request.complete();
});
@ -404,7 +404,7 @@ class FontFaceObject {
}
warn(`getPathGenerator - ignoring character: "${ex}".`);
return (this.compiledGlyphs[character] = function(c, size) {
return (this.compiledGlyphs[character] = function (c, size) {
// No-op function, to allow rendering to continue.
});
}
@ -428,7 +428,7 @@ class FontFaceObject {
}
// ... but fall back on using Function.prototype.apply() if we're
// blocked from using eval() for whatever reason (like CSP policies).
return (this.compiledGlyphs[character] = function(c, size) {
return (this.compiledGlyphs[character] = function (c, size) {
for (let i = 0, ii = cmds.length; i < ii; i++) {
current = cmds[i];

View File

@ -38,12 +38,12 @@ class Metadata {
// Start by removing any "junk" before the first tag (see issue 10395).
return data
.replace(/^[^<]+/, "")
.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
const bytes = codes
.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) {
.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
})
.replace(/&(amp|apos|gt|lt|quot);/g, function(str, name) {
.replace(/&(amp|apos|gt|lt|quot);/g, function (str, name) {
switch (name) {
case "amp":
return "&";

View File

@ -100,7 +100,7 @@ class NetworkManager {
xhr.responseType = "arraybuffer";
if (args.onError) {
xhr.onerror = function(evt) {
xhr.onerror = function (evt) {
args.onError(xhr.status);
};
}
@ -271,7 +271,7 @@ class PDFNetworkStream {
this._fullRequestReader.cancel(reason);
}
const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) {
readers.forEach(function (reader) {
reader.cancel(reason);
});
}
@ -359,7 +359,7 @@ class PDFNetworkStreamFullRequestReader {
if (this._cachedChunks.length > 0) {
return;
}
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];
@ -370,7 +370,7 @@ class PDFNetworkStreamFullRequestReader {
const exception = createResponseStatusError(status, url);
this._storedError = exception;
this._headersReceivedCapability.reject(exception);
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.reject(exception);
});
this._requests = [];
@ -425,7 +425,7 @@ class PDFNetworkStreamFullRequestReader {
cancel(reason) {
this._done = true;
this._headersReceivedCapability.reject(reason);
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];
@ -468,7 +468,7 @@ class PDFNetworkStreamRangeRequestReader {
this._queuedChunk = chunk;
}
this._done = true;
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];
@ -503,7 +503,7 @@ class PDFNetworkStreamRangeRequestReader {
cancel(reason) {
this._done = true;
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];

View File

@ -91,7 +91,7 @@ class PDFNodeStream {
}
const readers = this._rangeRequestReaders.slice(0);
readers.forEach(function(reader) {
readers.forEach(function (reader) {
reader.cancel(reason);
});
}

View File

@ -29,7 +29,7 @@ import {
import { DOMSVGFactory } from "./display_utils.js";
import { isNodeJS } from "../shared/is_node.js";
let SVGGraphics = function() {
let SVGGraphics = function () {
throw new Error("Not implemented: SVGGraphics");
};
@ -44,7 +44,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
const LINE_CAP_STYLES = ["butt", "round", "square"];
const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
const convertImgDataToPng = (function() {
const convertImgDataToPng = (function () {
const PNG_HEADER = new Uint8Array([
0x89,
0x50,
@ -1327,7 +1327,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
// The previous clipping group content can go out of order -- resetting
// cached clipGroups.
current.clipGroup = null;
this.extraStack.forEach(function(prev) {
this.extraStack.forEach(function (prev) {
prev.clipGroup = null;
});
// Intersect with the previous clipping path.
@ -1439,7 +1439,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
const current = this.current;
let dashArray = current.dashArray;
if (lineWidthScale !== 1 && dashArray.length > 0) {
dashArray = dashArray.map(function(value) {
dashArray = dashArray.map(function (value) {
return lineWidthScale * value;
});
}

View File

@ -234,7 +234,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
// Finding intersections with expanded box.
var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
var ts = new Float64Array(64);
points.forEach(function(p, j) {
points.forEach(function (p, j) {
var t = Util.applyTransform(p, m);
ts[j + 0] = c && (e.left - t[0]) / c;
ts[j + 4] = s && (e.top - t[1]) / s;
@ -268,7 +268,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
}
function expandBounds(width, height, boxes) {
var bounds = boxes.map(function(box, i) {
var bounds = boxes.map(function (box, i) {
return {
x1: box.left,
y1: box.top,
@ -281,7 +281,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
});
expandBoundsLTR(width, bounds);
var expanded = new Array(boxes.length);
bounds.forEach(function(b) {
bounds.forEach(function (b) {
var i = b.index;
expanded[i] = {
left: b.x1New,
@ -293,7 +293,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
// Rotating on 90 degrees and extending extended boxes. Reusing the bounds
// array and objects.
boxes.map(function(box, i) {
boxes.map(function (box, i) {
var e = expanded[i],
b = bounds[i];
b.x1 = box.top;
@ -306,7 +306,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
});
expandBoundsLTR(height, bounds);
bounds.forEach(function(b) {
bounds.forEach(function (b) {
var i = b.index;
expanded[i].top = b.x1New;
expanded[i].bottom = b.x2New;
@ -316,7 +316,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
function expandBoundsLTR(width, bounds) {
// Sorting by x1 coordinate and walk by the bounds in the same order.
bounds.sort(function(a, b) {
bounds.sort(function (a, b) {
return a.x1 - b.x1 || a.index - b.index;
});
@ -338,7 +338,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
},
];
bounds.forEach(function(boundary) {
bounds.forEach(function (boundary) {
// Searching for the affected part of horizon.
// TODO red-black tree or simple binary search
var i = 0;
@ -480,7 +480,7 @@ var renderTextLayer = (function renderTextLayerClosure() {
});
// Set new x2 for all unset boundaries.
horizon.forEach(function(horizonPart) {
horizon.forEach(function (horizonPart) {
var affectedBoundary = horizonPart.boundary;
if (affectedBoundary.x2New === undefined) {
affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);

View File

@ -66,7 +66,7 @@ class PDFDataTransportStream {
this._queuedChunks.push(buffer);
}
} else {
const found = this._rangeReaders.some(function(rangeReader) {
const found = this._rangeReaders.some(function (rangeReader) {
if (rangeReader._begin !== args.begin) {
return false;
}
@ -136,7 +136,7 @@ class PDFDataTransportStream {
this._fullRequestReader.cancel(reason);
}
const readers = this._rangeReaders.slice(0);
readers.forEach(function(rangeReader) {
readers.forEach(function (rangeReader) {
rangeReader.cancel(reason);
});
this._pdfDataRangeTransport.abort();
@ -209,7 +209,7 @@ class PDFDataTransportStreamReader {
cancel(reason) {
this._done = true;
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];
@ -245,7 +245,7 @@ class PDFDataTransportStreamRangeReader {
} else {
const requestsCapability = this._requests.shift();
requestsCapability.resolve({ value: chunk, done: false });
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];
@ -274,7 +274,7 @@ class PDFDataTransportStreamRangeReader {
cancel(reason) {
this._done = true;
this._requests.forEach(function(requestCapability) {
this._requests.forEach(function (requestCapability) {
requestCapability.resolve({ value: undefined, done: true });
});
this._requests = [];

View File

@ -317,7 +317,7 @@ class SimpleDOMNode {
return this.nodeValue || "";
}
return this.childNodes
.map(function(child) {
.map(function (child) {
return child.textContent;
})
.join("");

View File

@ -56,7 +56,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
} else if (PDFJSDev.test("CHROME")) {
const PDFNetworkStream = require("./display/network.js").PDFNetworkStream;
let PDFFetchStream;
const isChromeWithFetchCredentials = function() {
const isChromeWithFetchCredentials = function () {
// fetch does not include credentials until Chrome 61.0.3138.0 and later.
// https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707
try {

View File

@ -39,7 +39,7 @@ if (
if (globalThis.btoa || !isNodeJS) {
return;
}
globalThis.btoa = function(chars) {
globalThis.btoa = function (chars) {
// eslint-disable-next-line no-undef
return Buffer.from(chars, "binary").toString("base64");
};
@ -50,7 +50,7 @@ if (
if (globalThis.atob || !isNodeJS) {
return;
}
globalThis.atob = function(input) {
globalThis.atob = function (input) {
// eslint-disable-next-line no-undef
return Buffer.from(input, "base64").toString("binary");
};
@ -65,7 +65,7 @@ if (
if (typeof Element.prototype.remove !== "undefined") {
return;
}
Element.prototype.remove = function() {
Element.prototype.remove = function () {
if (this.parentNode) {
// eslint-disable-next-line mozilla/avoid-removeChild
this.parentNode.removeChild(this);
@ -92,12 +92,12 @@ if (
const OriginalDOMTokenListAdd = DOMTokenList.prototype.add;
const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function(...tokens) {
DOMTokenList.prototype.add = function (...tokens) {
for (const token of tokens) {
OriginalDOMTokenListAdd.call(this, token);
}
};
DOMTokenList.prototype.remove = function(...tokens) {
DOMTokenList.prototype.remove = function (...tokens) {
for (const token of tokens) {
OriginalDOMTokenListRemove.call(this, token);
}
@ -116,7 +116,7 @@ if (
return;
}
DOMTokenList.prototype.toggle = function(token) {
DOMTokenList.prototype.toggle = function (token) {
const force =
arguments.length > 1 ? !!arguments[1] : !this.contains(token);
return this[force ? "add" : "remove"](token), force;
@ -133,11 +133,11 @@ if (
const OriginalPushState = window.history.pushState;
const OriginalReplaceState = window.history.replaceState;
window.history.pushState = function(state, title, url) {
window.history.pushState = function (state, title, url) {
const args = url === undefined ? [state, title] : [state, title, url];
OriginalPushState.apply(this, args);
};
window.history.replaceState = function(state, title, url) {
window.history.replaceState = function (state, title, url) {
const args = url === undefined ? [state, title] : [state, title, url];
OriginalReplaceState.apply(this, args);
};

View File

@ -116,10 +116,10 @@ class MessageHandler {
if (data.callbackId) {
const cbSourceName = this.sourceName;
const cbTargetName = data.sourceName;
new Promise(function(resolve) {
new Promise(function (resolve) {
resolve(action(data.data));
}).then(
function(result) {
function (result) {
comObj.postMessage({
sourceName: cbSourceName,
targetName: cbTargetName,
@ -128,7 +128,7 @@ class MessageHandler {
data: result,
});
},
function(reason) {
function (reason) {
comObj.postMessage({
sourceName: cbSourceName,
targetName: cbTargetName,
@ -367,10 +367,10 @@ class MessageHandler {
streamSink.sinkCapability.resolve();
streamSink.ready = streamSink.sinkCapability.promise;
this.streamSinks[streamId] = streamSink;
new Promise(function(resolve) {
new Promise(function (resolve) {
resolve(action(data.data, streamSink));
}).then(
function() {
function () {
comObj.postMessage({
sourceName,
targetName,
@ -379,7 +379,7 @@ class MessageHandler {
success: true,
});
},
function(reason) {
function (reason) {
comObj.postMessage({
sourceName,
targetName,
@ -443,10 +443,10 @@ class MessageHandler {
// Reset desiredSize property of sink on every pull.
this.streamSinks[streamId].desiredSize = data.desiredSize;
const { onPull } = this.streamSinks[data.streamId];
new Promise(function(resolve) {
new Promise(function (resolve) {
resolve(onPull && onPull());
}).then(
function() {
function () {
comObj.postMessage({
sourceName,
targetName,
@ -455,7 +455,7 @@ class MessageHandler {
success: true,
});
},
function(reason) {
function (reason) {
comObj.postMessage({
sourceName,
targetName,
@ -513,10 +513,10 @@ class MessageHandler {
break;
}
const { onCancel } = this.streamSinks[data.streamId];
new Promise(function(resolve) {
new Promise(function (resolve) {
resolve(onCancel && onCancel(wrapReason(data.reason)));
}).then(
function() {
function () {
comObj.postMessage({
sourceName,
targetName,
@ -525,7 +525,7 @@ class MessageHandler {
success: true,
});
},
function(reason) {
function (reason) {
comObj.postMessage({
sourceName,
targetName,
@ -557,7 +557,7 @@ class MessageHandler {
this.streamControllers[streamId].startCall,
this.streamControllers[streamId].pullCall,
this.streamControllers[streamId].cancelCall,
].map(function(capability) {
].map(function (capability) {
return capability && capability.promise;
})
);

View File

@ -812,7 +812,7 @@ function isArrayEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
return arr1.every(function(element, index) {
return arr1.every(function (element, index) {
return element === arr2[index];
});
}
@ -842,12 +842,12 @@ function createPromiseCapability() {
return isSettled;
},
});
capability.promise = new Promise(function(resolve, reject) {
capability.resolve = function(data) {
capability.promise = new Promise(function (resolve, reject) {
capability.resolve = function (data) {
isSettled = true;
resolve(data);
};
capability.reject = function(reason) {
capability.reject = function (reason) {
isSettled = true;
reject(reason);
};

View File

@ -17,9 +17,9 @@
// Patch importScripts to work around a bug in WebKit and Chrome 48-.
// See https://crbug.com/572225 and https://webkit.org/b/153317.
self.importScripts = (function(importScripts) {
return function() {
setTimeout(function() {}, 0);
self.importScripts = (function (importScripts) {
return function () {
setTimeout(function () {}, 0);
return importScripts.apply(this, arguments);
};
})(importScripts);
@ -27,6 +27,6 @@ self.importScripts = (function(importScripts) {
importScripts("../node_modules/systemjs/dist/system.js");
importScripts("../systemjs.config.js");
SystemJS.import("pdfjs/core/worker.js").then(function() {
SystemJS.import("pdfjs/core/worker.js").then(function () {
// Worker is loaded at this point.
});

View File

@ -15,7 +15,7 @@
"use strict";
(function() {
(function () {
var baseLocation;
if (typeof document !== "undefined") {
baseLocation = new URL("./", document.currentScript.src);

View File

@ -25,13 +25,13 @@ if (!fs.existsSync(file)) {
function calculateMD5(pdfFile, callback) {
var hash = crypto.createHash("md5");
var stream = fs.createReadStream(pdfFile);
stream.on("data", function(data) {
stream.on("data", function (data) {
hash.update(data);
});
stream.on("error", function(err) {
stream.on("error", function (err) {
callback(err);
});
stream.on("end", function() {
stream.on("end", function () {
var result = hash.digest("hex");
callback(null, result);
});

View File

@ -45,13 +45,13 @@ function createExtensionGlobal() {
window.chrome.extension.inIncognitoContext = false;
window.chrome.runtime = {};
window.chrome.runtime.id = "oemmndcbldboiebfnladdacbdfmadadm";
window.chrome.runtime.getManifest = function() {
window.chrome.runtime.getManifest = function () {
return { version: "1.0.0" };
};
function createStorageAPI() {
var storageArea = {};
storageArea.get = function(key, callback) {
storageArea.get = function (key, callback) {
assert.equal(key, "disableTelemetry");
// chrome.storage.*. is async, but we make it synchronous to ease testing.
callback(storageArea.mock_data);
@ -73,7 +73,7 @@ function createExtensionGlobal() {
var getRandomValues_state = 0;
window.crypto = {};
window.crypto.getRandomValues = function(buf) {
window.crypto.getRandomValues = function (buf) {
var state = getRandomValues_state++;
for (var i = 0; i < buf.length; ++i) {
// Totally random byte ;)
@ -89,38 +89,38 @@ function createExtensionGlobal() {
throw new TypeError("Illegal invocation");
},
};
window.fetch = function(url, options) {
window.fetch = function (url, options) {
assert.equal(url, LOG_URL);
assert.equal(options.method, "POST");
assert.equal(options.mode, "cors");
assert.ok(!options.body);
test_requests.push(options.headers);
};
window.Headers = function(headers) {
window.Headers = function (headers) {
headers = JSON.parse(JSON.stringify(headers)); // Clone.
Object.keys(headers).forEach(function(k) {
Object.keys(headers).forEach(function (k) {
headers[k] = String(headers[k]);
});
return headers;
};
window.XMLHttpRequest = function() {
window.XMLHttpRequest = function () {
var invoked = {
open: false,
send: false,
};
var headers = {};
return {
open: function(method, url) {
open: function (method, url) {
assert.equal(invoked.open, false);
invoked.open = true;
assert.equal(method, "POST");
assert.equal(url, LOG_URL);
},
setRequestHeader: function(k, v) {
setRequestHeader: function (k, v) {
assert.equal(invoked.open, true);
headers[k] = String(v);
},
send: function(body) {
send: function (body) {
assert.equal(invoked.open, true);
assert.equal(invoked.send, false);
invoked.send = true;
@ -132,19 +132,19 @@ function createExtensionGlobal() {
// Time-related logic.
var timers = [];
window.setInterval = function(callback, ms) {
window.setInterval = function (callback, ms) {
assert.equal(typeof callback, "function");
timers.push(callback);
};
window.Date = {
test_now_value: Date.now(),
now: function() {
now: function () {
return window.Date.test_now_value;
},
};
window.test_fireTimers = function() {
window.test_fireTimers = function () {
assert.ok(timers.length);
timers.forEach(function(timer) {
timers.forEach(function (timer) {
timer();
});
};
@ -156,7 +156,7 @@ function createExtensionGlobal() {
function updateBrowser(window) {
window.navigator.userAgent = window.navigator.userAgent.replace(
/Chrome\/(\d+)/,
function(_, v) {
function (_, v) {
return "Chrome/" + (parseInt(v) + 1);
}
);
@ -351,7 +351,7 @@ var tests = [
function test_extension_update() {
var window = createExtensionGlobal();
telemetryScript.runInNewContext(window);
window.chrome.runtime.getManifest = function() {
window.chrome.runtime.getManifest = function () {
return { version: "1.0.1" };
};
window.Date.test_now_value += 12 * 36e5;
@ -373,7 +373,7 @@ var tests = [
var window = createExtensionGlobal();
var didWarn = false;
window.console = {};
window.console.warn = function() {
window.console.warn = function () {
didWarn = true;
};
window.chrome.runtime.id = "abcdefghijklmnopabcdefghijklmnop";
@ -413,7 +413,7 @@ var tests = [
function test_fetch_mode_not_supported() {
var window = createExtensionGlobal();
delete window.Request.prototype.mode;
window.fetch = function() {
window.fetch = function () {
throw new Error("Unexpected call to fetch!");
};
telemetryScript.runInNewContext(window);

View File

@ -40,7 +40,7 @@ function downloadFile(file, url, callback, redirects) {
var completed = false;
var protocol = /^https:\/\//.test(url) ? https : http;
protocol
.get(url, function(response) {
.get(url, function (response) {
var redirectTo;
if (
response.statusCode === 301 ||
@ -71,14 +71,14 @@ function downloadFile(file, url, callback, redirects) {
return;
}
var stream = fs.createWriteStream(file);
stream.on("error", function(err) {
stream.on("error", function (err) {
if (!completed) {
completed = true;
callback(err);
}
});
response.pipe(stream);
stream.on("finish", function() {
stream.on("finish", function () {
stream.end();
if (!completed) {
completed = true;
@ -86,7 +86,7 @@ function downloadFile(file, url, callback, redirects) {
}
});
})
.on("error", function(err) {
.on("error", function (err) {
if (!completed) {
if (
typeof err === "object" &&
@ -113,7 +113,7 @@ function downloadManifestFiles(manifest, callback) {
var file = links[i].file;
var url = links[i].url;
console.log("Downloading " + url + " to " + file + "...");
downloadFile(file, url, function(err) {
downloadFile(file, url, function (err) {
if (err) {
console.error("Error during downloading of " + url + ": " + err);
fs.writeFileSync(file, ""); // making it empty file
@ -125,10 +125,10 @@ function downloadManifestFiles(manifest, callback) {
}
var links = manifest
.filter(function(item) {
.filter(function (item) {
return item.link && !fs.existsSync(item.file);
})
.map(function(item) {
.map(function (item) {
var file = item.file;
var linkfile = file + ".link";
var url = fs.readFileSync(linkfile).toString();
@ -143,13 +143,13 @@ function downloadManifestFiles(manifest, callback) {
function calculateMD5(file, callback) {
var hash = crypto.createHash("md5");
var stream = fs.createReadStream(file);
stream.on("data", function(data) {
stream.on("data", function (data) {
hash.update(data);
});
stream.on("error", function(err) {
stream.on("error", function (err) {
callback(err);
});
stream.on("end", function() {
stream.on("end", function () {
var result = hash.digest("hex");
callback(null, result);
});
@ -171,7 +171,7 @@ function verifyManifestFiles(manifest, callback) {
verifyNext();
return;
}
calculateMD5(item.file, function(err, md5) {
calculateMD5(item.file, function (err, md5) {
if (err) {
console.log('WARNING: Unable to open file for reading "' + err + '".');
error = true;

View File

@ -34,10 +34,10 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
if (textLayerStylePromise) {
return textLayerStylePromise;
}
textLayerStylePromise = new Promise(function(resolve) {
textLayerStylePromise = new Promise(function (resolve) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "./text_layer_test.css");
xhr.onload = function() {
xhr.onload = function () {
resolve(xhr.responseText);
};
xhr.send(null);
@ -52,7 +52,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
textContent,
enhanceTextSelection
) {
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
// Building SVG with size of the viewport.
var svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("width", viewport.width + "px");
@ -80,7 +80,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
viewport,
enhanceTextSelection,
});
Promise.all([stylePromise, task.promise]).then(function(results) {
Promise.all([stylePromise, task.promise]).then(function (results) {
task.expandTextDivs(true);
style.textContent = results[0];
svg.appendChild(foreignObject);
@ -91,11 +91,11 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() {
);
var img = new Image();
img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
img.onload = function() {
img.onload = function () {
ctx.drawImage(img, 0, 0);
resolve();
};
img.onerror = function(e) {
img.onerror = function (e) {
reject(new Error("Error rasterizing text layer " + e));
};
});
@ -139,13 +139,13 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
// Load the style files and cache the results.
for (const key in styles) {
styles[key].promise = new Promise(function(resolve, reject) {
styles[key].promise = new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open("GET", styles[key].file);
xhr.onload = function() {
xhr.onload = function () {
resolve(xhr.responseText);
};
xhr.onerror = function(e) {
xhr.onerror = function (e) {
reject(new Error("Error fetching annotation style " + e));
};
xhr.send(null);
@ -158,17 +158,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
function inlineAnnotationImages(images) {
var imagePromises = [];
for (var i = 0, ii = images.length; i < ii; i++) {
var imagePromise = new Promise(function(resolve, reject) {
var imagePromise = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = function() {
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function() {
reader.onloadend = function () {
resolve(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.onerror = function(e) {
xhr.onerror = function (e) {
reject(new Error("Error fetching inline annotation image " + e));
};
xhr.open("GET", images[i].src);
@ -188,7 +188,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
imageResourcesPath,
renderInteractiveForms
) {
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
// Building SVG with size of the viewport.
var svg = document.createElementNS(SVG_NS, "svg:svg");
svg.setAttribute("width", viewport.width + "px");
@ -207,7 +207,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
div.className = "annotationLayer";
// Rendering annotation layer as HTML.
stylePromise.then(function(common, overrides) {
stylePromise.then(function (common, overrides) {
style.textContent = common + overrides;
var annotation_viewport = viewport.clone({ dontFlip: true });
@ -225,14 +225,14 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
// Inline SVG images from text annotations.
var images = div.getElementsByTagName("img");
var imagePromises = inlineAnnotationImages(images);
var converted = Promise.all(imagePromises).then(function(data) {
var converted = Promise.all(imagePromises).then(function (data) {
var loadedPromises = [];
for (var i = 0, ii = data.length; i < ii; i++) {
images[i].src = data[i];
loadedPromises.push(
new Promise(function(resolveImage, rejectImage) {
new Promise(function (resolveImage, rejectImage) {
images[i].onload = resolveImage;
images[i].onerror = function(e) {
images[i].onerror = function (e) {
rejectImage(new Error("Error loading image " + e));
};
})
@ -245,17 +245,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
svg.appendChild(foreignObject);
// We need to have UTF-8 encoded XML.
converted.then(function() {
converted.then(function () {
var svg_xml = unescape(
encodeURIComponent(new XMLSerializer().serializeToString(svg))
);
var img = new Image();
img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
img.onload = function() {
img.onload = function () {
ctx.drawImage(img, 0, 0);
resolve();
};
img.onerror = function(e) {
img.onerror = function (e) {
reject(new Error("Error rasterizing annotation layer " + e));
};
});
@ -325,7 +325,7 @@ var Driver = (function DriverClosure() {
run: function Driver_run() {
var self = this;
window.onerror = function(message, source, line, column, error) {
window.onerror = function (message, source, line, column, error) {
self._info(
"Error: " +
message +
@ -351,12 +351,12 @@ var Driver = (function DriverClosure() {
var r = new XMLHttpRequest();
r.open("GET", this.manifestFile, false);
r.onreadystatechange = function() {
r.onreadystatechange = function () {
if (r.readyState === 4) {
self._log("done\n");
self.manifest = JSON.parse(r.responseText);
if (self.testFilter && self.testFilter.length) {
self.manifest = self.manifest.filter(function(item) {
self.manifest = self.manifest.filter(function (item) {
return self.testFilter.includes(item.id);
});
}
@ -369,7 +369,7 @@ var Driver = (function DriverClosure() {
}
// When gathering the stats the numbers seem to be more reliable
// if the browser is given more time to start.
setTimeout(function() {
setTimeout(function () {
r.send(null);
}, this.delay);
},
@ -472,7 +472,7 @@ var Driver = (function DriverClosure() {
if (!task.pdfDoc) {
var dataUrl = this.canvas.toDataURL("image/png");
this._sendResult(dataUrl, task, failure, function() {
this._sendResult(dataUrl, task, failure, function () {
self._log(
"done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
);
@ -518,7 +518,7 @@ var Driver = (function DriverClosure() {
this.canvas.mozOpaque = true;
ctx = this.canvas.getContext("2d", { alpha: false });
task.pdfDoc.getPage(task.pageNum).then(
function(page) {
function (page) {
var viewport = page.getViewport({ scale: PDF_TO_CSS_UNITS });
self.canvas.width = viewport.width;
self.canvas.height = viewport.height;
@ -552,7 +552,7 @@ var Driver = (function DriverClosure() {
.getTextContent({
normalizeWhitespace: true,
})
.then(function(textContent) {
.then(function (textContent) {
return rasterizeTextLayer(
textLayerContext,
viewport,
@ -590,7 +590,7 @@ var Driver = (function DriverClosure() {
// The annotation builder will draw its content on the canvas.
initPromise = page
.getAnnotations({ intent: "display" })
.then(function(annotations) {
.then(function (annotations) {
return rasterizeAnnotationLayer(
annotationLayerContext,
viewport,
@ -611,7 +611,7 @@ var Driver = (function DriverClosure() {
viewport,
renderInteractiveForms: renderForms,
};
var completeRender = function(error) {
var completeRender = function (error) {
// if text layer is present, compose it on top of the page
if (textLayerCanvas) {
ctx.save();
@ -633,16 +633,16 @@ var Driver = (function DriverClosure() {
self._snapshot(task, error);
};
initPromise
.then(function() {
return page.render(renderContext).promise.then(function() {
.then(function () {
return page.render(renderContext).promise.then(function () {
completeRender(false);
});
})
.catch(function(error) {
.catch(function (error) {
completeRender("render : " + error);
});
},
function(error) {
function (error) {
self._snapshot(task, "render : " + error);
}
);
@ -664,7 +664,7 @@ var Driver = (function DriverClosure() {
this._log("Snapshotting... ");
var dataUrl = this.canvas.toDataURL("image/png");
this._sendResult(dataUrl, task, failure, function() {
this._sendResult(dataUrl, task, failure, function () {
self._log(
"done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
);
@ -680,7 +680,7 @@ var Driver = (function DriverClosure() {
// Send the quit request
var r = new XMLHttpRequest();
r.open("POST", "/tellMeToQuit?path=" + escape(this.appPath), false);
r.onreadystatechange = function(e) {
r.onreadystatechange = function (e) {
if (r.readyState === 4) {
window.close();
}
@ -744,13 +744,13 @@ var Driver = (function DriverClosure() {
var r = new XMLHttpRequest();
r.open("POST", url, true);
r.setRequestHeader("Content-Type", "application/json");
r.onreadystatechange = function(e) {
r.onreadystatechange = function (e) {
if (r.readyState === 4) {
self.inFlightRequests--;
// Retry until successful
if (r.status !== 200) {
setTimeout(function() {
setTimeout(function () {
self._send(url, message);
});
}

View File

@ -46,7 +46,7 @@ function initializePDFJS(callback) {
SystemJS.import("pdfjs/core/stream.js"),
SystemJS.import("pdfjs/core/primitives.js"),
SystemJS.import("pdfjs/core/cmap.js"),
]).then(function(modules) {
]).then(function (modules) {
var fonts = modules[0],
stream = modules[1],
primitives = modules[2],
@ -62,7 +62,7 @@ function initializePDFJS(callback) {
});
}
(function() {
(function () {
window.jasmine = jasmineRequire.core(jasmineRequire);
jasmineRequire.html(jasmine);
@ -134,7 +134,7 @@ function initializePDFJS(callback) {
},
});
config.specFilter = function(spec) {
config.specFilter = function (spec) {
return specFilter.matches(spec.getFullName());
};
@ -148,12 +148,12 @@ function initializePDFJS(callback) {
// instance and then executing the loaded Jasmine environment.
var currentWindowOnload = window.onload;
window.onload = function() {
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
initializePDFJS(function() {
initializePDFJS(function () {
htmlReporter.initialize();
env.execute();
});

View File

@ -25,9 +25,9 @@ var ttxResourcesHome = path.join(__dirname, "..", "ttx");
var nextTTXTaskId = Date.now();
function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) {
fs.realpath(ttxResourcesHomePath, function(error, realTtxResourcesHomePath) {
fs.realpath(ttxResourcesHomePath, function (error, realTtxResourcesHomePath) {
var fontToolsHome = path.join(realTtxResourcesHomePath, "fonttools-code");
fs.realpath(fontPath, function(errorFontPath, realFontPath) {
fs.realpath(fontPath, function (errorFontPath, realFontPath) {
var ttxPath = path.join("Tools", "ttx");
if (!fs.existsSync(path.join(fontToolsHome, ttxPath))) {
callback("TTX was not found, please checkout PDF.js submodules");
@ -44,16 +44,16 @@ function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) {
env: ttxEnv,
});
var ttxRunError;
registerOnCancel(function(reason) {
registerOnCancel(function (reason) {
ttxRunError = reason;
callback(reason);
ttx.kill();
});
ttx.on("error", function(errorTtx) {
ttx.on("error", function (errorTtx) {
ttxRunError = errorTtx;
callback("Unable to execute ttx");
});
ttx.on("close", function(code) {
ttx.on("close", function (code) {
if (ttxRunError) {
return;
}
@ -74,7 +74,7 @@ exports.translateFont = function translateFont(
var resultPath = path.join(ttxResourcesHome, taskId + ".ttx");
fs.writeFileSync(fontPath, buffer);
runTtx(ttxResourcesHome, fontPath, registerOnCancel, function(err) {
runTtx(ttxResourcesHome, fontPath, registerOnCancel, function (err) {
fs.unlinkSync(fontPath);
if (err) {
console.error(err);

View File

@ -57,8 +57,8 @@ function group(stats, groupBy) {
*/
function flatten(stats) {
var rows = [];
stats.forEach(function(curStat) {
curStat["stats"].forEach(function(s) {
stats.forEach(function (curStat) {
curStat["stats"].forEach(function (s) {
rows.push({
browser: curStat["browser"],
page: curStat["page"],
@ -71,7 +71,7 @@ function flatten(stats) {
});
// Use only overall results if not grouped by 'stat'
if (!options.groupBy.includes("stat")) {
rows = rows.filter(function(s) {
rows = rows.filter(function (s) {
return s.stat === "Overall";
});
}
@ -138,7 +138,7 @@ function stat(baseline, current) {
row,
rows = [];
// collect rows and measure column widths
var width = labels.map(function(s) {
var width = labels.map(function (s) {
return s.length;
});
rows.push(labels);
@ -172,7 +172,7 @@ function stat(baseline, current) {
}
// add horizontal line
var hline = width.map(function(w) {
var hline = width.map(function (w) {
return new Array(w + 1).join("-");
});
rows.splice(1, 0, hline);

View File

@ -27,7 +27,7 @@ var testUtils = require("./testutils.js");
function parseOptions() {
function describeCheck(fn, text) {
fn.toString = function() {
fn.toString = function () {
return text;
};
return fn;
@ -102,7 +102,7 @@ function parseOptions() {
)
.default("statsDelay", 0)
.check(
describeCheck(function(argv) {
describeCheck(function (argv) {
return (
+argv.reftest + argv.unitTest + argv.fontTest + argv.masterMode <= 1
);
@ -110,18 +110,18 @@ function parseOptions() {
"specified at the same time.")
)
.check(
describeCheck(function(argv) {
describeCheck(function (argv) {
return !argv.noDownload || !argv.downloadOnly;
}, "--noDownload and --downloadOnly cannot be used together.")
)
.check(
describeCheck(function(argv) {
describeCheck(function (argv) {
return !argv.masterMode || argv.manifestFile === "test_manifest.json";
}, "when --masterMode is specified --manifestFile shall be equal " +
"test_manifest.json")
)
.check(
describeCheck(function(argv) {
describeCheck(function (argv) {
return !argv.browser || !argv.browserManifestFile;
}, "--browser and --browserManifestFile must not be specified at the " +
"same time.")
@ -151,7 +151,7 @@ function monitorBrowserTimeout(session, onTimeout) {
session.timeoutMonitor = null;
return;
}
session.timeoutMonitor = setTimeout(function() {
session.timeoutMonitor = setTimeout(function () {
onTimeout(session);
}, browserTimeout * 1000);
}
@ -172,7 +172,7 @@ function updateRefImages() {
}
testUtils.confirm(
"Would you like to update the master copy in ref/? [yn] ",
function(confirmed) {
function (confirmed) {
if (confirmed) {
sync(true);
} else {
@ -203,7 +203,7 @@ function startRefTest(masterMode, showRefImages) {
var numFBFFailures = 0;
var numEqFailures = 0;
var numEqNoSnapshot = 0;
sessions.forEach(function(session) {
sessions.forEach(function (session) {
numErrors += session.numErrors;
numFBFFailures += session.numFBFFailures;
numEqFailures += session.numEqFailures;
@ -274,12 +274,12 @@ function startRefTest(masterMode, showRefImages) {
server.hooks["POST"].push(refTestPostHandler);
onAllSessionsClosed = finalize;
startBrowsers("/test/test_slave.html", function(session) {
startBrowsers("/test/test_slave.html", function (session) {
session.masterMode = masterMode;
session.taskResults = {};
session.tasks = {};
session.remaining = manifest.length;
manifest.forEach(function(item) {
manifest.forEach(function (item) {
var rounds = item.rounds || 1;
var roundsResults = [];
roundsResults.length = rounds;
@ -304,7 +304,7 @@ function startRefTest(masterMode, showRefImages) {
console.log("tmp/ can be removed if it has nothing you need.");
testUtils.confirm(
"SHOULD THIS SCRIPT REMOVE tmp/? THINK CAREFULLY [yn] ",
function(confirmed) {
function (confirmed) {
if (confirmed) {
testUtils.removeDirSync(refsTmpDir);
}
@ -350,7 +350,7 @@ function getTestManifest() {
var testFilter = options.testfilter.slice(0);
if (testFilter.length) {
manifest = manifest.filter(function(item) {
manifest = manifest.filter(function (item) {
var i = testFilter.indexOf(item.id);
if (i !== -1) {
testFilter.splice(i, 1);
@ -533,8 +533,8 @@ function checkRefTestResults(browser, id, results) {
var failed = false;
var session = getSession(browser);
var task = session.tasks[id];
results.forEach(function(roundResults, round) {
roundResults.forEach(function(pageResult, page) {
results.forEach(function (roundResults, round) {
roundResults.forEach(function (pageResult, page) {
if (!pageResult) {
return; // no results
}
@ -589,8 +589,8 @@ function checkRefTestResults(browser, id, results) {
throw new Error("Unknown test type");
}
// clear memory
results.forEach(function(roundResults, round) {
roundResults.forEach(function(pageResult, page) {
results.forEach(function (roundResults, round) {
roundResults.forEach(function (pageResult, page) {
pageResult.snapshot = null;
});
});
@ -608,10 +608,10 @@ function refTestPostHandler(req, res) {
}
var body = "";
req.on("data", function(data) {
req.on("data", function (data) {
body += data;
});
req.on("end", function() {
req.on("end", function () {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end();
@ -619,7 +619,7 @@ function refTestPostHandler(req, res) {
if (pathname === "/tellMeToQuit") {
// finding by path
var browserPath = parsedUrl.query.path;
session = sessions.filter(function(curSession) {
session = sessions.filter(function (curSession) {
return curSession.config.path === browserPath;
})[0];
monitorBrowserTimeout(session, null);
@ -693,11 +693,11 @@ function startUnitTest(testUrl, name) {
var startTime = Date.now();
startServer();
server.hooks["POST"].push(unitTestPostHandler);
onAllSessionsClosed = function() {
onAllSessionsClosed = function () {
stopServer();
var numRuns = 0,
numErrors = 0;
sessions.forEach(function(session) {
sessions.forEach(function (session) {
numRuns += session.numRuns;
numErrors += session.numErrors;
});
@ -712,7 +712,7 @@ function startUnitTest(testUrl, name) {
var runtime = (Date.now() - startTime) / 1000;
console.log(name + " tests runtime was " + runtime.toFixed(1) + " seconds");
};
startBrowsers(testUrl, function(session) {
startBrowsers(testUrl, function (session) {
session.numRuns = 0;
session.numErrors = 0;
});
@ -731,25 +731,25 @@ function unitTestPostHandler(req, res) {
}
var body = "";
req.on("data", function(data) {
req.on("data", function (data) {
body += data;
});
req.on("end", function() {
req.on("end", function () {
if (pathname === "/ttx") {
var translateFont = require("./font/ttxdriver.js").translateFont;
var onCancel = null,
ttxTimeout = 10000;
var timeoutId = setTimeout(function() {
var timeoutId = setTimeout(function () {
if (onCancel) {
onCancel("TTX timeout");
}
}, ttxTimeout);
translateFont(
body,
function(fn) {
function (fn) {
onCancel = fn;
},
function(err, xml) {
function (err, xml) {
clearTimeout(timeoutId);
res.writeHead(200, { "Content-Type": "text/xml" });
res.end(err ? "<error>" + err + "</error>" : xml);
@ -797,7 +797,7 @@ function startBrowsers(testUrl, initSessionCallback) {
process.exit(1);
}
sessions = [];
browsers.forEach(function(b) {
browsers.forEach(function (b) {
var browser = WebBrowser.create(b);
var startUrl =
getServerBaseAddress() +
@ -846,7 +846,7 @@ function stopServer() {
}
function getSession(browser) {
return sessions.filter(function(session) {
return sessions.filter(function (session) {
return session.name === browser;
})[0];
}
@ -858,9 +858,9 @@ function closeSession(browser) {
}
if (i < sessions.length) {
var session = sessions[i];
session.browser.stop(function() {
session.browser.stop(function () {
session.closed = true;
var allClosed = sessions.every(function(s) {
var allClosed = sessions.every(function (s) {
return s.closed;
});
if (allClosed && onAllSessionsClosed) {
@ -873,8 +873,8 @@ function closeSession(browser) {
function ensurePDFsDownloaded(callback) {
var downloadUtils = require("./downloadutils.js");
var manifest = getTestManifest();
downloadUtils.downloadManifestFiles(manifest, function() {
downloadUtils.verifyManifestFiles(manifest, function(hasErrors) {
downloadUtils.downloadManifestFiles(manifest, function () {
downloadUtils.verifyManifestFiles(manifest, function (hasErrors) {
if (hasErrors) {
console.log(
"Unable to verify the checksum for the files that are " +
@ -899,12 +899,12 @@ function main() {
}
if (options.downloadOnly) {
ensurePDFsDownloaded(function() {});
ensurePDFsDownloaded(function () {});
} else if (!options.browser && !options.browserManifestFile) {
startServer();
} else if (options.unitTest) {
// Allows linked PDF files in unit-tests as well.
ensurePDFsDownloaded(function() {
ensurePDFsDownloaded(function () {
startUnitTest("/test/unit/unit_test.html", "unit");
});
} else if (options.fontTest) {

View File

@ -32,7 +32,7 @@ exports.copySubtreeSync = function copySubtreeSync(src, dest) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
files.forEach(function(filename) {
files.forEach(function (filename) {
var srcFile = path.join(src, filename);
var file = path.join(dest, filename);
var stats = fs.statSync(srcFile);
@ -99,12 +99,12 @@ function handleStdinBuffer() {
function initStdin() {
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) {
process.stdin.on("data", function (chunk) {
stdinBuffer += chunk;
handleStdinBuffer();
});
process.stdin.on("end", function() {
process.stdin.on("end", function () {
endOfStdin = true;
handleStdinBuffer();
});
@ -125,7 +125,7 @@ exports.prompt = function prompt(message, callback) {
};
exports.confirm = function confirm(message, callback) {
exports.prompt(message, function(answer) {
exports.prompt(message, function (answer) {
if (answer === undefined) {
callback();
return;

View File

@ -33,14 +33,14 @@ import { Dict, Name, Ref } from "../../src/core/primitives.js";
import { Lexer, Parser } from "../../src/core/parser.js";
import { StringStream } from "../../src/core/stream.js";
describe("annotation", function() {
describe("annotation", function () {
class PDFManagerMock {
constructor(params) {
this.docBaseUrl = params.docBaseUrl || null;
}
ensure(obj, prop, args) {
return new Promise(function(resolve) {
return new Promise(function (resolve) {
const value = obj[prop];
if (typeof value === "function") {
resolve(value.apply(obj, args));
@ -53,7 +53,7 @@ describe("annotation", function() {
let pdfManagerMock, idFactoryMock;
beforeAll(function(done) {
beforeAll(function (done) {
pdfManagerMock = new PDFManagerMock({
docBaseUrl: null,
});
@ -61,13 +61,13 @@ describe("annotation", function() {
done();
});
afterAll(function() {
afterAll(function () {
pdfManagerMock = null;
idFactoryMock = null;
});
describe("AnnotationFactory", function() {
it("should get id for annotation", function(done) {
describe("AnnotationFactory", function () {
it("should get id for annotation", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -90,7 +90,7 @@ describe("annotation", function() {
it(
"should handle, and get fallback IDs for, annotations that are not " +
"indirect objects (issue 7569)",
function(done) {
function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -122,7 +122,7 @@ describe("annotation", function() {
}
);
it("should handle missing /Subtype", function(done) {
it("should handle missing /Subtype", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -141,35 +141,35 @@ describe("annotation", function() {
});
});
describe("getQuadPoints", function() {
describe("getQuadPoints", function () {
let dict, rect;
beforeEach(function(done) {
beforeEach(function (done) {
dict = new Dict();
rect = [];
done();
});
afterEach(function() {
afterEach(function () {
dict = null;
rect = null;
});
it("should ignore missing quadpoints", function() {
it("should ignore missing quadpoints", function () {
expect(getQuadPoints(dict, rect)).toEqual(null);
});
it("should ignore non-array values", function() {
it("should ignore non-array values", function () {
dict.set("QuadPoints", "foo");
expect(getQuadPoints(dict, rect)).toEqual(null);
});
it("should ignore arrays where the length is not a multiple of eight", function() {
it("should ignore arrays where the length is not a multiple of eight", function () {
dict.set("QuadPoints", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
expect(getQuadPoints(dict, rect)).toEqual(null);
});
it("should ignore quadpoints if one coordinate lies outside the rectangle", function() {
it("should ignore quadpoints if one coordinate lies outside the rectangle", function () {
rect = [10, 10, 20, 20];
const inputs = [
[11, 11, 12, 12, 9, 13, 14, 14], // Smaller than lower x coordinate.
@ -183,7 +183,7 @@ describe("annotation", function() {
}
});
it("should process valid quadpoints arrays", function() {
it("should process valid quadpoints arrays", function () {
rect = [10, 10, 20, 20];
dict.set("QuadPoints", [
11,
@ -220,48 +220,48 @@ describe("annotation", function() {
});
});
describe("Annotation", function() {
describe("Annotation", function () {
let dict, ref;
beforeAll(function(done) {
beforeAll(function (done) {
dict = new Dict();
ref = Ref.get(1, 0);
done();
});
afterAll(function() {
afterAll(function () {
dict = ref = null;
});
it("should set and get valid contents", function() {
it("should set and get valid contents", function () {
const annotation = new Annotation({ dict, ref });
annotation.setContents("Foo bar baz");
expect(annotation.contents).toEqual("Foo bar baz");
});
it("should not set and get invalid contents", function() {
it("should not set and get invalid contents", function () {
const annotation = new Annotation({ dict, ref });
annotation.setContents(undefined);
expect(annotation.contents).toEqual("");
});
it("should set and get a valid modification date", function() {
it("should set and get a valid modification date", function () {
const annotation = new Annotation({ dict, ref });
annotation.setModificationDate("D:20190422");
expect(annotation.modificationDate).toEqual("D:20190422");
});
it("should not set and get an invalid modification date", function() {
it("should not set and get an invalid modification date", function () {
const annotation = new Annotation({ dict, ref });
annotation.setModificationDate(undefined);
expect(annotation.modificationDate).toEqual(null);
});
it("should set and get flags", function() {
it("should set and get flags", function () {
const annotation = new Annotation({ dict, ref });
annotation.setFlags(13);
@ -271,63 +271,63 @@ describe("annotation", function() {
expect(annotation.hasFlag(AnnotationFlag.READONLY)).toEqual(false);
});
it("should be viewable and not printable by default", function() {
it("should be viewable and not printable by default", function () {
const annotation = new Annotation({ dict, ref });
expect(annotation.viewable).toEqual(true);
expect(annotation.printable).toEqual(false);
});
it("should set and get a valid rectangle", function() {
it("should set and get a valid rectangle", function () {
const annotation = new Annotation({ dict, ref });
annotation.setRectangle([117, 694, 164.298, 720]);
expect(annotation.rectangle).toEqual([117, 694, 164.298, 720]);
});
it("should not set and get an invalid rectangle", function() {
it("should not set and get an invalid rectangle", function () {
const annotation = new Annotation({ dict, ref });
annotation.setRectangle([117, 694, 164.298]);
expect(annotation.rectangle).toEqual([0, 0, 0, 0]);
});
it("should reject a color if it is not an array", function() {
it("should reject a color if it is not an array", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor("red");
expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
});
it("should set and get a transparent color", function() {
it("should set and get a transparent color", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor([]);
expect(annotation.color).toEqual(null);
});
it("should set and get a grayscale color", function() {
it("should set and get a grayscale color", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor([0.4]);
expect(annotation.color).toEqual(new Uint8ClampedArray([102, 102, 102]));
});
it("should set and get an RGB color", function() {
it("should set and get an RGB color", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor([0, 0, 1]);
expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 255]));
});
it("should set and get a CMYK color", function() {
it("should set and get a CMYK color", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor([0.1, 0.92, 0.84, 0.02]);
expect(annotation.color).toEqual(new Uint8ClampedArray([234, 59, 48]));
});
it("should not set and get an invalid color", function() {
it("should not set and get an invalid color", function () {
const annotation = new Annotation({ dict, ref });
annotation.setColor([0.4, 0.6]);
@ -335,22 +335,22 @@ describe("annotation", function() {
});
});
describe("AnnotationBorderStyle", function() {
it("should set and get a valid width", function() {
describe("AnnotationBorderStyle", function () {
it("should set and get a valid width", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setWidth(3);
expect(borderStyle.width).toEqual(3);
});
it("should not set and get an invalid width", function() {
it("should not set and get an invalid width", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setWidth("three");
expect(borderStyle.width).toEqual(1);
});
it("should set the width to zero, when the input is a `Name` (issue 10385)", function() {
it("should set the width to zero, when the input is a `Name` (issue 10385)", function () {
const borderStyleZero = new AnnotationBorderStyle();
borderStyleZero.setWidth(Name.get("0"));
const borderStyleFive = new AnnotationBorderStyle();
@ -360,56 +360,56 @@ describe("annotation", function() {
expect(borderStyleFive.width).toEqual(0);
});
it("should set and get a valid style", function() {
it("should set and get a valid style", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setStyle(Name.get("D"));
expect(borderStyle.style).toEqual(AnnotationBorderStyleType.DASHED);
});
it("should not set and get an invalid style", function() {
it("should not set and get an invalid style", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setStyle("Dashed");
expect(borderStyle.style).toEqual(AnnotationBorderStyleType.SOLID);
});
it("should set and get a valid dash array", function() {
it("should set and get a valid dash array", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setDashArray([1, 2, 3]);
expect(borderStyle.dashArray).toEqual([1, 2, 3]);
});
it("should not set and get an invalid dash array", function() {
it("should not set and get an invalid dash array", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setDashArray([0, 0]);
expect(borderStyle.dashArray).toEqual([3]);
});
it("should set and get a valid horizontal corner radius", function() {
it("should set and get a valid horizontal corner radius", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setHorizontalCornerRadius(3);
expect(borderStyle.horizontalCornerRadius).toEqual(3);
});
it("should not set and get an invalid horizontal corner radius", function() {
it("should not set and get an invalid horizontal corner radius", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setHorizontalCornerRadius("three");
expect(borderStyle.horizontalCornerRadius).toEqual(0);
});
it("should set and get a valid vertical corner radius", function() {
it("should set and get a valid vertical corner radius", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setVerticalCornerRadius(3);
expect(borderStyle.verticalCornerRadius).toEqual(3);
});
it("should not set and get an invalid vertical corner radius", function() {
it("should not set and get an invalid vertical corner radius", function () {
const borderStyle = new AnnotationBorderStyle();
borderStyle.setVerticalCornerRadius("three");
@ -417,34 +417,34 @@ describe("annotation", function() {
});
});
describe("MarkupAnnotation", function() {
describe("MarkupAnnotation", function () {
let dict, ref;
beforeAll(function(done) {
beforeAll(function (done) {
dict = new Dict();
ref = Ref.get(1, 0);
done();
});
afterAll(function() {
afterAll(function () {
dict = ref = null;
});
it("should set and get a valid creation date", function() {
it("should set and get a valid creation date", function () {
const markupAnnotation = new MarkupAnnotation({ dict, ref });
markupAnnotation.setCreationDate("D:20190422");
expect(markupAnnotation.creationDate).toEqual("D:20190422");
});
it("should not set and get an invalid creation date", function() {
it("should not set and get an invalid creation date", function () {
const markupAnnotation = new MarkupAnnotation({ dict, ref });
markupAnnotation.setCreationDate(undefined);
expect(markupAnnotation.creationDate).toEqual(null);
});
it("should not parse IRT/RT when not defined", function(done) {
it("should not parse IRT/RT when not defined", function (done) {
dict.set("Type", Name.get("Annot"));
dict.set("Subtype", Name.get("Text"));
@ -460,7 +460,7 @@ describe("annotation", function() {
);
});
it("should parse IRT and set default RT when not defined.", function(done) {
it("should parse IRT and set default RT when not defined.", function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -491,7 +491,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should parse IRT/RT for a group type", function(done) {
it("should parse IRT/RT for a group type", function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -548,7 +548,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should parse IRT/RT for a reply type", function(done) {
it("should parse IRT/RT for a reply type", function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -606,8 +606,8 @@ describe("annotation", function() {
});
});
describe("TextAnnotation", function() {
it("should not parse state model and state when not defined", function(done) {
describe("TextAnnotation", function () {
it("should not parse state model and state when not defined", function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -641,7 +641,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should correctly parse state model and state when defined", function(done) {
it("should correctly parse state model and state when defined", function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -676,8 +676,8 @@ describe("annotation", function() {
});
});
describe("LinkAnnotation", function() {
it("should correctly parse a URI action", function(done) {
describe("LinkAnnotation", function () {
it("should correctly parse a URI action", function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("URI"));
@ -710,7 +710,7 @@ describe("annotation", function() {
it(
"should correctly parse a URI action, where the URI entry " +
"is missing a protocol",
function(done) {
function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("URI"));
@ -744,7 +744,7 @@ describe("annotation", function() {
it(
"should correctly parse a URI action, where the URI entry " +
"has an incorrect encoding (bug 1122280)",
function(done) {
function (done) {
const actionStream = new StringStream(
"<<\n" +
"/Type /Action\n" +
@ -793,7 +793,7 @@ describe("annotation", function() {
}
);
it("should correctly parse a GoTo action", function(done) {
it("should correctly parse a GoTo action", function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoTo"));
@ -824,7 +824,7 @@ describe("annotation", function() {
it(
"should correctly parse a GoToR action, where the FileSpec entry " +
"is a string containing a relative URL",
function(done) {
function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR"));
@ -861,7 +861,7 @@ describe("annotation", function() {
it(
"should correctly parse a GoToR action, containing a relative URL, " +
'with the "docBaseUrl" parameter specified',
function(done) {
function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR"));
@ -898,7 +898,7 @@ describe("annotation", function() {
}
);
it("should correctly parse a GoToR action, with named destination", function(done) {
it("should correctly parse a GoToR action, with named destination", function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR"));
@ -928,7 +928,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should correctly parse a GoToR action, with explicit destination array", function(done) {
it("should correctly parse a GoToR action, with explicit destination array", function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("GoToR"));
@ -969,7 +969,7 @@ describe("annotation", function() {
it(
"should correctly parse a Launch action, where the FileSpec dict " +
'contains a relative URL, with the "docBaseUrl" parameter specified',
function(done) {
function (done) {
const fileSpecDict = new Dict();
fileSpecDict.set("Type", Name.get("FileSpec"));
fileSpecDict.set("F", "Part II/Part II.pdf");
@ -1015,7 +1015,7 @@ describe("annotation", function() {
it(
"should recover valid URLs from JavaScript actions having certain " +
"white-listed formats",
function(done) {
function (done) {
function checkJsAction(params) {
const jsEntry = params.jsEntry;
const expectedUrl = params.expectedUrl;
@ -1084,7 +1084,7 @@ describe("annotation", function() {
}
);
it("should correctly parse a Named action", function(done) {
it("should correctly parse a Named action", function (done) {
const actionDict = new Dict();
actionDict.set("Type", Name.get("Action"));
actionDict.set("S", Name.get("Named"));
@ -1112,7 +1112,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should correctly parse a simple Dest", function(done) {
it("should correctly parse a simple Dest", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -1135,7 +1135,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should correctly parse a simple Dest, with explicit destination array", function(done) {
it("should correctly parse a simple Dest, with explicit destination array", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -1173,7 +1173,7 @@ describe("annotation", function() {
it(
"should correctly parse a Dest, which violates the specification " +
"by containing a dictionary",
function(done) {
function (done) {
const destDict = new Dict();
destDict.set("Type", Name.get("Action"));
destDict.set("S", Name.get("GoTo"));
@ -1206,7 +1206,7 @@ describe("annotation", function() {
}
);
it("should not set quadpoints if not defined", function(done) {
it("should not set quadpoints if not defined", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -1226,7 +1226,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set quadpoints if defined", function(done) {
it("should set quadpoints if defined", function (done) {
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
annotationDict.set("Subtype", Name.get("Link"));
@ -1256,21 +1256,21 @@ describe("annotation", function() {
});
});
describe("WidgetAnnotation", function() {
describe("WidgetAnnotation", function () {
let widgetDict;
beforeEach(function(done) {
beforeEach(function (done) {
widgetDict = new Dict();
widgetDict.set("Type", Name.get("Annot"));
widgetDict.set("Subtype", Name.get("Widget"));
done();
});
afterEach(function() {
afterEach(function () {
widgetDict = null;
});
it("should handle unknown field names", function(done) {
it("should handle unknown field names", function (done) {
const widgetRef = Ref.get(20, 0);
const xref = new XRefMock([{ ref: widgetRef, data: widgetDict }]);
@ -1286,7 +1286,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should construct the field name when there are no ancestors", function(done) {
it("should construct the field name when there are no ancestors", function (done) {
widgetDict.set("T", "foo");
const widgetRef = Ref.get(21, 0);
@ -1304,7 +1304,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should construct the field name when there are ancestors", function(done) {
it("should construct the field name when there are ancestors", function (done) {
const firstParent = new Dict();
firstParent.set("T", "foo");
@ -1333,7 +1333,7 @@ describe("annotation", function() {
it(
"should construct the field name if a parent is not a dictionary " +
"(issue 8143)",
function(done) {
function (done) {
const parentDict = new Dict();
parentDict.set("Parent", null);
parentDict.set("T", "foo");
@ -1358,10 +1358,10 @@ describe("annotation", function() {
);
});
describe("TextWidgetAnnotation", function() {
describe("TextWidgetAnnotation", function () {
let textWidgetDict;
beforeEach(function(done) {
beforeEach(function (done) {
textWidgetDict = new Dict();
textWidgetDict.set("Type", Name.get("Annot"));
textWidgetDict.set("Subtype", Name.get("Widget"));
@ -1369,11 +1369,11 @@ describe("annotation", function() {
done();
});
afterEach(function() {
afterEach(function () {
textWidgetDict = null;
});
it("should handle unknown text alignment, maximum length and flags", function(done) {
it("should handle unknown text alignment, maximum length and flags", function (done) {
const textWidgetRef = Ref.get(124, 0);
const xref = new XRefMock([{ ref: textWidgetRef, data: textWidgetDict }]);
@ -1393,7 +1393,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should not set invalid text alignment, maximum length and flags", function(done) {
it("should not set invalid text alignment, maximum length and flags", function (done) {
textWidgetDict.set("Q", "center");
textWidgetDict.set("MaxLen", "five");
textWidgetDict.set("Ff", "readonly");
@ -1417,7 +1417,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set valid text alignment, maximum length and flags", function(done) {
it("should set valid text alignment, maximum length and flags", function (done) {
textWidgetDict.set("Q", 1);
textWidgetDict.set("MaxLen", 20);
textWidgetDict.set(
@ -1443,7 +1443,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should reject comb fields without a maximum length", function(done) {
it("should reject comb fields without a maximum length", function (done) {
textWidgetDict.set("Ff", AnnotationFieldFlag.COMB);
const textWidgetRef = Ref.get(46, 0);
@ -1461,7 +1461,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should accept comb fields with a maximum length", function(done) {
it("should accept comb fields with a maximum length", function (done) {
textWidgetDict.set("MaxLen", 20);
textWidgetDict.set("Ff", AnnotationFieldFlag.COMB);
@ -1480,7 +1480,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should only accept comb fields when the flags are valid", function(done) {
it("should only accept comb fields when the flags are valid", function (done) {
const invalidFieldFlags = [
AnnotationFieldFlag.MULTILINE,
AnnotationFieldFlag.PASSWORD,
@ -1528,10 +1528,10 @@ describe("annotation", function() {
});
});
describe("ButtonWidgetAnnotation", function() {
describe("ButtonWidgetAnnotation", function () {
let buttonWidgetDict;
beforeEach(function(done) {
beforeEach(function (done) {
buttonWidgetDict = new Dict();
buttonWidgetDict.set("Type", Name.get("Annot"));
buttonWidgetDict.set("Subtype", Name.get("Widget"));
@ -1539,11 +1539,11 @@ describe("annotation", function() {
done();
});
afterEach(function() {
afterEach(function () {
buttonWidgetDict = null;
});
it("should handle checkboxes with export value", function(done) {
it("should handle checkboxes with export value", function (done) {
buttonWidgetDict.set("V", Name.get("1"));
const appearanceStatesDict = new Dict();
@ -1574,7 +1574,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle checkboxes without export value", function(done) {
it("should handle checkboxes without export value", function (done) {
buttonWidgetDict.set("V", Name.get("1"));
const buttonWidgetRef = Ref.get(124, 0);
@ -1596,7 +1596,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle radio buttons with a field value", function(done) {
it("should handle radio buttons with a field value", function (done) {
const parentDict = new Dict();
parentDict.set("V", Name.get("1"));
@ -1630,7 +1630,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle radio buttons without a field value", function(done) {
it("should handle radio buttons without a field value", function (done) {
const normalAppearanceStateDict = new Dict();
normalAppearanceStateDict.set("2", null);
@ -1661,10 +1661,10 @@ describe("annotation", function() {
});
});
describe("ChoiceWidgetAnnotation", function() {
describe("ChoiceWidgetAnnotation", function () {
let choiceWidgetDict;
beforeEach(function(done) {
beforeEach(function (done) {
choiceWidgetDict = new Dict();
choiceWidgetDict.set("Type", Name.get("Annot"));
choiceWidgetDict.set("Subtype", Name.get("Widget"));
@ -1672,11 +1672,11 @@ describe("annotation", function() {
done();
});
afterEach(function() {
afterEach(function () {
choiceWidgetDict = null;
});
it("should handle missing option arrays", function(done) {
it("should handle missing option arrays", function (done) {
const choiceWidgetRef = Ref.get(122, 0);
const xref = new XRefMock([
{ ref: choiceWidgetRef, data: choiceWidgetDict },
@ -1694,7 +1694,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle option arrays with array elements", function(done) {
it("should handle option arrays with array elements", function (done) {
const optionBarRef = Ref.get(20, 0);
const optionBarStr = "Bar";
const optionOneRef = Ref.get(10, 0);
@ -1727,7 +1727,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle option arrays with string elements", function(done) {
it("should handle option arrays with string elements", function (done) {
const optionBarRef = Ref.get(10, 0);
const optionBarStr = "Bar";
@ -1757,7 +1757,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle inherited option arrays (issue 8094)", function(done) {
it("should handle inherited option arrays (issue 8094)", function (done) {
const options = [
["Value1", "Description1"],
["Value2", "Description2"],
@ -1789,7 +1789,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should sanitize display values in option arrays (issue 8947)", function(done) {
it("should sanitize display values in option arrays (issue 8947)", function (done) {
// The option value is a UTF-16BE string. The display value should be
// sanitized, but the export value should remain the same since that
// may be used as a unique identifier when exporting form values.
@ -1817,7 +1817,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle array field values", function(done) {
it("should handle array field values", function (done) {
const fieldValue = ["Foo", "Bar"];
choiceWidgetDict.set("V", fieldValue);
@ -1839,7 +1839,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle string field values", function(done) {
it("should handle string field values", function (done) {
const fieldValue = "Foo";
choiceWidgetDict.set("V", fieldValue);
@ -1861,7 +1861,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle unknown flags", function(done) {
it("should handle unknown flags", function (done) {
const choiceWidgetRef = Ref.get(166, 0);
const xref = new XRefMock([
{ ref: choiceWidgetRef, data: choiceWidgetDict },
@ -1881,7 +1881,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should not set invalid flags", function(done) {
it("should not set invalid flags", function (done) {
choiceWidgetDict.set("Ff", "readonly");
const choiceWidgetRef = Ref.get(165, 0);
@ -1903,7 +1903,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set valid flags", function(done) {
it("should set valid flags", function (done) {
choiceWidgetDict.set(
"Ff",
AnnotationFieldFlag.READONLY +
@ -1931,8 +1931,8 @@ describe("annotation", function() {
});
});
describe("LineAnnotation", function() {
it("should set the line coordinates", function(done) {
describe("LineAnnotation", function () {
it("should set the line coordinates", function (done) {
const lineDict = new Dict();
lineDict.set("Type", Name.get("Annot"));
lineDict.set("Subtype", Name.get("Line"));
@ -1954,8 +1954,8 @@ describe("annotation", function() {
});
});
describe("FileAttachmentAnnotation", function() {
it("should correctly parse a file attachment", function(done) {
describe("FileAttachmentAnnotation", function () {
it("should correctly parse a file attachment", function (done) {
const fileStream = new StringStream(
"<<\n" +
"/Type /EmbeddedFile\n" +
@ -2015,8 +2015,8 @@ describe("annotation", function() {
});
});
describe("PopupAnnotation", function() {
it("should inherit properties from its parent", function(done) {
describe("PopupAnnotation", function () {
it("should inherit properties from its parent", function (done) {
const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text"));
@ -2044,7 +2044,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle missing parent properties", function(done) {
it("should handle missing parent properties", function (done) {
const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text"));
@ -2073,7 +2073,7 @@ describe("annotation", function() {
it(
"should inherit the parent flags when the Popup is not viewable, " +
"but the parent is (PR 7352)",
function(done) {
function (done) {
const parentDict = new Dict();
parentDict.set("Type", Name.get("Annot"));
parentDict.set("Subtype", Name.get("Text"));
@ -2108,7 +2108,7 @@ describe("annotation", function() {
it(
"should correctly inherit Contents from group-master annotation " +
"if parent has ReplyType == Group",
function(done) {
function (done) {
const annotationRef = Ref.get(819, 0);
const annotationDict = new Dict();
annotationDict.set("Type", Name.get("Annot"));
@ -2165,8 +2165,8 @@ describe("annotation", function() {
);
});
describe("InkAnnotation", function() {
it("should handle a single ink list", function(done) {
describe("InkAnnotation", function () {
it("should handle a single ink list", function (done) {
const inkDict = new Dict();
inkDict.set("Type", Name.get("Annot"));
inkDict.set("Subtype", Name.get("Ink"));
@ -2193,7 +2193,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should handle multiple ink lists", function(done) {
it("should handle multiple ink lists", function (done) {
const inkDict = new Dict();
inkDict.set("Type", Name.get("Annot"));
inkDict.set("Subtype", Name.get("Ink"));
@ -2226,8 +2226,8 @@ describe("annotation", function() {
});
});
describe("HightlightAnnotation", function() {
it("should not set quadpoints if not defined", function(done) {
describe("HightlightAnnotation", function () {
it("should not set quadpoints if not defined", function (done) {
const highlightDict = new Dict();
highlightDict.set("Type", Name.get("Annot"));
highlightDict.set("Subtype", Name.get("Highlight"));
@ -2247,7 +2247,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set quadpoints if defined", function(done) {
it("should set quadpoints if defined", function (done) {
const highlightDict = new Dict();
highlightDict.set("Type", Name.get("Annot"));
highlightDict.set("Subtype", Name.get("Highlight"));
@ -2277,8 +2277,8 @@ describe("annotation", function() {
});
});
describe("UnderlineAnnotation", function() {
it("should not set quadpoints if not defined", function(done) {
describe("UnderlineAnnotation", function () {
it("should not set quadpoints if not defined", function (done) {
const underlineDict = new Dict();
underlineDict.set("Type", Name.get("Annot"));
underlineDict.set("Subtype", Name.get("Underline"));
@ -2298,7 +2298,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set quadpoints if defined", function(done) {
it("should set quadpoints if defined", function (done) {
const underlineDict = new Dict();
underlineDict.set("Type", Name.get("Annot"));
underlineDict.set("Subtype", Name.get("Underline"));
@ -2328,8 +2328,8 @@ describe("annotation", function() {
});
});
describe("SquigglyAnnotation", function() {
it("should not set quadpoints if not defined", function(done) {
describe("SquigglyAnnotation", function () {
it("should not set quadpoints if not defined", function (done) {
const squigglyDict = new Dict();
squigglyDict.set("Type", Name.get("Annot"));
squigglyDict.set("Subtype", Name.get("Squiggly"));
@ -2349,7 +2349,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set quadpoints if defined", function(done) {
it("should set quadpoints if defined", function (done) {
const squigglyDict = new Dict();
squigglyDict.set("Type", Name.get("Annot"));
squigglyDict.set("Subtype", Name.get("Squiggly"));
@ -2379,8 +2379,8 @@ describe("annotation", function() {
});
});
describe("StrikeOutAnnotation", function() {
it("should not set quadpoints if not defined", function(done) {
describe("StrikeOutAnnotation", function () {
it("should not set quadpoints if not defined", function (done) {
const strikeOutDict = new Dict();
strikeOutDict.set("Type", Name.get("Annot"));
strikeOutDict.set("Subtype", Name.get("StrikeOut"));
@ -2400,7 +2400,7 @@ describe("annotation", function() {
}, done.fail);
});
it("should set quadpoints if defined", function(done) {
it("should set quadpoints if defined", function (done) {
const strikeOutDict = new Dict();
strikeOutDict.set("Type", Name.get("Annot"));
strikeOutDict.set("Subtype", Name.get("StrikeOut"));

File diff suppressed because it is too large Load Diff

View File

@ -15,8 +15,8 @@
import { bidi } from "../../src/core/bidi.js";
describe("bidi", function() {
it("should mark text as RTL if more than 30% of text is RTL", function() {
describe("bidi", function () {
it("should mark text as RTL if more than 30% of text is RTL", function () {
// 33% of test text are RTL characters
var test = "\u0645\u0635\u0631 Egypt";
var result = "Egypt \u0631\u0635\u0645";
@ -26,7 +26,7 @@ describe("bidi", function() {
expect(bidiText.dir).toEqual("rtl");
});
it("should mark text as LTR if less than 30% of text is RTL", function() {
it("should mark text as LTR if less than 30% of text is RTL", function () {
var test = "Egypt is known as \u0645\u0635\u0631 in Arabic.";
var result = "Egypt is known as \u0631\u0635\u0645 in Arabic.";
var bidiText = bidi(test, -1, false);

View File

@ -23,7 +23,7 @@ import {
import { SEAC_ANALYSIS_ENABLED } from "../../src/core/fonts.js";
import { Stream } from "../../src/core/stream.js";
describe("CFFParser", function() {
describe("CFFParser", function () {
function createWithNullProto(obj) {
var result = Object.create(null);
for (var i in obj) {
@ -41,7 +41,7 @@ describe("CFFParser", function() {
var fontData, parser, cff;
beforeAll(function(done) {
beforeAll(function (done) {
// This example font comes from the CFF spec:
// http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf
var exampleFont =
@ -64,22 +64,22 @@ describe("CFFParser", function() {
done();
});
afterAll(function() {
afterAll(function () {
fontData = null;
});
beforeEach(function(done) {
beforeEach(function (done) {
parser = new CFFParser(fontData, {}, SEAC_ANALYSIS_ENABLED);
cff = parser.parse();
done();
});
afterEach(function(done) {
afterEach(function (done) {
parser = cff = null;
done();
});
it("parses header", function() {
it("parses header", function () {
var header = cff.header;
expect(header.major).toEqual(1);
expect(header.minor).toEqual(0);
@ -87,20 +87,20 @@ describe("CFFParser", function() {
expect(header.offSize).toEqual(1);
});
it("parses name index", function() {
it("parses name index", function () {
var names = cff.names;
expect(names.length).toEqual(1);
expect(names[0]).toEqual("ABCDEF+Times-Roman");
});
it("parses string index", function() {
it("parses string index", function () {
var strings = cff.strings;
expect(strings.count).toEqual(3);
expect(strings.get(0)).toEqual(".notdef");
expect(strings.get(391)).toEqual("001.007");
});
it("parses top dict", function() {
it("parses top dict", function () {
var topDict = cff.topDict;
// 391 version 392 FullName 393 FamilyName 389 Weight 28416 UniqueID
// -168 -218 1000 898 FontBBox 94 CharStrings 45 102 Private
@ -114,7 +114,7 @@ describe("CFFParser", function() {
expect(topDict.getByName("Private")).toEqual([45, 102]);
});
it("refuses to add topDict key with invalid value (bug 1068432)", function() {
it("refuses to add topDict key with invalid value (bug 1068432)", function () {
var topDict = cff.topDict;
var defaultValue = topDict.getByName("UnderlinePosition");
@ -125,7 +125,7 @@ describe("CFFParser", function() {
it(
"ignores reserved commands in parseDict, and refuses to add privateDict " +
"keys with invalid values (bug 1308536)",
function() {
function () {
// prettier-ignore
var bytes = new Uint8Array([
64, 39, 31, 30, 252, 114, 137, 115, 79, 30, 197, 119, 2, 99, 127, 6
@ -134,7 +134,7 @@ describe("CFFParser", function() {
var topDict = cff.topDict;
topDict.setByName("Private", [bytes.length, 0]);
var parsePrivateDict = function() {
var parsePrivateDict = function () {
parser.parsePrivateDict(topDict);
};
expect(parsePrivateDict).not.toThrow();
@ -144,7 +144,7 @@ describe("CFFParser", function() {
}
);
it("parses a CharString having cntrmask", function() {
it("parses a CharString having cntrmask", function () {
// prettier-ignore
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
@ -171,7 +171,7 @@ describe("CFFParser", function() {
expect(charStrings.get(0).length).toEqual(38);
});
it("parses a CharString endchar with 4 args w/seac enabled", function() {
it("parses a CharString endchar with 4 args w/seac enabled", function () {
const cffParser = new CFFParser(
fontData,
{},
@ -200,7 +200,7 @@ describe("CFFParser", function() {
expect(result.seacs[0][3]).toEqual(194);
});
it("parses a CharString endchar with 4 args w/seac disabled", function() {
it("parses a CharString endchar with 4 args w/seac disabled", function () {
const cffParser = new CFFParser(
fontData,
{},
@ -224,7 +224,7 @@ describe("CFFParser", function() {
expect(result.seacs.length).toEqual(0);
});
it("parses a CharString endchar no args", function() {
it("parses a CharString endchar no args", function () {
// prettier-ignore
var bytes = new Uint8Array([0, 1, // count
1, // offsetSize
@ -241,12 +241,12 @@ describe("CFFParser", function() {
expect(result.seacs.length).toEqual(0);
});
it("parses predefined charsets", function() {
it("parses predefined charsets", function () {
var charset = parser.parseCharsets(0, 0, null, true);
expect(charset.predefined).toEqual(true);
});
it("parses charset format 0", function() {
it("parses charset format 0", function () {
// The first three bytes make the offset large enough to skip predefined.
// prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, 0x00,
@ -262,7 +262,7 @@ describe("CFFParser", function() {
expect(charset.charset[1]).toEqual(2);
});
it("parses charset format 1", function() {
it("parses charset format 1", function () {
// The first three bytes make the offset large enough to skip predefined.
// prettier-ignore
var bytes = new Uint8Array([0x00, 0x00, 0x00,
@ -279,7 +279,7 @@ describe("CFFParser", function() {
expect(charset.charset).toEqual([0, 8, 9]);
});
it("parses charset format 2", function() {
it("parses charset format 2", function () {
// format 2 is the same as format 1 but the left is card16
// The first three bytes make the offset large enough to skip predefined.
// prettier-ignore
@ -297,7 +297,7 @@ describe("CFFParser", function() {
expect(charset.charset).toEqual([0, 8, 9]);
});
it("parses encoding format 0", function() {
it("parses encoding format 0", function () {
// The first two bytes make the offset large enough to skip predefined.
// prettier-ignore
var bytes = new Uint8Array([0x00, 0x00,
@ -310,7 +310,7 @@ describe("CFFParser", function() {
expect(encoding.encoding).toEqual(createWithNullProto({ 0x8: 1 }));
});
it("parses encoding format 1", function() {
it("parses encoding format 1", function () {
// The first two bytes make the offset large enough to skip predefined.
// prettier-ignore
var bytes = new Uint8Array([0x00, 0x00,
@ -326,7 +326,7 @@ describe("CFFParser", function() {
);
});
it("parses fdselect format 0", function() {
it("parses fdselect format 0", function () {
// prettier-ignore
var bytes = new Uint8Array([0x00, // format
0x00, // gid: 0 fd: 0
@ -339,7 +339,7 @@ describe("CFFParser", function() {
expect(fdSelect.format).toEqual(0);
});
it("parses fdselect format 3", function() {
it("parses fdselect format 3", function () {
// prettier-ignore
var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count
@ -356,7 +356,7 @@ describe("CFFParser", function() {
expect(fdSelect.format).toEqual(3);
});
it("parses invalid fdselect format 3 (bug 1146106)", function() {
it("parses invalid fdselect format 3 (bug 1146106)", function () {
// prettier-ignore
var bytes = new Uint8Array([0x03, // format
0x00, 0x02, // range count
@ -376,7 +376,7 @@ describe("CFFParser", function() {
// TODO fdArray
});
describe("CFFCompiler", function() {
describe("CFFCompiler", function () {
function testParser(bytes) {
bytes = new Uint8Array(bytes);
return new CFFParser(
@ -390,7 +390,7 @@ describe("CFFCompiler", function() {
);
}
it("encodes integers", function() {
it("encodes integers", function () {
var c = new CFFCompiler();
// all the examples from the spec
expect(c.encodeInteger(0)).toEqual([0x8b]);
@ -404,13 +404,13 @@ describe("CFFCompiler", function() {
expect(c.encodeInteger(-100000)).toEqual([0x1d, 0xff, 0xfe, 0x79, 0x60]);
});
it("encodes floats", function() {
it("encodes floats", function () {
var c = new CFFCompiler();
expect(c.encodeFloat(-2.25)).toEqual([0x1e, 0xe2, 0xa2, 0x5f]);
expect(c.encodeFloat(5e-11)).toEqual([0x1e, 0x5c, 0x11, 0xff]);
});
it("sanitizes name index", function() {
it("sanitizes name index", function () {
var c = new CFFCompiler();
var nameIndexCompiled = c.compileNameIndex(["[a"]);
var parser = testParser(nameIndexCompiled);
@ -429,7 +429,7 @@ describe("CFFCompiler", function() {
expect(names[0].length).toEqual(127);
});
it("compiles fdselect format 0", function() {
it("compiles fdselect format 0", function () {
var fdSelect = new CFFFDSelect(0, [3, 2, 1]);
var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect);
@ -441,7 +441,7 @@ describe("CFFCompiler", function() {
]);
});
it("compiles fdselect format 3", function() {
it("compiles fdselect format 3", function () {
var fdSelect = new CFFFDSelect(3, [0, 0, 1, 1]);
var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect);
@ -460,7 +460,7 @@ describe("CFFCompiler", function() {
]);
});
it("compiles fdselect format 3, single range", function() {
it("compiles fdselect format 3, single range", function () {
var fdSelect = new CFFFDSelect(3, [0, 0]);
var c = new CFFCompiler();
var out = c.compileFDSelect(fdSelect);
@ -476,7 +476,7 @@ describe("CFFCompiler", function() {
]);
});
it("compiles charset of CID font", function() {
it("compiles charset of CID font", function () {
var charset = new CFFCharset();
var c = new CFFCompiler();
var numGlyphs = 7;
@ -491,7 +491,7 @@ describe("CFFCompiler", function() {
]);
});
it("compiles charset of non CID font", function() {
it("compiles charset of non CID font", function () {
var charset = new CFFCharset(false, 0, ["space", "exclam"]);
var c = new CFFCompiler();
var numGlyphs = 3;

View File

@ -31,6 +31,6 @@ if (!isNodeJS) {
setVerbosityLevel(VerbosityLevel.ERRORS);
// Set the network stream factory for the unit-tests.
setPDFNetworkStreamFactory(function(params) {
setPDFNetworkStreamFactory(function (params) {
return new PDFNodeStream(params);
});

View File

@ -26,10 +26,10 @@ var cMapUrl = {
};
var cMapPacked = true;
describe("cmap", function() {
describe("cmap", function () {
var fetchBuiltInCMap;
beforeAll(function(done) {
beforeAll(function (done) {
// Allow CMap testing in Node.js, e.g. for Travis.
var CMapReaderFactory;
if (isNodeJS) {
@ -44,7 +44,7 @@ describe("cmap", function() {
});
}
fetchBuiltInCMap = function(name) {
fetchBuiltInCMap = function (name) {
return CMapReaderFactory.fetch({
name,
});
@ -52,11 +52,11 @@ describe("cmap", function() {
done();
});
afterAll(function() {
afterAll(function () {
fetchBuiltInCMap = null;
});
it("parses beginbfchar", function(done) {
it("parses beginbfchar", function (done) {
// prettier-ignore
var str = "2 beginbfchar\n" +
"<03> <00>\n" +
@ -65,17 +65,17 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00));
expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01));
expect(cmap.lookup(0x05)).toBeUndefined();
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses beginbfrange with range", function(done) {
it("parses beginbfrange with range", function (done) {
// prettier-ignore
var str = "1 beginbfrange\n" +
"<06> <0B> 0\n" +
@ -83,18 +83,18 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.lookup(0x05)).toBeUndefined();
expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00));
expect(cmap.lookup(0x0b)).toEqual(String.fromCharCode(0x05));
expect(cmap.lookup(0x0c)).toBeUndefined();
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses beginbfrange with array", function(done) {
it("parses beginbfrange with array", function (done) {
// prettier-ignore
var str = "1 beginbfrange\n" +
"<0D> <12> [ 0 1 2 3 4 5 ]\n" +
@ -102,18 +102,18 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.lookup(0x0c)).toBeUndefined();
expect(cmap.lookup(0x0d)).toEqual(0x00);
expect(cmap.lookup(0x12)).toEqual(0x05);
expect(cmap.lookup(0x13)).toBeUndefined();
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses begincidchar", function(done) {
it("parses begincidchar", function (done) {
// prettier-ignore
var str = "1 begincidchar\n" +
"<14> 0\n" +
@ -121,16 +121,16 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.lookup(0x14)).toEqual(0x00);
expect(cmap.lookup(0x15)).toBeUndefined();
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses begincidrange", function(done) {
it("parses begincidrange", function (done) {
// prettier-ignore
var str = "1 begincidrange\n" +
"<0016> <001B> 0\n" +
@ -138,18 +138,18 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.lookup(0x15)).toBeUndefined();
expect(cmap.lookup(0x16)).toEqual(0x00);
expect(cmap.lookup(0x1b)).toEqual(0x05);
expect(cmap.lookup(0x1c)).toBeUndefined();
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("decodes codespace ranges", function(done) {
it("decodes codespace ranges", function (done) {
// prettier-ignore
var str = "1 begincodespacerange\n" +
"<01> <02>\n" +
@ -158,7 +158,7 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
var c = {};
cmap.readCharCode(String.fromCharCode(1), 0, c);
expect(c.charcode).toEqual(1);
@ -168,11 +168,11 @@ describe("cmap", function() {
expect(c.length).toEqual(4);
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("decodes 4 byte codespace ranges", function(done) {
it("decodes 4 byte codespace ranges", function (done) {
// prettier-ignore
var str = "1 begincodespacerange\n" +
"<8EA1A1A1> <8EA1FEFE>\n" +
@ -180,18 +180,18 @@ describe("cmap", function() {
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
var c = {};
cmap.readCharCode(String.fromCharCode(0x8e, 0xa1, 0xa1, 0xa1), 0, c);
expect(c.charcode).toEqual(0x8ea1a1a1);
expect(c.length).toEqual(4);
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("read usecmap", function(done) {
it("read usecmap", function (done) {
var str = "/Adobe-Japan1-1 usecmap\n";
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({
@ -200,7 +200,7 @@ describe("cmap", function() {
useCMap: null,
});
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true);
expect(cmap.useCMap).not.toBeNull();
expect(cmap.builtInCMap).toBeFalsy();
@ -208,44 +208,44 @@ describe("cmap", function() {
expect(cmap.isIdentityCMap).toEqual(false);
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses cmapname", function(done) {
it("parses cmapname", function (done) {
var str = "/CMapName /Identity-H def\n";
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.name).toEqual("Identity-H");
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("parses wmode", function(done) {
it("parses wmode", function (done) {
var str = "/WMode 1 def\n";
var stream = new StringStream(str);
var cmapPromise = CMapFactory.create({ encoding: stream });
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap.vertical).toEqual(true);
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("loads built in cmap", function(done) {
it("loads built in cmap", function (done) {
var cmapPromise = CMapFactory.create({
encoding: Name.get("Adobe-Japan1-1"),
fetchBuiltInCMap,
useCMap: null,
});
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap instanceof CMap).toEqual(true);
expect(cmap.useCMap).toBeNull();
expect(cmap.builtInCMap).toBeTruthy();
@ -253,42 +253,42 @@ describe("cmap", function() {
expect(cmap.isIdentityCMap).toEqual(false);
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("loads built in identity cmap", function(done) {
it("loads built in identity cmap", function (done) {
var cmapPromise = CMapFactory.create({
encoding: Name.get("Identity-H"),
fetchBuiltInCMap,
useCMap: null,
});
cmapPromise
.then(function(cmap) {
.then(function (cmap) {
expect(cmap instanceof IdentityCMap).toEqual(true);
expect(cmap.vertical).toEqual(false);
expect(cmap.length).toEqual(0x10000);
expect(function() {
expect(function () {
return cmap.isIdentityCMap;
}).toThrow(new Error("should not access .isIdentityCMap"));
done();
})
.catch(function(reason) {
.catch(function (reason) {
done.fail(reason);
});
});
it("attempts to load a non-existent built-in CMap", function(done) {
it("attempts to load a non-existent built-in CMap", function (done) {
var cmapPromise = CMapFactory.create({
encoding: Name.get("null"),
fetchBuiltInCMap,
useCMap: null,
});
cmapPromise.then(
function() {
function () {
done.fail("No CMap should be loaded");
},
function(reason) {
function (reason) {
expect(reason instanceof Error).toEqual(true);
expect(reason.message).toEqual("Unknown CMap name: null");
done();
@ -296,7 +296,7 @@ describe("cmap", function() {
);
});
it("attempts to load a built-in CMap without the necessary API parameters", function(done) {
it("attempts to load a built-in CMap without the necessary API parameters", function (done) {
function tmpFetchBuiltInCMap(name) {
var CMapReaderFactory = isNodeJS
? new NodeCMapReaderFactory({})
@ -312,10 +312,10 @@ describe("cmap", function() {
useCMap: null,
});
cmapPromise.then(
function() {
function () {
done.fail("No CMap should be loaded");
},
function(reason) {
function (reason) {
expect(reason instanceof Error).toEqual(true);
expect(reason.message).toEqual(
'The CMap "baseUrl" parameter must be specified, ensure that ' +
@ -326,7 +326,7 @@ describe("cmap", function() {
);
});
it("attempts to load a built-in CMap with inconsistent API parameters", function(done) {
it("attempts to load a built-in CMap with inconsistent API parameters", function (done) {
function tmpFetchBuiltInCMap(name) {
let CMapReaderFactory;
if (isNodeJS) {
@ -351,10 +351,10 @@ describe("cmap", function() {
useCMap: null,
});
cmapPromise.then(
function() {
function () {
done.fail("No CMap should be loaded");
},
function(reason) {
function (reason) {
expect(reason instanceof Error).toEqual(true);
const message = reason.message;
expect(message.startsWith("Unable to load CMap at: ")).toEqual(true);

View File

@ -19,16 +19,16 @@ import { ColorSpace } from "../../src/core/colorspace.js";
import { PDFFunctionFactory } from "../../src/core/function.js";
import { XRefMock } from "./test_utils.js";
describe("colorspace", function() {
describe("ColorSpace", function() {
it("should be true if decode is not an array", function() {
describe("colorspace", function () {
describe("ColorSpace", function () {
it("should be true if decode is not an array", function () {
expect(ColorSpace.isDefaultDecode("string", 0)).toBeTruthy();
});
it("should be true if length of decode array is not correct", function() {
it("should be true if length of decode array is not correct", function () {
expect(ColorSpace.isDefaultDecode([0], 1)).toBeTruthy();
expect(ColorSpace.isDefaultDecode([0, 1, 0], 1)).toBeTruthy();
});
it("should be true if decode map matches the default decode map", function() {
it("should be true if decode map matches the default decode map", function () {
expect(ColorSpace.isDefaultDecode([], 0)).toBeTruthy();
expect(ColorSpace.isDefaultDecode([0, 0], 1)).toBeFalsy();
@ -46,8 +46,8 @@ describe("colorspace", function() {
});
});
describe("DeviceGrayCS", function() {
it("should handle the case when cs is a Name object", function() {
describe("DeviceGrayCS", function () {
it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceGray");
const xref = new XRefMock([
{
@ -92,7 +92,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeFalsy();
expect(testDest).toEqual(expectedDest);
});
it("should handle the case when cs is an indirect object", function() {
it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0);
const xref = new XRefMock([
{
@ -132,8 +132,8 @@ describe("colorspace", function() {
});
});
describe("DeviceRgbCS", function() {
it("should handle the case when cs is a Name object", function() {
describe("DeviceRgbCS", function () {
it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceRGB");
const xref = new XRefMock([
{
@ -184,7 +184,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeTruthy();
expect(testDest).toEqual(expectedDest);
});
it("should handle the case when cs is an indirect object", function() {
it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0);
const xref = new XRefMock([
{
@ -230,8 +230,8 @@ describe("colorspace", function() {
});
});
describe("DeviceCmykCS", function() {
it("should handle the case when cs is a Name object", function() {
describe("DeviceCmykCS", function () {
it("should handle the case when cs is a Name object", function () {
const cs = Name.get("DeviceCMYK");
const xref = new XRefMock([
{
@ -282,7 +282,7 @@ describe("colorspace", function() {
expect(colorSpace.isPassthrough(8)).toBeFalsy();
expect(testDest).toEqual(expectedDest);
});
it("should handle the case when cs is an indirect object", function() {
it("should handle the case when cs is an indirect object", function () {
const cs = Ref.get(10, 0);
const xref = new XRefMock([
{
@ -328,8 +328,8 @@ describe("colorspace", function() {
});
});
describe("CalGrayCS", function() {
it("should handle the case when cs is an array", function() {
describe("CalGrayCS", function () {
it("should handle the case when cs is an array", function () {
const params = new Dict();
params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]);
@ -381,8 +381,8 @@ describe("colorspace", function() {
});
});
describe("CalRGBCS", function() {
it("should handle the case when cs is an array", function() {
describe("CalRGBCS", function () {
it("should handle the case when cs is an array", function () {
const params = new Dict();
params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]);
@ -434,8 +434,8 @@ describe("colorspace", function() {
});
});
describe("LabCS", function() {
it("should handle the case when cs is an array", function() {
describe("LabCS", function () {
it("should handle the case when cs is an array", function () {
const params = new Dict();
params.set("WhitePoint", [1, 1, 1]);
params.set("BlackPoint", [0, 0, 0]);
@ -487,8 +487,8 @@ describe("colorspace", function() {
});
});
describe("IndexedCS", function() {
it("should handle the case when cs is an array", function() {
describe("IndexedCS", function () {
it("should handle the case when cs is an array", function () {
// prettier-ignore
const lookup = new Uint8Array([
23, 155, 35,
@ -534,8 +534,8 @@ describe("colorspace", function() {
});
});
describe("AlternateCS", function() {
it("should handle the case when cs is an array", function() {
describe("AlternateCS", function () {
it("should handle the case when cs is an array", function () {
const fnDict = new Dict();
fnDict.set("FunctionType", 4);
fnDict.set("Domain", [0.0, 1.0]);

View File

@ -22,9 +22,9 @@ import {
} from "../../src/core/core_utils.js";
import { XRefMock } from "./test_utils.js";
describe("core_utils", function() {
describe("getInheritableProperty", function() {
it("handles non-dictionary arguments", function() {
describe("core_utils", function () {
describe("getInheritableProperty", function () {
it("handles non-dictionary arguments", function () {
expect(getInheritableProperty({ dict: null, key: "foo" })).toEqual(
undefined
);
@ -33,7 +33,7 @@ describe("core_utils", function() {
);
});
it("handles dictionaries that do not contain the property", function() {
it("handles dictionaries that do not contain the property", function () {
// Empty dictionary.
const emptyDict = new Dict();
expect(getInheritableProperty({ dict: emptyDict, key: "foo" })).toEqual(
@ -48,7 +48,7 @@ describe("core_utils", function() {
);
});
it("fetches the property if it is not inherited", function() {
it("fetches the property if it is not inherited", function () {
const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]);
const dict = new Dict(xref);
@ -64,7 +64,7 @@ describe("core_utils", function() {
).toEqual(["qux", "quux"]);
});
it("fetches the property if it is inherited and present on one level", function() {
it("fetches the property if it is inherited and present on one level", function () {
const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]);
const firstDict = new Dict(xref);
@ -84,7 +84,7 @@ describe("core_utils", function() {
).toEqual(["qux", "quux"]);
});
it("fetches the property if it is inherited and present on multiple levels", function() {
it("fetches the property if it is inherited and present on multiple levels", function () {
const ref = Ref.get(10, 0);
const xref = new XRefMock([{ ref, data: "quux" }]);
const firstDict = new Dict(xref);
@ -122,7 +122,7 @@ describe("core_utils", function() {
]);
});
it("stops searching when the loop limit is reached", function() {
it("stops searching when the loop limit is reached", function () {
const dict = new Dict();
let currentDict = dict;
let parentDict = null;
@ -147,16 +147,16 @@ describe("core_utils", function() {
});
});
describe("toRomanNumerals", function() {
it("handles invalid arguments", function() {
describe("toRomanNumerals", function () {
it("handles invalid arguments", function () {
for (const input of ["foo", -1, 0]) {
expect(function() {
expect(function () {
toRomanNumerals(input);
}).toThrow(new Error("The number should be a positive integer."));
}
});
it("converts numbers to uppercase Roman numerals", function() {
it("converts numbers to uppercase Roman numerals", function () {
expect(toRomanNumerals(1)).toEqual("I");
expect(toRomanNumerals(6)).toEqual("VI");
expect(toRomanNumerals(7)).toEqual("VII");
@ -169,7 +169,7 @@ describe("core_utils", function() {
expect(toRomanNumerals(2019)).toEqual("MMXIX");
});
it("converts numbers to lowercase Roman numerals", function() {
it("converts numbers to lowercase Roman numerals", function () {
expect(toRomanNumerals(1, /* lowercase = */ true)).toEqual("i");
expect(toRomanNumerals(6, /* lowercase = */ true)).toEqual("vi");
expect(toRomanNumerals(7, /* lowercase = */ true)).toEqual("vii");
@ -183,13 +183,13 @@ describe("core_utils", function() {
});
});
describe("log2", function() {
it("handles values smaller than/equal to zero", function() {
describe("log2", function () {
it("handles values smaller than/equal to zero", function () {
expect(log2(0)).toEqual(0);
expect(log2(-1)).toEqual(0);
});
it("handles values larger than zero", function() {
it("handles values larger than zero", function () {
expect(log2(1)).toEqual(0);
expect(log2(2)).toEqual(1);
expect(log2(3)).toEqual(2);
@ -197,15 +197,15 @@ describe("core_utils", function() {
});
});
describe("isWhiteSpace", function() {
it("handles space characters", function() {
describe("isWhiteSpace", function () {
it("handles space characters", function () {
expect(isWhiteSpace(0x20)).toEqual(true);
expect(isWhiteSpace(0x09)).toEqual(true);
expect(isWhiteSpace(0x0d)).toEqual(true);
expect(isWhiteSpace(0x0a)).toEqual(true);
});
it("handles non-space characters", function() {
it("handles non-space characters", function () {
expect(isWhiteSpace(0x0b)).toEqual(false);
expect(isWhiteSpace(null)).toEqual(false);
expect(isWhiteSpace(undefined)).toEqual(false);

View File

@ -32,7 +32,7 @@ import {
stringToBytes,
} from "../../src/shared/util.js";
describe("crypto", function() {
describe("crypto", function () {
function hex2binary(s) {
var digits = "0123456789ABCDEF";
s = s.toUpperCase();
@ -50,43 +50,43 @@ describe("crypto", function() {
}
// RFC 1321, A.5 Test suite
describe("calculateMD5", function() {
it("should pass RFC 1321 test #1", function() {
describe("calculateMD5", function () {
it("should pass RFC 1321 test #1", function () {
var input, result, expected;
input = stringToBytes("");
result = calculateMD5(input, 0, input.length);
expected = hex2binary("d41d8cd98f00b204e9800998ecf8427e");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #2", function() {
it("should pass RFC 1321 test #2", function () {
var input, result, expected;
input = stringToBytes("a");
result = calculateMD5(input, 0, input.length);
expected = hex2binary("0cc175b9c0f1b6a831c399e269772661");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #3", function() {
it("should pass RFC 1321 test #3", function () {
var input, result, expected;
input = stringToBytes("abc");
result = calculateMD5(input, 0, input.length);
expected = hex2binary("900150983cd24fb0d6963f7d28e17f72");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #4", function() {
it("should pass RFC 1321 test #4", function () {
var input, result, expected;
input = stringToBytes("message digest");
result = calculateMD5(input, 0, input.length);
expected = hex2binary("f96b697d7cb7938d525a2f31aaf161d0");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #5", function() {
it("should pass RFC 1321 test #5", function () {
var input, result, expected;
input = stringToBytes("abcdefghijklmnopqrstuvwxyz");
result = calculateMD5(input, 0, input.length);
expected = hex2binary("c3fcd3d76192e4007dfb496cca67e13b");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #6", function() {
it("should pass RFC 1321 test #6", function () {
var input, result, expected;
input = stringToBytes(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@ -95,7 +95,7 @@ describe("crypto", function() {
expected = hex2binary("d174ab98d277d9f5a5611c2c9f419d9f");
expect(result).toEqual(expected);
});
it("should pass RFC 1321 test #7", function() {
it("should pass RFC 1321 test #7", function () {
var input, result, expected;
input = stringToBytes(
"123456789012345678901234567890123456789012345678" +
@ -108,8 +108,8 @@ describe("crypto", function() {
});
// http://www.freemedialibrary.com/index.php/RC4_test_vectors are used
describe("ARCFourCipher", function() {
it("should pass test #1", function() {
describe("ARCFourCipher", function () {
it("should pass test #1", function () {
var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef");
input = hex2binary("0123456789abcdef");
@ -118,7 +118,7 @@ describe("crypto", function() {
expected = hex2binary("75b7878099e0c596");
expect(result).toEqual(expected);
});
it("should pass test #2", function() {
it("should pass test #2", function () {
var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef");
input = hex2binary("0000000000000000");
@ -127,7 +127,7 @@ describe("crypto", function() {
expected = hex2binary("7494c2e7104b0879");
expect(result).toEqual(expected);
});
it("should pass test #3", function() {
it("should pass test #3", function () {
var key, input, result, expected, cipher;
key = hex2binary("0000000000000000");
input = hex2binary("0000000000000000");
@ -136,7 +136,7 @@ describe("crypto", function() {
expected = hex2binary("de188941a3375d3a");
expect(result).toEqual(expected);
});
it("should pass test #4", function() {
it("should pass test #4", function () {
var key, input, result, expected, cipher;
key = hex2binary("ef012345");
input = hex2binary("00000000000000000000");
@ -145,7 +145,7 @@ describe("crypto", function() {
expected = hex2binary("d6a141a7ec3c38dfbd61");
expect(result).toEqual(expected);
});
it("should pass test #5", function() {
it("should pass test #5", function () {
var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef");
input = hex2binary(
@ -188,7 +188,7 @@ describe("crypto", function() {
);
expect(result).toEqual(expected);
});
it("should pass test #6", function() {
it("should pass test #6", function () {
var key, input, result, expected, cipher;
key = hex2binary("fb029e3031323334");
input = hex2binary(
@ -205,7 +205,7 @@ describe("crypto", function() {
);
expect(result).toEqual(expected);
});
it("should pass test #7", function() {
it("should pass test #7", function () {
var key, input, result, expected, cipher;
key = hex2binary("0123456789abcdef");
input = hex2binary(
@ -220,8 +220,8 @@ describe("crypto", function() {
});
});
describe("calculateSHA256", function() {
it("should properly hash abc", function() {
describe("calculateSHA256", function () {
it("should properly hash abc", function () {
var input, result, expected;
input = stringToBytes("abc");
result = calculateSHA256(input, 0, input.length);
@ -230,7 +230,7 @@ describe("crypto", function() {
);
expect(result).toEqual(expected);
});
it("should properly hash a multiblock input", function() {
it("should properly hash a multiblock input", function () {
var input, result, expected;
input = stringToBytes(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
@ -243,8 +243,8 @@ describe("crypto", function() {
});
});
describe("calculateSHA384", function() {
it("should properly hash abc", function() {
describe("calculateSHA384", function () {
it("should properly hash abc", function () {
var input, result, expected;
input = stringToBytes("abc");
result = calculateSHA384(input, 0, input.length);
@ -254,7 +254,7 @@ describe("crypto", function() {
);
expect(result).toEqual(expected);
});
it("should properly hash a multiblock input", function() {
it("should properly hash a multiblock input", function () {
var input, result, expected;
input = stringToBytes(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" +
@ -270,8 +270,8 @@ describe("crypto", function() {
});
});
describe("calculateSHA512", function() {
it("should properly hash abc", function() {
describe("calculateSHA512", function () {
it("should properly hash abc", function () {
var input, result, expected;
input = stringToBytes("abc");
result = calculateSHA512(input, 0, input.length);
@ -282,7 +282,7 @@ describe("crypto", function() {
);
expect(result).toEqual(expected);
});
it("should properly hash a multiblock input", function() {
it("should properly hash a multiblock input", function () {
var input, result, expected;
input = stringToBytes(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" +
@ -299,9 +299,9 @@ describe("crypto", function() {
});
});
describe("AES128", function() {
describe("Encryption", function() {
it("should be able to encrypt a block", function() {
describe("AES128", function () {
describe("Encryption", function () {
it("should be able to encrypt a block", function () {
var input, key, result, expected, iv, cipher;
input = hex2binary("00112233445566778899aabbccddeeff");
key = hex2binary("000102030405060708090a0b0c0d0e0f");
@ -313,8 +313,8 @@ describe("crypto", function() {
});
});
describe("Decryption", function() {
it("should be able to decrypt a block with IV in stream", function() {
describe("Decryption", function () {
it("should be able to decrypt a block with IV in stream", function () {
var input, key, result, expected, cipher;
input = hex2binary(
"0000000000000000000000000000000069c4e0d86a7b0430d" +
@ -329,9 +329,9 @@ describe("crypto", function() {
});
});
describe("AES256", function() {
describe("Encryption", function() {
it("should be able to encrypt a block", function() {
describe("AES256", function () {
describe("Encryption", function () {
it("should be able to encrypt a block", function () {
var input, key, result, expected, iv, cipher;
input = hex2binary("00112233445566778899aabbccddeeff");
key = hex2binary(
@ -346,8 +346,8 @@ describe("crypto", function() {
});
});
describe("Decryption", function() {
it("should be able to decrypt a block with specified iv", function() {
describe("Decryption", function () {
it("should be able to decrypt a block with specified iv", function () {
var input, key, result, expected, cipher, iv;
input = hex2binary("8ea2b7ca516745bfeafc49904b496089");
key = hex2binary(
@ -360,7 +360,7 @@ describe("crypto", function() {
expected = hex2binary("00112233445566778899aabbccddeeff");
expect(result).toEqual(expected);
});
it("should be able to decrypt a block with IV in stream", function() {
it("should be able to decrypt a block with IV in stream", function () {
var input, key, result, expected, cipher;
input = hex2binary(
"000000000000000000000000000000008ea2b7ca516745bf" +
@ -378,8 +378,8 @@ describe("crypto", function() {
});
});
describe("PDF17Algorithm", function() {
it("should correctly check a user key", function() {
describe("PDF17Algorithm", function () {
it("should correctly check a user key", function () {
var password, userValidation, userPassword, alg, result;
alg = new PDF17();
password = new Uint8Array([117, 115, 101, 114]);
@ -393,7 +393,7 @@ describe("crypto", function() {
expect(result).toEqual(true);
});
it("should correctly check an owner key", function() {
it("should correctly check an owner key", function () {
var password, ownerValidation, ownerPassword, alg, result, uBytes;
alg = new PDF17();
password = new Uint8Array([111, 119, 110, 101, 114]);
@ -418,7 +418,7 @@ describe("crypto", function() {
expect(result).toEqual(true);
});
it("should generate a file encryption key from the user key", function() {
it("should generate a file encryption key from the user key", function () {
var password, userKeySalt, expected, alg, result, userEncryption;
alg = new PDF17();
password = new Uint8Array([117, 115, 101, 114]);
@ -437,7 +437,7 @@ describe("crypto", function() {
expect(result).toEqual(expected);
});
it("should generate a file encryption key from the owner key", function() {
it("should generate a file encryption key from the owner key", function () {
var password, ownerKeySalt, expected, alg, result, ownerEncryption;
var uBytes;
alg = new PDF17();
@ -464,8 +464,8 @@ describe("crypto", function() {
});
});
describe("PDF20Algorithm", function() {
it("should correctly check a user key", function() {
describe("PDF20Algorithm", function () {
it("should correctly check a user key", function () {
var password, userValidation, userPassword, alg, result;
alg = new PDF20();
password = new Uint8Array([117, 115, 101, 114]);
@ -479,7 +479,7 @@ describe("crypto", function() {
expect(result).toEqual(true);
});
it("should correctly check an owner key", function() {
it("should correctly check an owner key", function () {
var password, ownerValidation, ownerPassword, alg, result, uBytes;
alg = new PDF20();
password = new Uint8Array([111, 119, 110, 101, 114]);
@ -504,7 +504,7 @@ describe("crypto", function() {
expect(result).toEqual(true);
});
it("should generate a file encryption key from the user key", function() {
it("should generate a file encryption key from the user key", function () {
var password, userKeySalt, expected, alg, result, userEncryption;
alg = new PDF20();
password = new Uint8Array([117, 115, 101, 114]);
@ -523,7 +523,7 @@ describe("crypto", function() {
expect(result).toEqual(expected);
});
it("should generate a file encryption key from the owner key", function() {
it("should generate a file encryption key from the owner key", function () {
var password, ownerKeySalt, expected, alg, result, ownerEncryption;
var uBytes;
alg = new PDF20();
@ -551,7 +551,7 @@ describe("crypto", function() {
});
});
describe("CipherTransformFactory", function() {
describe("CipherTransformFactory", function () {
function buildDict(map) {
var dict = new Dict();
for (var key in map) {
@ -602,7 +602,7 @@ describe("CipherTransformFactory", function() {
var fileId1, fileId2, dict1, dict2;
var aes256Dict, aes256IsoDict, aes256BlankDict, aes256IsoBlankDict;
beforeAll(function(done) {
beforeAll(function (done) {
fileId1 = unescape("%F6%C6%AF%17%F3rR%8DRM%9A%80%D1%EF%DF%18");
fileId2 = unescape("%3CL_%3AD%96%AF@%9A%9D%B3%3Cx%1Cv%AC");
@ -741,61 +741,61 @@ describe("CipherTransformFactory", function() {
done();
});
afterAll(function() {
afterAll(function () {
fileId1 = fileId2 = dict1 = dict2 = null;
aes256Dict = aes256IsoDict = aes256BlankDict = aes256IsoBlankDict = null;
});
describe("#ctor", function() {
describe("AES256 Revision 5", function() {
it("should accept user password", function(done) {
describe("#ctor", function () {
describe("AES256 Revision 5", function () {
it("should accept user password", function (done) {
ensurePasswordCorrect(done, aes256Dict, fileId1, "user");
});
it("should accept owner password", function(done) {
it("should accept owner password", function (done) {
ensurePasswordCorrect(done, aes256Dict, fileId1, "owner");
});
it("should not accept blank password", function(done) {
it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, aes256Dict, fileId1);
});
it("should not accept wrong password", function(done) {
it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, aes256Dict, fileId1, "wrong");
});
it("should accept blank password", function(done) {
it("should accept blank password", function (done) {
ensurePasswordCorrect(done, aes256BlankDict, fileId1);
});
});
describe("AES256 Revision 6", function() {
it("should accept user password", function(done) {
describe("AES256 Revision 6", function () {
it("should accept user password", function (done) {
ensurePasswordCorrect(done, aes256IsoDict, fileId1, "user");
});
it("should accept owner password", function(done) {
it("should accept owner password", function (done) {
ensurePasswordCorrect(done, aes256IsoDict, fileId1, "owner");
});
it("should not accept blank password", function(done) {
it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, aes256IsoDict, fileId1);
});
it("should not accept wrong password", function(done) {
it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, aes256IsoDict, fileId1, "wrong");
});
it("should accept blank password", function(done) {
it("should accept blank password", function (done) {
ensurePasswordCorrect(done, aes256IsoBlankDict, fileId1);
});
});
it("should accept user password", function(done) {
it("should accept user password", function (done) {
ensurePasswordCorrect(done, dict1, fileId1, "123456");
});
it("should accept owner password", function(done) {
it("should accept owner password", function (done) {
ensurePasswordCorrect(done, dict1, fileId1, "654321");
});
it("should not accept blank password", function(done) {
it("should not accept blank password", function (done) {
ensurePasswordNeeded(done, dict1, fileId1);
});
it("should not accept wrong password", function(done) {
it("should not accept wrong password", function (done) {
ensurePasswordIncorrect(done, dict1, fileId1, "wrong");
});
it("should accept blank password", function(done) {
it("should accept blank password", function (done) {
ensurePasswordCorrect(done, dict2, fileId2);
});
});

View File

@ -28,7 +28,7 @@ function getTopLeftPixel(canvasContext) {
};
}
describe("custom canvas rendering", function() {
describe("custom canvas rendering", function () {
const transparentGetDocumentParams = buildGetDocumentParams(
"transparent.pdf"
);
@ -37,7 +37,7 @@ describe("custom canvas rendering", function() {
let loadingTask;
let page;
beforeAll(function(done) {
beforeAll(function (done) {
if (isNodeJS) {
CanvasFactory = new NodeCanvasFactory();
} else {
@ -45,23 +45,23 @@ describe("custom canvas rendering", function() {
}
loadingTask = getDocument(transparentGetDocumentParams);
loadingTask.promise
.then(function(doc) {
.then(function (doc) {
return doc.getPage(1);
})
.then(function(data) {
.then(function (data) {
page = data;
done();
})
.catch(done.fail);
});
afterAll(function(done) {
afterAll(function (done) {
CanvasFactory = null;
page = null;
loadingTask.destroy().then(done);
});
it("renders to canvas with a default white background", function(done) {
it("renders to canvas with a default white background", function (done) {
var viewport = page.getViewport({ scale: 1 });
var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
@ -70,7 +70,7 @@ describe("custom canvas rendering", function() {
viewport,
});
renderTask.promise
.then(function() {
.then(function () {
expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({
r: 255,
g: 255,
@ -83,7 +83,7 @@ describe("custom canvas rendering", function() {
.catch(done.fail);
});
it("renders to canvas with a custom background", function(done) {
it("renders to canvas with a custom background", function (done) {
var viewport = page.getViewport({ scale: 1 });
var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
@ -93,7 +93,7 @@ describe("custom canvas rendering", function() {
background: "rgba(255,0,0,1.0)",
});
renderTask.promise
.then(function() {
.then(function () {
expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({
r: 255,
g: 0,

View File

@ -58,37 +58,37 @@ function withZlib(isZlibRequired, callback) {
return promise;
}
describe("SVGGraphics", function() {
describe("SVGGraphics", function () {
var loadingTask;
var page;
beforeAll(function(done) {
beforeAll(function (done) {
loadingTask = getDocument(
buildGetDocumentParams("xobject-image.pdf", {
nativeImageDecoderSupport: NativeImageDecoding.DISPLAY,
})
);
loadingTask.promise.then(function(doc) {
doc.getPage(1).then(function(firstPage) {
loadingTask.promise.then(function (doc) {
doc.getPage(1).then(function (firstPage) {
page = firstPage;
done();
});
});
});
afterAll(function(done) {
afterAll(function (done) {
loadingTask.destroy().then(done);
});
describe("paintImageXObject", function() {
describe("paintImageXObject", function () {
function getSVGImage() {
var svgGfx;
return page
.getOperatorList()
.then(function(opList) {
.then(function (opList) {
var forceDataSchema = true;
svgGfx = new SVGGraphics(page.commonObjs, page.objs, forceDataSchema);
return svgGfx.loadDependencies(opList);
})
.then(function() {
.then(function () {
var svgImg;
// A mock to steal the svg:image element from paintInlineImageXObject.
var elementContainer = {
@ -114,7 +114,7 @@ describe("SVGGraphics", function() {
});
}
it('should fail require("zlib") unless in Node.js', function() {
it('should fail require("zlib") unless in Node.js', function () {
function testFunc() {
__non_webpack_require__("zlib");
}
@ -129,12 +129,12 @@ describe("SVGGraphics", function() {
}
});
it("should produce a reasonably small svg:image", function(done) {
it("should produce a reasonably small svg:image", function (done) {
if (!isNodeJS) {
pending("zlib.deflateSync is not supported in non-Node environments.");
}
withZlib(true, getSVGImage)
.then(function(svgImg) {
.then(function (svgImg) {
expect(svgImg.nodeName).toBe("svg:image");
expect(svgImg.getAttributeNS(null, "width")).toBe("200px");
expect(svgImg.getAttributeNS(null, "height")).toBe("100px");
@ -150,9 +150,9 @@ describe("SVGGraphics", function() {
.then(done, done.fail);
});
it("should be able to produce a svg:image without zlib", function(done) {
it("should be able to produce a svg:image without zlib", function (done) {
withZlib(false, getSVGImage)
.then(function(svgImg) {
.then(function (svgImg) {
expect(svgImg.nodeName).toBe("svg:image");
expect(svgImg.getAttributeNS(null, "width")).toBe("200px");
expect(svgImg.getAttributeNS(null, "height")).toBe("100px");

View File

@ -23,32 +23,32 @@ import {
} from "../../src/display/display_utils.js";
import { isNodeJS } from "../../src/shared/is_node.js";
describe("display_utils", function() {
describe("DOMCanvasFactory", function() {
describe("display_utils", function () {
describe("DOMCanvasFactory", function () {
let canvasFactory;
beforeAll(function(done) {
beforeAll(function (done) {
canvasFactory = new DOMCanvasFactory();
done();
});
afterAll(function() {
afterAll(function () {
canvasFactory = null;
});
it("`create` should throw an error if the dimensions are invalid", function() {
it("`create` should throw an error if the dimensions are invalid", function () {
// Invalid width.
expect(function() {
expect(function () {
return canvasFactory.create(-1, 1);
}).toThrow(new Error("Invalid canvas size"));
// Invalid height.
expect(function() {
expect(function () {
return canvasFactory.create(1, -1);
}).toThrow(new Error("Invalid canvas size"));
});
it("`create` should return a canvas if the dimensions are valid", function() {
it("`create` should return a canvas if the dimensions are valid", function () {
if (isNodeJS) {
pending("Document is not supported in Node.js.");
}
@ -60,29 +60,29 @@ describe("display_utils", function() {
expect(canvas.height).toBe(40);
});
it("`reset` should throw an error if no canvas is provided", function() {
it("`reset` should throw an error if no canvas is provided", function () {
const canvasAndContext = { canvas: null, context: null };
expect(function() {
expect(function () {
return canvasFactory.reset(canvasAndContext, 20, 40);
}).toThrow(new Error("Canvas is not specified"));
});
it("`reset` should throw an error if the dimensions are invalid", function() {
it("`reset` should throw an error if the dimensions are invalid", function () {
const canvasAndContext = { canvas: "foo", context: "bar" };
// Invalid width.
expect(function() {
expect(function () {
return canvasFactory.reset(canvasAndContext, -1, 1);
}).toThrow(new Error("Invalid canvas size"));
// Invalid height.
expect(function() {
expect(function () {
return canvasFactory.reset(canvasAndContext, 1, -1);
}).toThrow(new Error("Invalid canvas size"));
});
it("`reset` should alter the canvas/context if the dimensions are valid", function() {
it("`reset` should alter the canvas/context if the dimensions are valid", function () {
if (isNodeJS) {
pending("Document is not supported in Node.js.");
}
@ -97,13 +97,13 @@ describe("display_utils", function() {
expect(canvas.height).toBe(80);
});
it("`destroy` should throw an error if no canvas is provided", function() {
expect(function() {
it("`destroy` should throw an error if no canvas is provided", function () {
expect(function () {
return canvasFactory.destroy({});
}).toThrow(new Error("Canvas is not specified"));
});
it("`destroy` should clear the canvas/context", function() {
it("`destroy` should clear the canvas/context", function () {
if (isNodeJS) {
pending("Document is not supported in Node.js.");
}
@ -117,31 +117,31 @@ describe("display_utils", function() {
});
});
describe("DOMSVGFactory", function() {
describe("DOMSVGFactory", function () {
let svgFactory;
beforeAll(function(done) {
beforeAll(function (done) {
svgFactory = new DOMSVGFactory();
done();
});
afterAll(function() {
afterAll(function () {
svgFactory = null;
});
it("`create` should throw an error if the dimensions are invalid", function() {
it("`create` should throw an error if the dimensions are invalid", function () {
// Invalid width.
expect(function() {
expect(function () {
return svgFactory.create(-1, 0);
}).toThrow(new Error("Invalid SVG dimensions"));
// Invalid height.
expect(function() {
expect(function () {
return svgFactory.create(0, -1);
}).toThrow(new Error("Invalid SVG dimensions"));
});
it("`create` should return an SVG element if the dimensions are valid", function() {
it("`create` should return an SVG element if the dimensions are valid", function () {
if (isNodeJS) {
pending("Document is not supported in Node.js.");
}
@ -155,13 +155,13 @@ describe("display_utils", function() {
expect(svg.getAttribute("viewBox")).toBe("0 0 20 40");
});
it("`createElement` should throw an error if the type is not a string", function() {
expect(function() {
it("`createElement` should throw an error if the type is not a string", function () {
expect(function () {
return svgFactory.createElement(true);
}).toThrow(new Error("Invalid SVG element type"));
});
it("`createElement` should return an SVG element if the type is valid", function() {
it("`createElement` should return an SVG element if the type is valid", function () {
if (isNodeJS) {
pending("Document is not supported in Node.js.");
}
@ -171,55 +171,55 @@ describe("display_utils", function() {
});
});
describe("getFilenameFromUrl", function() {
it("should get the filename from an absolute URL", function() {
describe("getFilenameFromUrl", function () {
it("should get the filename from an absolute URL", function () {
const url = "https://server.org/filename.pdf";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
});
it("should get the filename from a relative URL", function() {
it("should get the filename from a relative URL", function () {
const url = "../../filename.pdf";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
});
it("should get the filename from a URL with an anchor", function() {
it("should get the filename from a URL with an anchor", function () {
const url = "https://server.org/filename.pdf#foo";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
});
it("should get the filename from a URL with query parameters", function() {
it("should get the filename from a URL with query parameters", function () {
const url = "https://server.org/filename.pdf?foo=bar";
expect(getFilenameFromUrl(url)).toEqual("filename.pdf");
});
});
describe("isValidFetchUrl", function() {
it("handles invalid Fetch URLs", function() {
describe("isValidFetchUrl", function () {
it("handles invalid Fetch URLs", function () {
expect(isValidFetchUrl(null)).toEqual(false);
expect(isValidFetchUrl(100)).toEqual(false);
expect(isValidFetchUrl("foo")).toEqual(false);
expect(isValidFetchUrl("/foo", 100)).toEqual(false);
});
it("handles relative Fetch URLs", function() {
it("handles relative Fetch URLs", function () {
expect(isValidFetchUrl("/foo", "file://www.example.com")).toEqual(false);
expect(isValidFetchUrl("/foo", "http://www.example.com")).toEqual(true);
});
it("handles unsupported Fetch protocols", function() {
it("handles unsupported Fetch protocols", function () {
expect(isValidFetchUrl("file://www.example.com")).toEqual(false);
expect(isValidFetchUrl("ftp://www.example.com")).toEqual(false);
});
it("handles supported Fetch protocols", function() {
it("handles supported Fetch protocols", function () {
expect(isValidFetchUrl("http://www.example.com")).toEqual(true);
expect(isValidFetchUrl("https://www.example.com")).toEqual(true);
});
});
describe("PDFDateString", function() {
describe("toDateObject", function() {
it("converts PDF date strings to JavaScript `Date` objects", function() {
describe("PDFDateString", function () {
describe("toDateObject", function () {
it("converts PDF date strings to JavaScript `Date` objects", function () {
const expectations = {
undefined: null,
null: null,

Some files were not shown because too many files have changed in this diff Show More