pdf.js/src/worker.js

286 lines
8.0 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: */
2011-10-26 10:18:22 +09:00
'use strict';
function MessageHandler(name, comObj) {
this.name = name;
this.comObj = comObj;
this.callbackIndex = 1;
var callbacks = this.callbacks = {};
var ah = this.actionHandler = {};
2011-10-29 03:23:30 +09:00
ah['console_log'] = [function ahConsoleLog(data) {
console.log.apply(console, data);
}];
2011-10-29 03:23:30 +09:00
ah['console_error'] = [function ahConsoleError(data) {
console.error.apply(console, data);
}];
ah['_warn'] = [function ah_Warn(data) {
warn(data);
}];
comObj.onmessage = function messageHandlerComObjOnMessage(event) {
var data = event.data;
if (data.isReply) {
var callbackId = data.callbackId;
if (data.callbackId in callbacks) {
var callback = callbacks[callbackId];
delete callbacks[callbackId];
callback(data.data);
} else {
2012-01-25 05:04:59 +09:00
error('Cannot resolve callback ' + callbackId);
}
} else if (data.action in ah) {
var action = ah[data.action];
2011-12-15 07:02:00 +09:00
if (data.callbackId) {
var promise = new Promise();
promise.then(function(resolvedData) {
comObj.postMessage({
isReply: true,
callbackId: data.callbackId,
data: resolvedData
});
});
action[0].call(action[1], data.data, promise);
} else {
action[0].call(action[1], data.data);
}
} else {
2012-01-25 05:04:59 +09:00
error('Unkown action from worker: ' + data.action);
}
};
}
MessageHandler.prototype = {
2011-10-29 03:23:30 +09:00
on: function messageHandlerOn(actionName, handler, scope) {
var ah = this.actionHandler;
if (ah[actionName]) {
2012-01-25 05:04:59 +09:00
error('There is already an actionName called "' + actionName + '"');
}
ah[actionName] = [handler, scope];
},
/**
* Sends a message to the comObj to invoke the action with the supplied data.
* @param {String} actionName Action to call.
* @param {JSON} data JSON data to send.
* @param {function} [callback] Optional callback that will handle a reply.
*/
send: function messageHandlerSend(actionName, data, callback) {
var message = {
action: actionName,
data: data
};
if (callback) {
var callbackId = this.callbackIndex++;
this.callbacks[callbackId] = callback;
message.callbackId = callbackId;
}
this.comObj.postMessage(message);
}
};
var WorkerMessageHandler = {
2011-10-29 03:23:30 +09:00
setup: function wphSetup(handler) {
var pdfModel = null;
2011-10-09 17:37:53 +09:00
2011-12-15 07:02:00 +09:00
handler.on('test', function wphSetupTest(data) {
handler.send('test', data instanceof Uint8Array);
});
2012-04-13 04:11:22 +09:00
handler.on('GetDocRequest', function wphSetupDoc(data) {
// Create only the model of the PDFDoc, which is enough for
// processing the content of the pdf.
var pdfData = data.data;
var pdfPassword = data.params.password;
try {
pdfModel = new PDFDocument(new Stream(pdfData), pdfPassword);
} catch (e) {
if (e instanceof PasswordException) {
if (e.code === 'needpassword') {
handler.send('NeedPassword', {
exception: e
});
} else if (e.code === 'incorrectpassword') {
handler.send('IncorrectPassword', {
exception: e
});
}
return;
} else {
throw e;
}
}
2012-04-12 07:52:15 +09:00
var doc = {
numPages: pdfModel.numPages,
2012-04-13 07:14:18 +09:00
fingerprint: pdfModel.getFingerprint(),
2012-04-12 07:52:15 +09:00
destinations: pdfModel.catalog.destinations,
outline: pdfModel.catalog.documentOutline,
2012-04-13 07:56:17 +09:00
info: pdfModel.getDocumentInfo(),
metadata: pdfModel.catalog.metadata,
encrypted: !!pdfModel.xref.encrypt
2012-04-12 07:52:15 +09:00
};
2012-04-13 04:11:22 +09:00
handler.send('GetDoc', {pdfInfo: doc});
2012-04-12 07:52:15 +09:00
});
handler.on('GetPageRequest', function wphSetupGetPage(data) {
2012-04-13 02:01:07 +09:00
var pageNumber = data.pageIndex + 1;
var pdfPage = pdfModel.getPage(pageNumber);
2012-04-12 07:52:15 +09:00
var page = {
2012-04-13 02:01:07 +09:00
pageIndex: data.pageIndex,
2012-04-12 07:52:15 +09:00
rotate: pdfPage.rotate,
ref: pdfPage.ref,
view: pdfPage.view
2012-04-12 07:52:15 +09:00
};
2012-04-13 04:11:22 +09:00
handler.send('GetPage', {pageInfo: page});
});
2011-10-09 17:37:53 +09:00
handler.on('GetData', function wphSetupGetData(data, promise) {
promise.resolve(pdfModel.stream.bytes);
});
handler.on('GetAnnotationsRequest', function wphSetupGetAnnotations(data) {
var pdfPage = pdfModel.getPage(data.pageIndex + 1);
handler.send('GetAnnotations', {
pageIndex: data.pageIndex,
annotations: pdfPage.getAnnotations()
});
});
handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
2012-04-13 02:01:07 +09:00
var pageNum = data.pageIndex + 1;
2011-10-09 17:37:53 +09:00
// The following code does quite the same as
// Page.prototype.startRendering, but stops at one point and sends the
// result back to the main thread.
var gfx = new CanvasGraphics(null);
var start = Date.now();
var dependency = [];
var operatorList = null;
try {
var page = pdfModel.getPage(pageNum);
// Pre compile the pdf page and fetch the fonts/images.
operatorList = page.getOperatorList(handler, dependency);
2011-11-30 04:32:01 +09:00
} catch (e) {
var minimumStackMessage =
'worker.js: while trying to getPage() and getOperatorList()';
// Turn the error into an obj that can be serialized
if (typeof e === 'string') {
e = {
message: e,
stack: minimumStackMessage
};
} else if (typeof e === 'object') {
e = {
message: e.message || e.toString(),
stack: e.stack || minimumStackMessage
};
} else {
e = {
message: 'Unknown exception type: ' + (typeof e),
stack: minimumStackMessage
2012-01-21 08:44:51 +09:00
};
}
2012-04-13 04:11:22 +09:00
handler.send('PageError', {
pageNum: pageNum,
error: e
});
return;
}
console.log('page=%d - getOperatorList: time=%dms, len=%d', pageNum,
Date.now() - start, operatorList.fnArray.length);
// Filter the dependecies for fonts.
var fonts = {};
2011-11-03 04:11:33 +09:00
for (var i = 0, ii = dependency.length; i < ii; i++) {
var dep = dependency[i];
if (dep.indexOf('font_') == 0) {
fonts[dep] = true;
}
}
2012-04-13 04:11:22 +09:00
handler.send('RenderPage', {
2012-04-13 02:01:07 +09:00
pageIndex: data.pageIndex,
operatorList: operatorList,
depFonts: Object.keys(fonts)
});
}, this);
2011-10-09 17:37:53 +09:00
2012-04-21 08:49:08 +09:00
handler.on('GetTextContent', function wphExtractText(data, promise) {
var pageNum = data.pageIndex + 1;
var start = Date.now();
var textContent = '';
try {
var page = pdfModel.getPage(pageNum);
textContent = page.extractTextContent();
2012-04-21 08:49:08 +09:00
promise.resolve(textContent);
} catch (e) {
// Skip errored pages
2012-04-21 08:49:08 +09:00
promise.reject(e);
}
2011-12-11 08:24:54 +09:00
console.log('text indexing: page=%d - time=%dms',
pageNum, Date.now() - start);
2011-12-11 08:24:54 +09:00
});
}
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);
postMessage({
action: 'console_log',
data: args
});
},
error: function error() {
var args = Array.prototype.slice.call(arguments);
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 == null) {
2012-01-25 05:04:59 +09:00
error('Unkown 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
// Worker thread?
if (typeof window === 'undefined') {
globalScope.console = workerConsole;
2011-10-26 07:43:41 +09:00
// Add a logger so we can pass warnings on to the main thread, errors will
// throw an exception which will be forwarded on automatically.
PDFJS.LogManager.addLogger({
warn: function(msg) {
postMessage({
action: '_warn',
data: msg
});
}
});
var handler = new MessageHandler('worker_processor', this);
WorkerMessageHandler.setup(handler);
2011-10-26 07:43:41 +09:00
}