Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PDFJS.abortGetDocument function to enable cancelling of calls to PDFJS.getDocument #5234

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 7 additions & 16 deletions src/core/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
if (status === 404) {
var exception = new MissingPDFException('Missing PDF "' +
source.url + '".');
handler.send('MissingPDF', { exception: exception });
handler.send('MissingPDF', exception);
} else {
handler.send('DocError', 'Unexpected server response (' +
status + ') while retrieving PDF "' +
Expand Down Expand Up @@ -200,26 +200,17 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
var onFailure = function(e) {
if (e instanceof PasswordException) {
if (e.code === PasswordResponses.NEED_PASSWORD) {
handler.send('NeedPassword', {
exception: e
});
handler.send('NeedPassword', e);
} else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
handler.send('IncorrectPassword', {
exception: e
});
handler.send('IncorrectPassword', e);
}
} else if (e instanceof InvalidPDFException) {
handler.send('InvalidPDF', {
exception: e
});
handler.send('InvalidPDF', e);
} else if (e instanceof MissingPDFException) {
handler.send('MissingPDF', {
exception: e
});
handler.send('MissingPDF', e);
} else {
handler.send('UnknownError', {
exception: new UnknownErrorException(e.message, e.toString())
});
handler.send('UnknownError',
new UnknownErrorException(e.message, e.toString()));
}
};

Expand Down
47 changes: 32 additions & 15 deletions src/display/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
FontLoader, globalScope, info, isArrayBuffer, loadJpegStream,
MessageHandler, PDFJS, Promise, StatTimer, warn,
PasswordResponses, Util, loadScript, createPromiseCapability,
FontFace */
FontFace, AbortGetDocumentException */

'use strict';

Expand Down Expand Up @@ -230,6 +230,11 @@ PDFJS.getDocument = function getDocument(source,

workerInitializedCapability = createPromiseCapability();
workerReadyCapability = createPromiseCapability();

// Add the reject method of workerReadyCapability to the global object to
// enable aborting the current PDFJS.getDocument call.
PDFJS._workerReadyCapabilityReject = workerReadyCapability.reject;

transport = new WorkerTransport(workerInitializedCapability,
workerReadyCapability, pdfDataRangeTransport,
progressCallback);
Expand All @@ -240,6 +245,19 @@ PDFJS.getDocument = function getDocument(source,
return workerReadyCapability.promise;
};

/**
* Abort the currently active PDFJS.getDocument call.
* NOTE: This is only effective when PDFJS.getDocument is still pending,
* i.e. when it is still neither resolved nor rejected.
*/
PDFJS.abortGetDocument = function abortGetDocument() {
if (PDFJS._workerReadyCapabilityReject) {
var exception =
new AbortGetDocumentException('PDFJS.getDocument was aborted.');
PDFJS._workerReadyCapabilityReject(exception);
}
};

/**
* Proxy to a PDFDocument in the worker thread. Also, contains commonly used
* properties that can be read synchronously.
Expand Down Expand Up @@ -865,36 +883,35 @@ var WorkerTransport = (function WorkerTransportClosure() {
this.workerReadyCapability.resolve(pdfDocument);
}, this);

messageHandler.on('NeedPassword', function transportPassword(data) {
messageHandler.on('NeedPassword',
function transportNeedPassword(exception) {
if (this.passwordCallback) {
return this.passwordCallback(updatePassword,
PasswordResponses.NEED_PASSWORD);
}
this.workerReadyCapability.reject(data.exception.message,
data.exception);
this.workerReadyCapability.reject(exception);
}, this);

messageHandler.on('IncorrectPassword', function transportBadPass(data) {
messageHandler.on('IncorrectPassword',
function transportIncorrectPassword(exception) {
if (this.passwordCallback) {
return this.passwordCallback(updatePassword,
PasswordResponses.INCORRECT_PASSWORD);
}
this.workerReadyCapability.reject(data.exception.message,
data.exception);
this.workerReadyCapability.reject(exception);
}, this);

messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {
this.workerReadyCapability.reject(data.exception.name, data.exception);
messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
this.workerReadyCapability.reject(exception);
}, this);

messageHandler.on('MissingPDF', function transportMissingPDF(data) {
this.workerReadyCapability.reject(data.exception.message,
data.exception);
messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
this.workerReadyCapability.reject(exception);
}, this);

messageHandler.on('UnknownError', function transportUnknownError(data) {
this.workerReadyCapability.reject(data.exception.message,
data.exception);
messageHandler.on('UnknownError',
function transportUnknownError(exception) {
this.workerReadyCapability.reject(exception);
}, this);

messageHandler.on('DataLoaded', function transportPage(data) {
Expand Down
13 changes: 12 additions & 1 deletion src/shared/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,18 @@ var MissingPDFException = (function MissingPDFExceptionClosure() {
return MissingPDFException;
})();

var AbortGetDocumentException = (function AbortGetDocumentExceptionClosure() {
function AbortGetDocumentException(msg) {
this.name = 'AbortGetDocumentException';
this.message = msg;
}

AbortGetDocumentException.prototype = new Error();
AbortGetDocumentException.constructor = AbortGetDocumentException;

return AbortGetDocumentException;
})();

var NotImplementedException = (function NotImplementedExceptionClosure() {
function NotImplementedException(msg) {
this.message = msg;
Expand Down Expand Up @@ -418,7 +430,6 @@ var XRefParseException = (function XRefParseExceptionClosure() {
return XRefParseException;
})();


function bytesToString(bytes) {
var length = bytes.length;
var MAX_ARGUMENT_COUNT = 8192;
Expand Down
59 changes: 40 additions & 19 deletions test/unit/api_spec.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor,
isArray */
isArray, AbortGetDocumentException */

'use strict';

describe('api', function() {
// TODO run with worker enabled
var basicApiUrl = combineUrl(window.location.href, '../pdfs/basicapi.pdf');
function waitsForPromise(promise, successCallback) {
function waitsForPromiseResolved(promise, successCallback) {
var data;
promise.then(function(val) {
data = val;
Expand All @@ -22,11 +22,25 @@ describe('api', function() {
return data !== undefined;
}, 20000);
}
function waitsForPromiseRejected(promise, failureCallback) {
var data;
promise.then(function(val) {
// Shouldn't get here.
expect(false).toEqual(true);
},
function(error) {
data = error;
failureCallback(data);
});
waitsFor(function() {
return data !== undefined;
}, 20000);
}
describe('PDFJS', function() {
describe('getDocument', function() {
it('creates pdf doc from URL', function() {
var promise = PDFJS.getDocument(basicApiUrl);
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
expect(true).toEqual(true);
});
});
Expand Down Expand Up @@ -61,16 +75,23 @@ describe('api', function() {
expect(typedArrayPdf.length).toEqual(105779);

var promise = PDFJS.getDocument(typedArrayPdf);
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
expect(true).toEqual(true);
});
});
it('aborts creation of pdf doc from URL', function() {
var promise = PDFJS.getDocument(basicApiUrl);
PDFJS.abortGetDocument();
waitsForPromiseRejected(promise, function(error) {
expect(error instanceof AbortGetDocumentException).toEqual(true);
});
});
});
});
describe('PDFDocument', function() {
var promise = PDFJS.getDocument(basicApiUrl);
var doc;
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
doc = data;
});
it('gets number of pages', function() {
Expand All @@ -81,40 +102,40 @@ describe('api', function() {
});
it('gets page', function() {
var promise = doc.getPage(1);
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
expect(true).toEqual(true);
});
});
it('gets page index', function() {
// reference to second page
var ref = {num: 17, gen: 0};
var promise = doc.getPageIndex(ref);
waitsForPromise(promise, function(pageIndex) {
waitsForPromiseResolved(promise, function(pageIndex) {
expect(pageIndex).toEqual(1);
});
});
it('gets destinations', function() {
var promise = doc.getDestinations();
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
expect(data).toEqual({ chapter1: [{ gen: 0, num: 17 }, { name: 'XYZ' },
0, 841.89, null] });
});
});
it('gets attachments', function() {
var promise = doc.getAttachments();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(data).toEqual(null);
});
});
it('gets javascript', function() {
var promise = doc.getJavaScript();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(data).toEqual([]);
});
});
it('gets outline', function() {
var promise = doc.getOutline();
waitsForPromise(promise, function(outline) {
waitsForPromiseResolved(promise, function(outline) {
// Two top level entries.
expect(outline.length).toEqual(2);
// Make sure some basic attributes are set.
Expand All @@ -125,26 +146,26 @@ describe('api', function() {
});
it('gets metadata', function() {
var promise = doc.getMetadata();
waitsForPromise(promise, function(metadata) {
waitsForPromiseResolved(promise, function(metadata) {
expect(metadata.info['Title']).toEqual('Basic API Test');
expect(metadata.metadata.get('dc:title')).toEqual('Basic API Test');
});
});
it('gets data', function() {
var promise = doc.getData();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(true).toEqual(true);
});
});
it('gets filesize in bytes', function() {
var promise = doc.getDownloadInfo();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(data.length).toEqual(105779);
});
});
it('gets stats', function() {
var promise = doc.getStats();
waitsForPromise(promise, function (stats) {
waitsForPromiseResolved(promise, function (stats) {
expect(isArray(stats.streamTypes)).toEqual(true);
expect(isArray(stats.fontTypes)).toEqual(true);
});
Expand All @@ -161,7 +182,7 @@ describe('api', function() {
});
});
var page;
waitsForPromise(promise, function(data) {
waitsForPromiseResolved(promise, function(data) {
page = data;
});
it('gets page number', function () {
Expand All @@ -187,21 +208,21 @@ describe('api', function() {
});
it('gets annotations', function () {
var promise = page.getAnnotations();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(data.length).toEqual(4);
});
});
it('gets text content', function () {
var promise = page.getTextContent();
waitsForPromise(promise, function (data) {
waitsForPromiseResolved(promise, function (data) {
expect(!!data.items).toEqual(true);
expect(data.items.length).toEqual(7);
expect(!!data.styles).toEqual(true);
});
});
it('gets operator list', function() {
var promise = page.getOperatorList();
waitsForPromise(promise, function (oplist) {
waitsForPromiseResolved(promise, function (oplist) {
expect(!!oplist.fnArray).toEqual(true);
expect(!!oplist.argsArray).toEqual(true);
expect(oplist.lastChunk).toEqual(true);
Expand Down
28 changes: 23 additions & 5 deletions web/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,10 @@ var PDFView = {
},

close: function pdfViewClose() {
if (this.loading) {
PDFJS.abortGetDocument();
}

var errorWrapper = document.getElementById('errorWrapper');
errorWrapper.setAttribute('hidden', 'true');

Expand Down Expand Up @@ -672,24 +676,38 @@ var PDFView = {
self.load(pdfDocument, scale);
self.loading = false;
},
function getDocumentError(message, exception) {
function getDocumentError(exception) {
var name, message;
if (exception) {
name = exception.name;
message = exception.message;
}

if (name === 'AbortGetDocumentException') {
console.log(message);
self.loading = false;
// No need to display the fallback bar (or errorWrapper) when
// PDFJS.getDocument was aborted during document load.
return;
}

var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');

if (exception && exception.name === 'InvalidPDFException') {
if (name === 'InvalidPDFException') {
// change error message also for other builds
loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
'Invalid or corrupted PDF file.');
//#if B2G
// window.alert(loadingErrorMessage);
// return window.close();
//#endif
}

if (exception && exception.name === 'MissingPDFException') {
if (name === 'MissingPDFException') {
// special message for missing PDF's
loadingErrorMessage = mozL10n.get('missing_file_error', null,
'Missing PDF file.');
'Missing PDF file.');

//#if B2G
// window.alert(loadingErrorMessage);
Expand Down