pdf.js/src/core/worker.js

457 lines
15 KiB
JavaScript
Raw Normal View History

2011-10-26 10:18:22 +09:00
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
2012-09-01 07:48:21 +09:00
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2014-01-16 06:28:31 +09:00
/* globals error, globalScope, InvalidPDFException, info,
MissingPDFException, PasswordException, PDFJS, Promise,
UnknownErrorException, NetworkManager, LocalPdfManager,
NetworkPdfManager, XRefParseException, LegacyPromise,
isInt, PasswordResponses, MessageHandler, Ref, RANGE_CHUNK_SIZE */
2011-10-26 10:18:22 +09:00
'use strict';
var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
2011-10-29 03:23:30 +09:00
setup: function wphSetup(handler) {
2013-02-07 08:19:29 +09:00
var pdfManager;
2011-10-09 17:37:53 +09:00
2013-02-07 08:19:29 +09:00
function loadDocument(recoveryMode) {
var loadDocumentPromise = new LegacyPromise();
2013-02-07 08:19:29 +09:00
var parseSuccess = function parseSuccess() {
var numPagesPromise = pdfManager.ensureDoc('numPages');
var fingerprintPromise = pdfManager.ensureDoc('fingerprint');
2013-02-07 08:19:29 +09:00
var outlinePromise = pdfManager.ensureCatalog('documentOutline');
var infoPromise = pdfManager.ensureDoc('documentInfo');
2013-02-07 08:19:29 +09:00
var metadataPromise = pdfManager.ensureCatalog('metadata');
var encryptedPromise = pdfManager.ensureXRef('encrypt');
var javaScriptPromise = pdfManager.ensureCatalog('javaScript');
2013-04-19 02:41:33 +09:00
Promise.all([numPagesPromise, fingerprintPromise, outlinePromise,
2013-02-07 08:19:29 +09:00
infoPromise, metadataPromise, encryptedPromise,
javaScriptPromise]).then(
function onDocReady(results) {
var doc = {
numPages: results[0],
fingerprint: results[1],
outline: results[2],
info: results[3],
metadata: results[4],
encrypted: !!results[5],
javaScript: results[6]
};
loadDocumentPromise.resolve(doc);
},
parseFailure);
2013-02-07 08:19:29 +09:00
};
var parseFailure = function parseFailure(e) {
loadDocumentPromise.reject(e);
};
pdfManager.ensureDoc('checkHeader', []).then(function() {
pdfManager.ensureDoc('parseStartXRef', []).then(function() {
pdfManager.ensureDoc('parse', [recoveryMode]).then(
parseSuccess, parseFailure);
}, parseFailure);
}, parseFailure);
2013-02-07 08:19:29 +09:00
return loadDocumentPromise;
}
function getPdfManager(data) {
var pdfManagerPromise = new LegacyPromise();
2013-02-07 08:19:29 +09:00
var source = data.source;
var disableRange = data.disableRange;
if (source.data) {
2013-05-31 06:54:49 +09:00
try {
pdfManager = new LocalPdfManager(source.data, source.password);
pdfManagerPromise.resolve();
} catch (ex) {
pdfManagerPromise.reject(ex);
}
2013-02-07 08:19:29 +09:00
return pdfManagerPromise;
} else if (source.chunkedViewerLoading) {
2013-05-31 06:54:49 +09:00
try {
pdfManager = new NetworkPdfManager(source, handler);
pdfManagerPromise.resolve();
} catch (ex) {
pdfManagerPromise.reject(ex);
}
2013-02-07 08:19:29 +09:00
return pdfManagerPromise;
}
var networkManager = new NetworkManager(source.url, {
httpHeaders: source.httpHeaders,
withCredentials: source.withCredentials
2013-02-07 08:19:29 +09:00
});
var fullRequestXhrId = networkManager.requestFull({
onHeadersReceived: function onHeadersReceived() {
if (disableRange) {
return;
}
2013-02-07 08:19:29 +09:00
var fullRequestXhr = networkManager.getRequestXhr(fullRequestXhrId);
if (fullRequestXhr.getResponseHeader('Accept-Ranges') !== 'bytes') {
return;
}
var contentEncoding =
fullRequestXhr.getResponseHeader('Content-Encoding') || 'identity';
if (contentEncoding !== 'identity') {
return;
}
2013-02-07 08:19:29 +09:00
var length = fullRequestXhr.getResponseHeader('Content-Length');
length = parseInt(length, 10);
if (!isInt(length)) {
return;
}
source.length = length;
if (length <= 2 * RANGE_CHUNK_SIZE) {
// The file size is smaller than the size of two chunks, so it does
// not make any sense to abort the request and retry with a range
// request.
return;
}
2013-02-07 08:19:29 +09:00
// NOTE: by cancelling the full request, and then issuing range
// requests, there will be an issue for sites where you can only
// request the pdf once. However, if this is the case, then the
// server should not be returning that it can support range requests.
networkManager.abortRequest(fullRequestXhrId);
2013-05-31 06:54:49 +09:00
try {
pdfManager = new NetworkPdfManager(source, handler);
pdfManagerPromise.resolve(pdfManager);
} catch (ex) {
pdfManagerPromise.reject(ex);
}
2013-02-07 08:19:29 +09:00
},
onDone: function onDone(args) {
// the data is array, instantiating directly from it
2013-05-31 06:54:49 +09:00
try {
pdfManager = new LocalPdfManager(args.chunk, source.password);
pdfManagerPromise.resolve();
} catch (ex) {
pdfManagerPromise.reject(ex);
}
2013-02-07 08:19:29 +09:00
},
onError: function onError(status) {
if (status == 404) {
var exception = new MissingPDFException( 'Missing PDF "' +
source.url + '".');
handler.send('MissingPDF', { exception: exception });
} else {
handler.send('DocError', 'Unexpected server response (' +
status + ') while retrieving PDF "' +
source.url + '".');
}
},
2013-02-07 08:19:29 +09:00
onProgress: function onProgress(evt) {
handler.send('DocProgress', {
loaded: evt.loaded,
total: evt.lengthComputable ? evt.total : source.length
2013-02-07 08:19:29 +09:00
});
}
2013-02-07 08:19:29 +09:00
});
return pdfManagerPromise;
2012-06-24 04:48:33 +09:00
}
handler.on('test', function wphSetupTest(data) {
// check if Uint8Array can be sent to worker
if (!(data instanceof Uint8Array)) {
handler.send('test', false);
return;
}
2013-11-12 12:30:26 +09:00
// making sure postMessage transfers are working
var supportTransfers = data[0] === 255;
handler.postMessageTransfers = supportTransfers;
// check if the response property is supported by xhr
var xhr = new XMLHttpRequest();
var responseExists = 'response' in xhr;
// check if the property is actually implemented
try {
var dummy = xhr.responseType;
} catch (e) {
responseExists = false;
}
if (!responseExists) {
handler.send('test', false);
return;
}
2013-11-12 12:30:26 +09:00
handler.send('test', {
supportTypedArray: true,
supportTransfers: supportTransfers
});
2012-06-24 04:48:33 +09:00
});
handler.on('GetDocRequest', function wphSetupDoc(data) {
2013-02-07 08:19:29 +09:00
var onSuccess = function(doc) {
handler.send('GetDoc', { pdfInfo: doc });
};
var onFailure = function(e) {
if (e instanceof PasswordException) {
if (e.code === PasswordResponses.NEED_PASSWORD) {
2013-02-07 08:19:29 +09:00
handler.send('NeedPassword', {
exception: e
});
} else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
2013-02-07 08:19:29 +09:00
handler.send('IncorrectPassword', {
exception: e
});
}
} else if (e instanceof InvalidPDFException) {
handler.send('InvalidPDF', {
exception: e
});
} else if (e instanceof MissingPDFException) {
handler.send('MissingPDF', {
exception: e
});
} else {
handler.send('UnknownError', {
exception: new UnknownErrorException(e.message, e.toString())
});
}
};
2013-07-11 01:52:37 +09:00
PDFJS.maxImageSize = data.maxImageSize === undefined ?
-1 : data.maxImageSize;
PDFJS.disableFontFace = data.disableFontFace;
2014-01-11 07:30:41 +09:00
PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;
2013-12-19 06:39:03 +09:00
PDFJS.verbosity = data.verbosity;
PDFJS.cMapUrl = data.cMapUrl === undefined ?
null : data.cMapUrl;
2014-03-15 03:22:02 +09:00
PDFJS.cMapPacked = data.cMapPacked === true;
2013-07-11 01:52:37 +09:00
getPdfManager(data).then(function () {
pdfManager.onLoadedStream().then(function(stream) {
handler.send('DataLoaded', { length: stream.bytes.byteLength });
});
}).then(function pdfManagerReady() {
loadDocument(false).then(onSuccess, function loadFailure(ex) {
2013-02-07 08:19:29 +09:00
// Try again with recoveryMode == true
if (!(ex instanceof XRefParseException)) {
if (ex instanceof PasswordException) {
// after password exception prepare to receive a new password
// to repeat loading
pdfManager.passwordChangedPromise =
new LegacyPromise();
pdfManager.passwordChangedPromise.then(pdfManagerReady);
}
2013-02-07 08:19:29 +09:00
onFailure(ex);
return;
}
pdfManager.requestLoadedStream();
2013-02-07 08:19:29 +09:00
pdfManager.onLoadedStream().then(function() {
loadDocument(true).then(onSuccess, onFailure);
});
2013-05-31 06:54:49 +09:00
}, onFailure);
}, onFailure);
2012-04-12 07:52:15 +09:00
});
handler.on('GetPageRequest', function wphSetupGetPage(data) {
2013-02-07 08:19:29 +09:00
var pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function(page) {
var rotatePromise = pdfManager.ensure(page, 'rotate');
var refPromise = pdfManager.ensure(page, 'ref');
var viewPromise = pdfManager.ensure(page, 'view');
2013-04-19 02:41:33 +09:00
Promise.all([rotatePromise, refPromise, viewPromise]).then(
2013-02-07 08:19:29 +09:00
function(results) {
var page = {
pageIndex: data.pageIndex,
rotate: results[0],
ref: results[1],
view: results[2]
};
handler.send('GetPage', { pageInfo: page });
});
});
});
2011-10-09 17:37:53 +09:00
handler.on('GetPageIndex', function wphSetupGetPageIndex(data, deferred) {
var ref = new Ref(data.ref.num, data.ref.gen);
pdfManager.pdfModel.catalog.getPageIndex(ref).then(function (pageIndex) {
deferred.resolve(pageIndex);
}, deferred.reject);
});
2013-02-07 08:19:29 +09:00
handler.on('GetDestinations',
function wphSetupGetDestinations(data, deferred) {
2013-02-07 08:19:29 +09:00
pdfManager.ensureCatalog('destinations').then(function(destinations) {
deferred.resolve(destinations);
2013-02-07 08:19:29 +09:00
});
}
);
handler.on('GetData', function wphSetupGetData(data, deferred) {
2013-02-07 08:19:29 +09:00
pdfManager.requestLoadedStream();
pdfManager.onLoadedStream().then(function(stream) {
deferred.resolve(stream.bytes);
2013-02-07 08:19:29 +09:00
});
});
handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
pdfManager.updatePassword(data);
});
handler.on('GetAnnotationsRequest', function wphSetupGetAnnotations(data) {
2013-02-07 08:19:29 +09:00
pdfManager.getPage(data.pageIndex).then(function(page) {
2013-03-21 17:04:44 +09:00
pdfManager.ensure(page, 'getAnnotationsData', []).then(
function(annotationsData) {
2013-04-18 16:12:40 +09:00
handler.send('GetAnnotations', {
pageIndex: data.pageIndex,
2013-03-21 17:04:44 +09:00
annotations: annotationsData
2013-04-18 16:12:40 +09:00
});
}
);
});
});
handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
2013-02-07 08:19:29 +09:00
pdfManager.getPage(data.pageIndex).then(function(page) {
2013-02-07 08:19:29 +09:00
var pageNum = data.pageIndex + 1;
var start = Date.now();
// Pre compile the pdf page and fetch the fonts/images.
page.getOperatorList(handler, data.intent).then(function(operatorList) {
info('page=' + pageNum + ' - getOperatorList: time=' +
(Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);
2013-02-07 08:19:29 +09:00
}, function(e) {
2013-02-07 08:19:29 +09:00
var minimumStackMessage =
'worker.js: while trying to getPage() and getOperatorList()';
2013-02-07 08:19:29 +09:00
var wrappedException;
// Turn the error into an obj that can be serialized
if (typeof e === 'string') {
wrappedException = {
message: e,
stack: minimumStackMessage
};
} else if (typeof e === 'object') {
wrappedException = {
message: e.message || e.toString(),
stack: e.stack || minimumStackMessage
};
} else {
wrappedException = {
message: 'Unknown exception type: ' + (typeof e),
stack: minimumStackMessage
};
}
handler.send('PageError', {
pageNum: pageNum,
error: wrappedException,
intent: data.intent
2013-02-07 08:19:29 +09:00
});
});
});
}, this);
2011-10-09 17:37:53 +09:00
handler.on('GetTextContent', function wphExtractText(data, deferred) {
2013-02-07 08:19:29 +09:00
pdfManager.getPage(data.pageIndex).then(function(page) {
var pageNum = data.pageIndex + 1;
var start = Date.now();
page.extractTextContent().then(function(textContent) {
deferred.resolve(textContent);
info('text indexing: page=' + pageNum + ' - time=' +
(Date.now() - start) + 'ms');
2013-02-07 08:19:29 +09:00
}, function (e) {
// Skip errored pages
deferred.reject(e);
2013-02-07 08:19:29 +09:00
});
});
2011-12-11 08:24:54 +09:00
});
handler.on('Cleanup', function wphCleanup(data, deferred) {
pdfManager.cleanup();
deferred.resolve(true);
});
handler.on('Terminate', function wphTerminate(data, deferred) {
pdfManager.terminate();
deferred.resolve();
});
}
2011-10-09 17:37:53 +09:00
};
2011-10-26 07:43:41 +09:00
var consoleTimer = {};
var workerConsole = {
log: function log() {
var args = Array.prototype.slice.call(arguments);
globalScope.postMessage({
action: 'console_log',
data: args
});
},
error: function error() {
var args = Array.prototype.slice.call(arguments);
globalScope.postMessage({
action: 'console_error',
data: args
});
throw 'pdf.js execution error';
},
2011-10-29 03:23:30 +09:00
time: function time(name) {
consoleTimer[name] = Date.now();
},
2011-10-29 03:23:30 +09:00
timeEnd: function timeEnd(name) {
var time = consoleTimer[name];
if (!time) {
2014-01-16 06:28:31 +09:00
error('Unknown timer name ' + name);
}
this.log('Timer:', name, Date.now() - time);
}
2011-10-26 02:43:28 +09:00
};
2011-10-26 07:43:41 +09:00
2014-01-16 06:28:31 +09:00
2011-10-26 07:43:41 +09:00
// Worker thread?
if (typeof window === 'undefined') {
2014-01-16 06:28:31 +09:00
if (!('console' in globalScope)) {
globalScope.console = workerConsole;
}
2011-10-26 07:43:41 +09:00
// Listen for unsupported features so we can pass them on to the main thread.
PDFJS.UnsupportedManager.listen(function (msg) {
globalScope.postMessage({
action: '_unsupported_feature',
data: msg
});
});
var handler = new MessageHandler('worker_processor', this);
WorkerMessageHandler.setup(handler);
2011-10-26 07:43:41 +09:00
}