mirror of
https://github.com/mozilla/pdf.js.git
synced 2025-04-26 01:58:06 +02:00
Enable auto-formatting of the entire code-base using Prettier (issue 11444)
Note that Prettier, purposely, has only limited [configuration options](https://prettier.io/docs/en/options.html). The configuration file is based on [the one in `mozilla central`](https://searchfox.org/mozilla-central/source/.prettierrc) with just a few additions (to avoid future breakage if the defaults ever changes). Prettier is being used for a couple of reasons: - To be consistent with `mozilla-central`, where Prettier is already in use across the tree. - To ensure a *consistent* coding style everywhere, which is automatically enforced during linting (since Prettier is used as an ESLint plugin). This thus ends "all" formatting disussions once and for all, removing the need for review comments on most stylistic matters. Many ESLint options are now redundant, and I've tried my best to remove all the now unnecessary options (but I may have missed some). Note also that since Prettier considers the `printWidth` option as a guide, rather than a hard rule, this patch resorts to a small hack in the ESLint config to ensure that *comments* won't become too long. *Please note:* This patch is generated automatically, by appending the `--fix` argument to the ESLint call used in the `gulp lint` task. It will thus require some additional clean-up, which will be done in a *separate* commit. (On a more personal note, I'll readily admit that some of the changes Prettier makes are *extremely* ugly. However, in the name of consistency we'll probably have to live with that.)
This commit is contained in:
parent
8ec1dfde49
commit
de36b2aaba
205 changed files with 40024 additions and 31859 deletions
|
@ -14,17 +14,28 @@
|
|||
*/
|
||||
|
||||
import {
|
||||
AbortException, arrayByteLength, arraysToBytes, createPromiseCapability,
|
||||
getVerbosityLevel, info, InvalidPDFException, MissingPDFException,
|
||||
PasswordException, setVerbosityLevel, UnexpectedResponseException,
|
||||
UnknownErrorException, UNSUPPORTED_FEATURES, VerbosityLevel, warn
|
||||
} from '../shared/util';
|
||||
import { clearPrimitiveCaches, Ref } from './primitives';
|
||||
import { LocalPdfManager, NetworkPdfManager } from './pdf_manager';
|
||||
import { isNodeJS } from '../shared/is_node';
|
||||
import { MessageHandler } from '../shared/message_handler';
|
||||
import { PDFWorkerStream } from './worker_stream';
|
||||
import { XRefParseException } from './core_utils';
|
||||
AbortException,
|
||||
arrayByteLength,
|
||||
arraysToBytes,
|
||||
createPromiseCapability,
|
||||
getVerbosityLevel,
|
||||
info,
|
||||
InvalidPDFException,
|
||||
MissingPDFException,
|
||||
PasswordException,
|
||||
setVerbosityLevel,
|
||||
UnexpectedResponseException,
|
||||
UnknownErrorException,
|
||||
UNSUPPORTED_FEATURES,
|
||||
VerbosityLevel,
|
||||
warn,
|
||||
} from "../shared/util";
|
||||
import { clearPrimitiveCaches, Ref } from "./primitives";
|
||||
import { LocalPdfManager, NetworkPdfManager } from "./pdf_manager";
|
||||
import { isNodeJS } from "../shared/is_node";
|
||||
import { MessageHandler } from "../shared/message_handler";
|
||||
import { PDFWorkerStream } from "./worker_stream";
|
||||
import { XRefParseException } from "./core_utils";
|
||||
|
||||
var WorkerTask = (function WorkerTaskClosure() {
|
||||
function WorkerTask(name) {
|
||||
|
@ -48,7 +59,7 @@ var WorkerTask = (function WorkerTaskClosure() {
|
|||
|
||||
ensureNotTerminated() {
|
||||
if (this.terminated) {
|
||||
throw new Error('Worker task was terminated');
|
||||
throw new Error("Worker task was terminated");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
@ -59,7 +70,7 @@ var WorkerTask = (function WorkerTaskClosure() {
|
|||
var WorkerMessageHandler = {
|
||||
setup(handler, port) {
|
||||
var testMessageProcessed = false;
|
||||
handler.on('test', function wphSetupTest(data) {
|
||||
handler.on("test", function wphSetupTest(data) {
|
||||
if (testMessageProcessed) {
|
||||
return; // we already processed 'test' message once
|
||||
}
|
||||
|
@ -67,21 +78,21 @@ var WorkerMessageHandler = {
|
|||
|
||||
// check if Uint8Array can be sent to worker
|
||||
if (!(data instanceof Uint8Array)) {
|
||||
handler.send('test', null);
|
||||
handler.send("test", null);
|
||||
return;
|
||||
}
|
||||
// making sure postMessage transfers are working
|
||||
const supportTransfers = data[0] === 255;
|
||||
handler.postMessageTransfers = supportTransfers;
|
||||
|
||||
handler.send('test', { supportTransfers, });
|
||||
handler.send("test", { supportTransfers });
|
||||
});
|
||||
|
||||
handler.on('configure', function wphConfigure(data) {
|
||||
handler.on("configure", function wphConfigure(data) {
|
||||
setVerbosityLevel(data.verbosity);
|
||||
});
|
||||
|
||||
handler.on('GetDocRequest', function wphSetupDoc(data) {
|
||||
handler.on("GetDocRequest", function wphSetupDoc(data) {
|
||||
return WorkerMessageHandler.createDocumentHandler(data, port);
|
||||
});
|
||||
},
|
||||
|
@ -96,16 +107,19 @@ var WorkerMessageHandler = {
|
|||
|
||||
const apiVersion = docParams.apiVersion;
|
||||
const workerVersion =
|
||||
typeof PDFJSDev !== 'undefined' && !PDFJSDev.test('TESTING') ?
|
||||
PDFJSDev.eval('BUNDLE_VERSION') : null;
|
||||
typeof PDFJSDev !== "undefined" && !PDFJSDev.test("TESTING")
|
||||
? PDFJSDev.eval("BUNDLE_VERSION")
|
||||
: null;
|
||||
if (apiVersion !== workerVersion) {
|
||||
throw new Error(`The API version "${apiVersion}" does not match ` +
|
||||
`the Worker version "${workerVersion}".`);
|
||||
throw new Error(
|
||||
`The API version "${apiVersion}" does not match ` +
|
||||
`the Worker version "${workerVersion}".`
|
||||
);
|
||||
}
|
||||
|
||||
var docId = docParams.docId;
|
||||
var docBaseUrl = docParams.docBaseUrl;
|
||||
var workerHandlerName = docParams.docId + '_worker';
|
||||
var workerHandlerName = docParams.docId + "_worker";
|
||||
var handler = new MessageHandler(workerHandlerName, docId, port);
|
||||
|
||||
// Ensure that postMessage transfers are always correctly enabled/disabled,
|
||||
|
@ -114,7 +128,7 @@ var WorkerMessageHandler = {
|
|||
|
||||
function ensureNotTerminated() {
|
||||
if (terminated) {
|
||||
throw new Error('Worker was terminated');
|
||||
throw new Error("Worker was terminated");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -129,21 +143,21 @@ var WorkerMessageHandler = {
|
|||
}
|
||||
|
||||
async function loadDocument(recoveryMode) {
|
||||
await pdfManager.ensureDoc('checkHeader');
|
||||
await pdfManager.ensureDoc('parseStartXRef');
|
||||
await pdfManager.ensureDoc('parse', [recoveryMode]);
|
||||
await pdfManager.ensureDoc("checkHeader");
|
||||
await pdfManager.ensureDoc("parseStartXRef");
|
||||
await pdfManager.ensureDoc("parse", [recoveryMode]);
|
||||
|
||||
if (!recoveryMode) {
|
||||
// Check that at least the first page can be successfully loaded,
|
||||
// since otherwise the XRef table is definitely not valid.
|
||||
await pdfManager.ensureDoc('checkFirstPage');
|
||||
await pdfManager.ensureDoc("checkFirstPage");
|
||||
}
|
||||
|
||||
const [numPages, fingerprint] = await Promise.all([
|
||||
pdfManager.ensureDoc('numPages'),
|
||||
pdfManager.ensureDoc('fingerprint'),
|
||||
pdfManager.ensureDoc("numPages"),
|
||||
pdfManager.ensureDoc("fingerprint"),
|
||||
]);
|
||||
return { numPages, fingerprint, };
|
||||
return { numPages, fingerprint };
|
||||
}
|
||||
|
||||
function getPdfManager(data, evaluatorOptions) {
|
||||
|
@ -153,8 +167,13 @@ var WorkerMessageHandler = {
|
|||
var source = data.source;
|
||||
if (source.data) {
|
||||
try {
|
||||
pdfManager = new LocalPdfManager(docId, source.data, source.password,
|
||||
evaluatorOptions, docBaseUrl);
|
||||
pdfManager = new LocalPdfManager(
|
||||
docId,
|
||||
source.data,
|
||||
source.password,
|
||||
evaluatorOptions,
|
||||
docBaseUrl
|
||||
);
|
||||
pdfManagerCapability.resolve(pdfManager);
|
||||
} catch (ex) {
|
||||
pdfManagerCapability.reject(ex);
|
||||
|
@ -162,7 +181,8 @@ var WorkerMessageHandler = {
|
|||
return pdfManagerCapability.promise;
|
||||
}
|
||||
|
||||
var pdfStream, cachedChunks = [];
|
||||
var pdfStream,
|
||||
cachedChunks = [];
|
||||
try {
|
||||
pdfStream = new PDFWorkerStream(handler);
|
||||
} catch (ex) {
|
||||
|
@ -171,55 +191,68 @@ var WorkerMessageHandler = {
|
|||
}
|
||||
|
||||
var fullRequest = pdfStream.getFullReader();
|
||||
fullRequest.headersReady.then(function () {
|
||||
if (!fullRequest.isRangeSupported) {
|
||||
return;
|
||||
}
|
||||
fullRequest.headersReady
|
||||
.then(function() {
|
||||
if (!fullRequest.isRangeSupported) {
|
||||
return;
|
||||
}
|
||||
|
||||
// We don't need auto-fetch when streaming is enabled.
|
||||
var disableAutoFetch = source.disableAutoFetch ||
|
||||
fullRequest.isStreamingSupported;
|
||||
pdfManager = new NetworkPdfManager(docId, pdfStream, {
|
||||
msgHandler: handler,
|
||||
password: source.password,
|
||||
length: fullRequest.contentLength,
|
||||
disableAutoFetch,
|
||||
rangeChunkSize: source.rangeChunkSize,
|
||||
}, evaluatorOptions, docBaseUrl);
|
||||
// There may be a chance that `pdfManager` is not initialized
|
||||
// for first few runs of `readchunk` block of code. Be sure
|
||||
// to send all cached chunks, if any, to chunked_stream via
|
||||
// pdf_manager.
|
||||
for (let i = 0; i < cachedChunks.length; i++) {
|
||||
pdfManager.sendProgressiveData(cachedChunks[i]);
|
||||
}
|
||||
// We don't need auto-fetch when streaming is enabled.
|
||||
var disableAutoFetch =
|
||||
source.disableAutoFetch || fullRequest.isStreamingSupported;
|
||||
pdfManager = new NetworkPdfManager(
|
||||
docId,
|
||||
pdfStream,
|
||||
{
|
||||
msgHandler: handler,
|
||||
password: source.password,
|
||||
length: fullRequest.contentLength,
|
||||
disableAutoFetch,
|
||||
rangeChunkSize: source.rangeChunkSize,
|
||||
},
|
||||
evaluatorOptions,
|
||||
docBaseUrl
|
||||
);
|
||||
// There may be a chance that `pdfManager` is not initialized
|
||||
// for first few runs of `readchunk` block of code. Be sure
|
||||
// to send all cached chunks, if any, to chunked_stream via
|
||||
// pdf_manager.
|
||||
for (let i = 0; i < cachedChunks.length; i++) {
|
||||
pdfManager.sendProgressiveData(cachedChunks[i]);
|
||||
}
|
||||
|
||||
cachedChunks = [];
|
||||
pdfManagerCapability.resolve(pdfManager);
|
||||
cancelXHRs = null;
|
||||
}).catch(function (reason) {
|
||||
pdfManagerCapability.reject(reason);
|
||||
cancelXHRs = null;
|
||||
});
|
||||
cachedChunks = [];
|
||||
pdfManagerCapability.resolve(pdfManager);
|
||||
cancelXHRs = null;
|
||||
})
|
||||
.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');
|
||||
warn("reported HTTP length is different from actual");
|
||||
}
|
||||
// the data is array, instantiating directly from it
|
||||
try {
|
||||
pdfManager = new LocalPdfManager(docId, pdfFile, source.password,
|
||||
evaluatorOptions, docBaseUrl);
|
||||
pdfManager = new LocalPdfManager(
|
||||
docId,
|
||||
pdfFile,
|
||||
source.password,
|
||||
evaluatorOptions,
|
||||
docBaseUrl
|
||||
);
|
||||
pdfManagerCapability.resolve(pdfManager);
|
||||
} catch (ex) {
|
||||
pdfManagerCapability.reject(ex);
|
||||
}
|
||||
cachedChunks = [];
|
||||
};
|
||||
var readPromise = new Promise(function (resolve, reject) {
|
||||
var readChunk = function (chunk) {
|
||||
var readPromise = new Promise(function(resolve, reject) {
|
||||
var readChunk = function(chunk) {
|
||||
try {
|
||||
ensureNotTerminated();
|
||||
if (chunk.done) {
|
||||
|
@ -233,7 +266,7 @@ var WorkerMessageHandler = {
|
|||
var data = chunk.value;
|
||||
loaded += arrayByteLength(data);
|
||||
if (!fullRequest.isStreamingSupported) {
|
||||
handler.send('DocProgress', {
|
||||
handler.send("DocProgress", {
|
||||
loaded,
|
||||
total: Math.max(loaded, fullRequest.contentLength || 0),
|
||||
});
|
||||
|
@ -252,7 +285,7 @@ var WorkerMessageHandler = {
|
|||
};
|
||||
fullRequest.read().then(readChunk, reject);
|
||||
});
|
||||
readPromise.catch(function (e) {
|
||||
readPromise.catch(function(e) {
|
||||
pdfManagerCapability.reject(e);
|
||||
cancelXHRs = null;
|
||||
});
|
||||
|
@ -267,7 +300,7 @@ var WorkerMessageHandler = {
|
|||
function setupDoc(data) {
|
||||
function onSuccess(doc) {
|
||||
ensureNotTerminated();
|
||||
handler.send('GetDoc', { pdfInfo: doc, });
|
||||
handler.send("GetDoc", { pdfInfo: doc });
|
||||
}
|
||||
|
||||
function onFailure(ex) {
|
||||
|
@ -277,43 +310,54 @@ var WorkerMessageHandler = {
|
|||
var task = new WorkerTask(`PasswordException: response ${ex.code}`);
|
||||
startWorkerTask(task);
|
||||
|
||||
handler.sendWithPromise('PasswordRequest', ex).then(function(data) {
|
||||
finishWorkerTask(task);
|
||||
pdfManager.updatePassword(data.password);
|
||||
pdfManagerReady();
|
||||
}).catch(function() {
|
||||
finishWorkerTask(task);
|
||||
handler.send('DocException', ex);
|
||||
});
|
||||
} else if (ex instanceof InvalidPDFException ||
|
||||
ex instanceof MissingPDFException ||
|
||||
ex instanceof UnexpectedResponseException ||
|
||||
ex instanceof UnknownErrorException) {
|
||||
handler.send('DocException', ex);
|
||||
handler
|
||||
.sendWithPromise("PasswordRequest", ex)
|
||||
.then(function(data) {
|
||||
finishWorkerTask(task);
|
||||
pdfManager.updatePassword(data.password);
|
||||
pdfManagerReady();
|
||||
})
|
||||
.catch(function() {
|
||||
finishWorkerTask(task);
|
||||
handler.send("DocException", ex);
|
||||
});
|
||||
} else if (
|
||||
ex instanceof InvalidPDFException ||
|
||||
ex instanceof MissingPDFException ||
|
||||
ex instanceof UnexpectedResponseException ||
|
||||
ex instanceof UnknownErrorException
|
||||
) {
|
||||
handler.send("DocException", ex);
|
||||
} else {
|
||||
handler.send('DocException',
|
||||
new UnknownErrorException(ex.message, ex.toString()));
|
||||
handler.send(
|
||||
"DocException",
|
||||
new UnknownErrorException(ex.message, ex.toString())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function pdfManagerReady() {
|
||||
ensureNotTerminated();
|
||||
|
||||
loadDocument(false).then(onSuccess, function loadFailure(ex) {
|
||||
ensureNotTerminated();
|
||||
|
||||
// Try again with recoveryMode == true
|
||||
if (!(ex instanceof XRefParseException)) {
|
||||
onFailure(ex);
|
||||
return;
|
||||
}
|
||||
pdfManager.requestLoadedStream();
|
||||
pdfManager.onLoadedStream().then(function() {
|
||||
loadDocument(false).then(
|
||||
onSuccess,
|
||||
function loadFailure(ex) {
|
||||
ensureNotTerminated();
|
||||
|
||||
loadDocument(true).then(onSuccess, onFailure);
|
||||
});
|
||||
}, onFailure);
|
||||
// Try again with recoveryMode == true
|
||||
if (!(ex instanceof XRefParseException)) {
|
||||
onFailure(ex);
|
||||
return;
|
||||
}
|
||||
pdfManager.requestLoadedStream();
|
||||
pdfManager.onLoadedStream().then(function() {
|
||||
ensureNotTerminated();
|
||||
|
||||
loadDocument(true).then(onSuccess, onFailure);
|
||||
});
|
||||
},
|
||||
onFailure
|
||||
);
|
||||
}
|
||||
|
||||
ensureNotTerminated();
|
||||
|
@ -327,28 +371,32 @@ var WorkerMessageHandler = {
|
|||
isEvalSupported: data.isEvalSupported,
|
||||
};
|
||||
|
||||
getPdfManager(data, evaluatorOptions).then(function (newPdfManager) {
|
||||
if (terminated) {
|
||||
// We were in a process of setting up the manager, but it got
|
||||
// terminated in the middle.
|
||||
newPdfManager.terminate(new AbortException('Worker was terminated.'));
|
||||
throw new Error('Worker was terminated');
|
||||
}
|
||||
pdfManager = newPdfManager;
|
||||
getPdfManager(data, evaluatorOptions)
|
||||
.then(function(newPdfManager) {
|
||||
if (terminated) {
|
||||
// We were in a process of setting up the manager, but it got
|
||||
// terminated in the middle.
|
||||
newPdfManager.terminate(
|
||||
new AbortException("Worker was terminated.")
|
||||
);
|
||||
throw new Error("Worker was terminated");
|
||||
}
|
||||
pdfManager = newPdfManager;
|
||||
|
||||
pdfManager.onLoadedStream().then(function(stream) {
|
||||
handler.send('DataLoaded', { length: stream.bytes.byteLength, });
|
||||
});
|
||||
}).then(pdfManagerReady, onFailure);
|
||||
pdfManager.onLoadedStream().then(function(stream) {
|
||||
handler.send("DataLoaded", { length: stream.bytes.byteLength });
|
||||
});
|
||||
})
|
||||
.then(pdfManagerReady, onFailure);
|
||||
}
|
||||
|
||||
handler.on('GetPage', function wphSetupGetPage(data) {
|
||||
handler.on("GetPage", function wphSetupGetPage(data) {
|
||||
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'),
|
||||
pdfManager.ensure(page, "rotate"),
|
||||
pdfManager.ensure(page, "ref"),
|
||||
pdfManager.ensure(page, "userUnit"),
|
||||
pdfManager.ensure(page, "view"),
|
||||
]).then(function([rotate, ref, userUnit, view]) {
|
||||
return {
|
||||
rotate,
|
||||
|
@ -360,201 +408,206 @@ var WorkerMessageHandler = {
|
|||
});
|
||||
});
|
||||
|
||||
handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
|
||||
handler.on("GetPageIndex", function wphSetupGetPageIndex(data) {
|
||||
var ref = Ref.get(data.ref.num, data.ref.gen);
|
||||
var catalog = pdfManager.pdfDocument.catalog;
|
||||
return catalog.getPageIndex(ref);
|
||||
});
|
||||
|
||||
handler.on('GetDestinations',
|
||||
function wphSetupGetDestinations(data) {
|
||||
return pdfManager.ensureCatalog('destinations');
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetDestination',
|
||||
function wphSetupGetDestination(data) {
|
||||
return pdfManager.ensureCatalog('getDestination', [data.id]);
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetPageLabels',
|
||||
function wphSetupGetPageLabels(data) {
|
||||
return pdfManager.ensureCatalog('pageLabels');
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetPageLayout', function wphSetupGetPageLayout(data) {
|
||||
return pdfManager.ensureCatalog('pageLayout');
|
||||
handler.on("GetDestinations", function wphSetupGetDestinations(data) {
|
||||
return pdfManager.ensureCatalog("destinations");
|
||||
});
|
||||
|
||||
handler.on('GetPageMode', function wphSetupGetPageMode(data) {
|
||||
return pdfManager.ensureCatalog('pageMode');
|
||||
handler.on("GetDestination", function wphSetupGetDestination(data) {
|
||||
return pdfManager.ensureCatalog("getDestination", [data.id]);
|
||||
});
|
||||
|
||||
handler.on('GetViewerPreferences', function(data) {
|
||||
return pdfManager.ensureCatalog('viewerPreferences');
|
||||
handler.on("GetPageLabels", function wphSetupGetPageLabels(data) {
|
||||
return pdfManager.ensureCatalog("pageLabels");
|
||||
});
|
||||
|
||||
handler.on('GetOpenActionDestination', function(data) {
|
||||
return pdfManager.ensureCatalog('openActionDestination');
|
||||
handler.on("GetPageLayout", function wphSetupGetPageLayout(data) {
|
||||
return pdfManager.ensureCatalog("pageLayout");
|
||||
});
|
||||
|
||||
handler.on('GetAttachments',
|
||||
function wphSetupGetAttachments(data) {
|
||||
return pdfManager.ensureCatalog('attachments');
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetJavaScript',
|
||||
function wphSetupGetJavaScript(data) {
|
||||
return pdfManager.ensureCatalog('javaScript');
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetOutline',
|
||||
function wphSetupGetOutline(data) {
|
||||
return pdfManager.ensureCatalog('documentOutline');
|
||||
}
|
||||
);
|
||||
|
||||
handler.on('GetPermissions', function(data) {
|
||||
return pdfManager.ensureCatalog('permissions');
|
||||
handler.on("GetPageMode", function wphSetupGetPageMode(data) {
|
||||
return pdfManager.ensureCatalog("pageMode");
|
||||
});
|
||||
|
||||
handler.on('GetMetadata',
|
||||
function wphSetupGetMetadata(data) {
|
||||
return Promise.all([pdfManager.ensureDoc('documentInfo'),
|
||||
pdfManager.ensureCatalog('metadata')]);
|
||||
}
|
||||
);
|
||||
handler.on("GetViewerPreferences", function(data) {
|
||||
return pdfManager.ensureCatalog("viewerPreferences");
|
||||
});
|
||||
|
||||
handler.on('GetData', function wphSetupGetData(data) {
|
||||
handler.on("GetOpenActionDestination", function(data) {
|
||||
return pdfManager.ensureCatalog("openActionDestination");
|
||||
});
|
||||
|
||||
handler.on("GetAttachments", function wphSetupGetAttachments(data) {
|
||||
return pdfManager.ensureCatalog("attachments");
|
||||
});
|
||||
|
||||
handler.on("GetJavaScript", function wphSetupGetJavaScript(data) {
|
||||
return pdfManager.ensureCatalog("javaScript");
|
||||
});
|
||||
|
||||
handler.on("GetOutline", function wphSetupGetOutline(data) {
|
||||
return pdfManager.ensureCatalog("documentOutline");
|
||||
});
|
||||
|
||||
handler.on("GetPermissions", function(data) {
|
||||
return pdfManager.ensureCatalog("permissions");
|
||||
});
|
||||
|
||||
handler.on("GetMetadata", function wphSetupGetMetadata(data) {
|
||||
return Promise.all([
|
||||
pdfManager.ensureDoc("documentInfo"),
|
||||
pdfManager.ensureCatalog("metadata"),
|
||||
]);
|
||||
});
|
||||
|
||||
handler.on("GetData", function wphSetupGetData(data) {
|
||||
pdfManager.requestLoadedStream();
|
||||
return pdfManager.onLoadedStream().then(function(stream) {
|
||||
return stream.bytes;
|
||||
});
|
||||
});
|
||||
|
||||
handler.on('GetStats',
|
||||
function wphSetupGetStats(data) {
|
||||
return pdfManager.pdfDocument.xref.stats;
|
||||
}
|
||||
);
|
||||
handler.on("GetStats", function wphSetupGetStats(data) {
|
||||
return pdfManager.pdfDocument.xref.stats;
|
||||
});
|
||||
|
||||
handler.on('GetAnnotations', function({ pageIndex, intent, }) {
|
||||
handler.on("GetAnnotations", function({ pageIndex, intent }) {
|
||||
return pdfManager.getPage(pageIndex).then(function(page) {
|
||||
return page.getAnnotationsData(intent);
|
||||
});
|
||||
});
|
||||
|
||||
handler.on('GetOperatorList', function wphSetupRenderPage(data, sink) {
|
||||
handler.on(
|
||||
"GetOperatorList",
|
||||
function wphSetupRenderPage(data, sink) {
|
||||
var pageIndex = data.pageIndex;
|
||||
pdfManager.getPage(pageIndex).then(function(page) {
|
||||
var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
|
||||
startWorkerTask(task);
|
||||
|
||||
// NOTE: Keep this condition in sync with the `info` helper function.
|
||||
const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;
|
||||
|
||||
// Pre compile the pdf page and fetch the fonts/images.
|
||||
page
|
||||
.getOperatorList({
|
||||
handler,
|
||||
sink,
|
||||
task,
|
||||
intent: data.intent,
|
||||
renderInteractiveForms: data.renderInteractiveForms,
|
||||
})
|
||||
.then(
|
||||
function(operatorListInfo) {
|
||||
finishWorkerTask(task);
|
||||
|
||||
if (start) {
|
||||
info(
|
||||
`page=${pageIndex + 1} - getOperatorList: time=` +
|
||||
`${Date.now() - start}ms, len=${operatorListInfo.length}`
|
||||
);
|
||||
}
|
||||
sink.close();
|
||||
},
|
||||
function(reason) {
|
||||
finishWorkerTask(task);
|
||||
if (task.terminated) {
|
||||
return; // ignoring errors from the terminated thread
|
||||
}
|
||||
// For compatibility with older behavior, generating unknown
|
||||
// unsupported feature notification on errors.
|
||||
handler.send("UnsupportedFeature", {
|
||||
featureId: UNSUPPORTED_FEATURES.unknown,
|
||||
});
|
||||
|
||||
sink.error(reason);
|
||||
|
||||
// TODO: Should `reason` be re-thrown here (currently that casues
|
||||
// "Uncaught exception: ..." messages in the console)?
|
||||
}
|
||||
);
|
||||
});
|
||||
},
|
||||
this
|
||||
);
|
||||
|
||||
handler.on("GetTextContent", function wphExtractText(data, sink) {
|
||||
var pageIndex = data.pageIndex;
|
||||
sink.onPull = function(desiredSize) {};
|
||||
sink.onCancel = function(reason) {};
|
||||
|
||||
pdfManager.getPage(pageIndex).then(function(page) {
|
||||
var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);
|
||||
var task = new WorkerTask("GetTextContent: page " + pageIndex);
|
||||
startWorkerTask(task);
|
||||
|
||||
// NOTE: Keep this condition in sync with the `info` helper function.
|
||||
const start = (verbosity >= VerbosityLevel.INFOS ? Date.now() : 0);
|
||||
const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;
|
||||
|
||||
// Pre compile the pdf page and fetch the fonts/images.
|
||||
page.getOperatorList({
|
||||
handler,
|
||||
sink,
|
||||
task,
|
||||
intent: data.intent,
|
||||
renderInteractiveForms: data.renderInteractiveForms,
|
||||
}).then(function(operatorListInfo) {
|
||||
finishWorkerTask(task);
|
||||
page
|
||||
.extractTextContent({
|
||||
handler,
|
||||
task,
|
||||
sink,
|
||||
normalizeWhitespace: data.normalizeWhitespace,
|
||||
combineTextItems: data.combineTextItems,
|
||||
})
|
||||
.then(
|
||||
function() {
|
||||
finishWorkerTask(task);
|
||||
|
||||
if (start) {
|
||||
info(`page=${pageIndex + 1} - getOperatorList: time=` +
|
||||
`${Date.now() - start}ms, len=${operatorListInfo.length}`);
|
||||
}
|
||||
sink.close();
|
||||
}, function(reason) {
|
||||
finishWorkerTask(task);
|
||||
if (task.terminated) {
|
||||
return; // ignoring errors from the terminated thread
|
||||
}
|
||||
// For compatibility with older behavior, generating unknown
|
||||
// unsupported feature notification on errors.
|
||||
handler.send('UnsupportedFeature',
|
||||
{ featureId: UNSUPPORTED_FEATURES.unknown, });
|
||||
if (start) {
|
||||
info(
|
||||
`page=${pageIndex + 1} - getTextContent: time=` +
|
||||
`${Date.now() - start}ms`
|
||||
);
|
||||
}
|
||||
sink.close();
|
||||
},
|
||||
function(reason) {
|
||||
finishWorkerTask(task);
|
||||
if (task.terminated) {
|
||||
return; // ignoring errors from the terminated thread
|
||||
}
|
||||
sink.error(reason);
|
||||
|
||||
sink.error(reason);
|
||||
|
||||
// TODO: Should `reason` be re-thrown here (currently that casues
|
||||
// "Uncaught exception: ..." messages in the console)?
|
||||
});
|
||||
});
|
||||
}, this);
|
||||
|
||||
handler.on('GetTextContent', function wphExtractText(data, sink) {
|
||||
var pageIndex = data.pageIndex;
|
||||
sink.onPull = function (desiredSize) { };
|
||||
sink.onCancel = function (reason) { };
|
||||
|
||||
pdfManager.getPage(pageIndex).then(function(page) {
|
||||
var task = new WorkerTask('GetTextContent: page ' + pageIndex);
|
||||
startWorkerTask(task);
|
||||
|
||||
// NOTE: Keep this condition in sync with the `info` helper function.
|
||||
const start = (verbosity >= VerbosityLevel.INFOS ? Date.now() : 0);
|
||||
|
||||
page.extractTextContent({
|
||||
handler,
|
||||
task,
|
||||
sink,
|
||||
normalizeWhitespace: data.normalizeWhitespace,
|
||||
combineTextItems: data.combineTextItems,
|
||||
}).then(function() {
|
||||
finishWorkerTask(task);
|
||||
|
||||
if (start) {
|
||||
info(`page=${pageIndex + 1} - getTextContent: time=` +
|
||||
`${Date.now() - start}ms`);
|
||||
}
|
||||
sink.close();
|
||||
}, function (reason) {
|
||||
finishWorkerTask(task);
|
||||
if (task.terminated) {
|
||||
return; // ignoring errors from the terminated thread
|
||||
}
|
||||
sink.error(reason);
|
||||
|
||||
// TODO: Should `reason` be re-thrown here (currently that casues
|
||||
// "Uncaught exception: ..." messages in the console)?
|
||||
});
|
||||
// TODO: Should `reason` be re-thrown here (currently that casues
|
||||
// "Uncaught exception: ..." messages in the console)?
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
handler.on('FontFallback', function(data) {
|
||||
handler.on("FontFallback", function(data) {
|
||||
return pdfManager.fontFallback(data.id, handler);
|
||||
});
|
||||
|
||||
handler.on('Cleanup', function wphCleanup(data) {
|
||||
handler.on("Cleanup", function wphCleanup(data) {
|
||||
return pdfManager.cleanup();
|
||||
});
|
||||
|
||||
handler.on('Terminate', function wphTerminate(data) {
|
||||
handler.on("Terminate", function wphTerminate(data) {
|
||||
terminated = true;
|
||||
if (pdfManager) {
|
||||
pdfManager.terminate(new AbortException('Worker was terminated.'));
|
||||
pdfManager.terminate(new AbortException("Worker was terminated."));
|
||||
pdfManager = null;
|
||||
}
|
||||
if (cancelXHRs) {
|
||||
cancelXHRs(new AbortException('Worker was terminated.'));
|
||||
cancelXHRs(new AbortException("Worker was terminated."));
|
||||
}
|
||||
clearPrimitiveCaches();
|
||||
|
||||
var waitOn = [];
|
||||
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();
|
||||
|
@ -562,31 +615,33 @@ var WorkerMessageHandler = {
|
|||
});
|
||||
});
|
||||
|
||||
handler.on('Ready', function wphReady(data) {
|
||||
handler.on("Ready", function wphReady(data) {
|
||||
setupDoc(docParams);
|
||||
docParams = null; // we don't need docParams anymore -- saving memory.
|
||||
});
|
||||
return workerHandlerName;
|
||||
},
|
||||
initializeFromPort(port) {
|
||||
var handler = new MessageHandler('worker', 'main', port);
|
||||
var handler = new MessageHandler("worker", "main", port);
|
||||
WorkerMessageHandler.setup(handler, port);
|
||||
handler.send('ready', null);
|
||||
handler.send("ready", null);
|
||||
},
|
||||
};
|
||||
|
||||
function isMessagePort(maybePort) {
|
||||
return typeof maybePort.postMessage === 'function' &&
|
||||
('onmessage' in maybePort);
|
||||
return (
|
||||
typeof maybePort.postMessage === "function" && "onmessage" in maybePort
|
||||
);
|
||||
}
|
||||
|
||||
// Worker thread (and not node.js)?
|
||||
if (typeof window === 'undefined' && !isNodeJS &&
|
||||
typeof self !== 'undefined' && isMessagePort(self)) {
|
||||
if (
|
||||
typeof window === "undefined" &&
|
||||
!isNodeJS &&
|
||||
typeof self !== "undefined" &&
|
||||
isMessagePort(self)
|
||||
) {
|
||||
WorkerMessageHandler.initializeFromPort(self);
|
||||
}
|
||||
|
||||
export {
|
||||
WorkerTask,
|
||||
WorkerMessageHandler,
|
||||
};
|
||||
export { WorkerTask, WorkerMessageHandler };
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue