pdf.js/test/driver.js

434 lines
12 KiB
JavaScript
Raw Normal View History

2011-09-13 02:37:33 +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.
*/
2013-06-06 04:28:31 +09:00
/* globals PDFJS, getPdf, combineUrl, StatTimer, SpecialPowers, Promise */
2012-09-01 07:48:21 +09:00
'use strict';
/*
* A Test Driver for PDF.js
*/
2013-05-31 08:33:05 +09:00
(function DriverClosure() {
// Disable worker support for running test as
// https://github.com/mozilla/pdf.js/pull/764#issuecomment-2638944
// "firefox-bin: Fatal IO error 12 (Cannot allocate memory) on X server :1."
2012-04-14 06:04:57 +09:00
// PDFJS.disableWorker = true;
2012-12-11 03:19:02 +09:00
PDFJS.enableStats = true;
2013-02-07 08:19:29 +09:00
var appPath, masterMode, browser, canvas, dummyCanvas, currentTaskIdx,
manifest, stdout;
2011-09-16 05:32:44 +09:00
var inFlightRequests = 0;
function queryParams() {
2011-08-17 04:17:46 +09:00
var qs = window.location.search.substring(1);
var kvs = qs.split('&');
var params = { };
for (var i = 0; i < kvs.length; ++i) {
var kv = kvs[i].split('=');
params[unescape(kv[0])] = unescape(kv[1]);
}
return params;
}
2013-05-31 08:33:05 +09:00
window.load = function load() {
2011-08-17 04:17:46 +09:00
var params = queryParams();
browser = params.browser;
var manifestFile = params.manifestFile;
appPath = params.path;
2013-02-07 08:19:29 +09:00
masterMode = params.masterMode === 'True';
2012-12-11 03:19:02 +09:00
var delay = params.delay || 0;
2011-08-17 04:17:46 +09:00
canvas = document.createElement('canvas');
stdout = document.getElementById('stdout');
2012-12-05 03:28:25 +09:00
info('User Agent: ' + navigator.userAgent);
2011-08-17 04:17:46 +09:00
log('load...\n');
log('Harness thinks this browser is "' + browser + '" with path "' +
appPath + '"\n');
log('Fetching manifest "' + manifestFile + '"... ');
var r = new XMLHttpRequest();
r.open('GET', manifestFile, false);
r.onreadystatechange = function loadOnreadystatechange(e) {
2011-08-17 04:17:46 +09:00
if (r.readyState == 4) {
log('done\n');
manifest = JSON.parse(r.responseText);
2011-09-16 05:32:44 +09:00
currentTaskIdx = 0;
nextTask();
2011-08-17 04:17:46 +09:00
}
};
2012-12-11 03:19:02 +09:00
if (delay) {
log('\nDelaying for ' + delay + 'ms...\n');
}
// When gathering the stats the numbers seem to be more reliable if the
// browser is given more time to startup.
setTimeout(function() {
r.send(null);
}, delay);
2013-05-31 08:33:05 +09:00
};
function cleanup() {
2011-11-16 07:43:05 +09:00
// Clear out all the stylesheets since a new one is created for each font.
while (document.styleSheets.length > 0) {
var styleSheet = document.styleSheets[0];
2011-11-16 08:45:37 +09:00
while (styleSheet.cssRules.length > 0)
styleSheet.deleteRule(0);
var ownerNode = styleSheet.ownerNode;
ownerNode.parentNode.removeChild(ownerNode);
}
var guard = document.getElementById('content-end');
var body = document.body;
2011-09-23 20:58:54 +09:00
while (body.lastChild !== guard)
body.removeChild(body.lastChild);
2011-11-16 07:43:05 +09:00
// Wipe out the link to the pdfdoc so it can be GC'ed.
for (var i = 0; i < manifest.length; i++) {
if (manifest[i].pdfDoc) {
manifest[i].pdfDoc.destroy();
2011-11-16 08:45:37 +09:00
delete manifest[i].pdfDoc;
2011-11-16 07:43:05 +09:00
}
}
}
2012-01-10 11:37:39 +09:00
function exceptionToString(e) {
if (typeof e !== 'object')
return String(e);
if (!('message' in e))
return JSON.stringify(e);
return e.message + ('stack' in e ? ' at ' + e.stack.split('\n')[0] : '');
}
function nextTask() {
cleanup();
2011-08-17 04:17:46 +09:00
if (currentTaskIdx == manifest.length) {
2011-10-20 03:14:13 +09:00
done();
return;
2011-08-17 04:17:46 +09:00
}
var task = manifest[currentTaskIdx];
task.round = 0;
2012-12-11 03:19:02 +09:00
task.stats = {times: []};
2011-08-17 04:17:46 +09:00
log('Loading file "' + task.file + '"\n');
var absoluteUrl = combineUrl(window.location.href, task.file);
2013-02-07 08:19:29 +09:00
var failure;
function continuation() {
task.pageNum = task.firstPage || 1;
nextPage(task, failure);
}
// When generating reference images in masterMode, disable range requests
PDFJS.disableRange = task.disableRange || masterMode;
PDFJS.disableAutoFetch = !task.enableAutoFetch || masterMode;
2013-02-07 08:19:29 +09:00
try {
var promise = PDFJS.getDocument(absoluteUrl);
promise.then(function(doc) {
task.pdfDoc = doc;
continuation();
}, function(e) {
failure = 'load PDF doc : ' + e;
continuation();
});
return;
} catch (e) {
failure = 'load PDF doc : ' + exceptionToString(e);
}
continuation();
}
function getLastPageNum(task) {
2013-05-31 06:54:49 +09:00
if (!task.pdfDoc) {
return task.firstPage || 1;
}
var lastPageNum = task.lastPage || 0;
if (!lastPageNum || lastPageNum > task.pdfDoc.numPages) {
lastPageNum = task.pdfDoc.numPages;
}
return lastPageNum;
}
2011-10-20 03:14:13 +09:00
function isLastPage(task) {
return task.pageNum > getLastPageNum(task);
}
function canvasToDataURL() {
return canvas.toDataURL('image/png');
}
2012-09-12 08:04:01 +09:00
function NullTextLayerBuilder() {
}
NullTextLayerBuilder.prototype = {
beginLayout: function NullTextLayerBuilder_BeginLayout() {},
endLayout: function NullTextLayerBuilder_EndLayout() {},
appendText: function NullTextLayerBuilder_AppendText() {}
};
function SimpleTextLayerBuilder(ctx, viewport) {
this.ctx = ctx;
this.viewport = viewport;
this.textCounter = 0;
2012-09-12 08:04:01 +09:00
}
SimpleTextLayerBuilder.prototype = {
beginLayout: function SimpleTextLayerBuilder_BeginLayout() {
this.ctx.save();
},
endLayout: function SimpleTextLayerBuilder_EndLayout() {
this.ctx.restore();
},
appendText: function SimpleTextLayerBuilder_AppendText(geom) {
2012-09-12 08:04:01 +09:00
var ctx = this.ctx, viewport = this.viewport;
// vScale and hScale already contain the scaling to pixel units
2013-06-21 07:03:30 +09:00
var fontHeight = geom.fontSize * Math.abs(geom.vScale);
ctx.save();
2012-09-12 08:04:01 +09:00
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.fillStyle = 'yellow';
2013-06-21 07:03:30 +09:00
ctx.translate(geom.x + (fontHeight * Math.sin(geom.angle)),
geom.y - (fontHeight * Math.cos(geom.angle)));
ctx.rotate(geom.angle);
ctx.rect(0, 0, geom.canvasWidth * Math.abs(geom.hScale), fontHeight);
2012-09-12 08:04:01 +09:00
ctx.stroke();
ctx.fill();
2013-06-21 07:03:30 +09:00
ctx.restore();
2012-09-22 18:18:26 +09:00
var textContent = this.textContent.bidiTexts[this.textCounter].str;
ctx.font = fontHeight + 'px ' + geom.fontFamily;
2012-09-12 08:04:01 +09:00
ctx.fillStyle = 'black';
2012-09-21 04:48:18 +09:00
ctx.fillText(textContent, geom.x, geom.y);
2012-09-18 00:19:27 +09:00
this.textCounter++;
},
setTextContent: function SimpleTextLayerBuilder_SetTextContent(textContent) {
this.textContent = textContent;
2012-09-12 08:04:01 +09:00
}
};
function nextPage(task, loadError) {
var failure = loadError || '';
if (!task.pdfDoc) {
sendTaskResult(canvasToDataURL(), task, failure);
log('done' + (failure ? ' (failed !: ' + failure + ')' : '') + '\n');
2011-09-16 05:32:44 +09:00
++currentTaskIdx;
nextTask();
return;
}
2011-08-17 04:17:46 +09:00
if (isLastPage(task)) {
if (++task.round < task.rounds) {
log(' Round ' + (1 + task.round) + '\n');
task.pageNum = task.firstPage || 1;
2011-08-17 04:17:46 +09:00
} else {
2011-09-16 05:32:44 +09:00
++currentTaskIdx;
nextTask();
2011-08-17 04:17:46 +09:00
return;
}
2011-08-17 04:17:46 +09:00
}
if (task.skipPages && task.skipPages.indexOf(task.pageNum) >= 0) {
log(' skipping page ' + task.pageNum + '/' + task.pdfDoc.numPages +
'... ');
2011-12-08 13:07:34 +09:00
// empty the canvas
canvas.width = 1;
canvas.height = 1;
clear(canvas.getContext('2d'));
snapshotCurrentPage(task, '');
return;
}
2011-08-17 04:17:46 +09:00
var page = null;
2011-08-17 04:17:46 +09:00
if (!failure) {
try {
log(' loading page ' + task.pageNum + '/' + task.pdfDoc.numPages +
'... ');
var ctx = canvas.getContext('2d');
2012-04-12 10:05:43 +09:00
task.pdfDoc.getPage(task.pageNum).then(function(page) {
var pdfToCssUnitsCoef = 96.0 / 72.0;
2012-04-13 00:23:38 +09:00
var viewport = page.getViewport(pdfToCssUnitsCoef);
canvas.width = viewport.width;
canvas.height = viewport.height;
2012-04-12 10:05:43 +09:00
clear(ctx);
2012-09-12 08:04:01 +09:00
var drawContext, textLayerBuilder;
2013-06-06 04:28:31 +09:00
var initPromise = new Promise();
2012-09-12 08:04:01 +09:00
if (task.type == 'text') {
// using dummy canvas for pdf context drawing operations
if (!dummyCanvas) {
dummyCanvas = document.createElement('canvas');
}
drawContext = dummyCanvas.getContext('2d');
// ... text builder will draw its content on the test canvas
textLayerBuilder = new SimpleTextLayerBuilder(ctx, viewport);
page.getTextContent().then(function(textContent) {
textLayerBuilder.setTextContent(textContent);
2013-06-06 04:28:31 +09:00
initPromise.resolve();
});
2012-09-12 08:04:01 +09:00
} else {
drawContext = ctx;
textLayerBuilder = new NullTextLayerBuilder();
2013-06-06 04:28:31 +09:00
initPromise.resolve();
2012-09-12 08:04:01 +09:00
}
2012-04-12 10:05:43 +09:00
var renderContext = {
2012-09-12 08:04:01 +09:00
canvasContext: drawContext,
2012-04-12 10:05:43 +09:00
textLayer: textLayerBuilder,
2012-04-13 01:59:17 +09:00
viewport: viewport
2012-04-12 10:05:43 +09:00
};
var completeRender = (function(error) {
2012-04-17 04:49:55 +09:00
page.destroy();
2012-12-11 03:19:02 +09:00
task.stats = page.stats;
page.stats = new StatTimer();
snapshotCurrentPage(task, error);
});
2013-06-06 04:28:31 +09:00
initPromise.then(function () {
page.render(renderContext).then(function() {
completeRender(false);
},
function(error) {
completeRender('render : ' + error);
});
2012-04-12 10:05:43 +09:00
});
},
function(error) {
snapshotCurrentPage(task, 'render : ' + error);
});
2011-08-17 04:17:46 +09:00
} catch (e) {
2012-01-10 11:37:39 +09:00
failure = 'page setup : ' + exceptionToString(e);
2012-04-12 10:05:43 +09:00
snapshotCurrentPage(task, failure);
}
2011-08-17 04:17:46 +09:00
}
}
2011-09-16 05:32:44 +09:00
function snapshotCurrentPage(task, failure) {
2011-08-17 04:17:46 +09:00
log('done, snapshotting... ');
sendTaskResult(canvasToDataURL(), task, failure);
2011-08-17 04:17:46 +09:00
log('done' + (failure ? ' (failed !: ' + failure + ')' : '') + '\n');
2011-08-17 04:17:46 +09:00
// Set up the next request
var backoff = (inFlightRequests > 0) ? inFlightRequests * 10 : 0;
setTimeout(
function snapshotCurrentPageSetTimeout() {
2011-09-16 05:32:44 +09:00
++task.pageNum;
nextPage(task);
},
backoff
);
}
function sendQuitRequest() {
var r = new XMLHttpRequest();
r.open('POST', '/tellMeToQuit?path=' + escape(appPath), false);
r.send(null);
}
function quitApp() {
log('Done !');
document.body.innerHTML = 'Tests are finished. <h1>CLOSE ME!</h1>' +
document.body.innerHTML;
if (window.SpecialPowers) {
SpecialPowers.quitApplication();
} else {
sendQuitRequest();
window.close();
}
}
function done() {
if (inFlightRequests > 0) {
document.getElementById('inFlightCount').innerHTML = inFlightRequests;
setTimeout(done, 100);
} else {
setTimeout(quitApp, 100);
}
}
function sendTaskResult(snapshot, task, failure, result) {
// Optional result argument is for retrying XHR requests - see below
if (!result) {
result = JSON.stringify({
browser: browser,
id: task.id,
numPages: task.pdfDoc ?
(task.lastPage || task.pdfDoc.numPages) : 0,
lastPageNum: getLastPageNum(task),
failure: failure,
file: task.file,
round: task.round,
page: task.pageNum,
2012-12-11 03:19:02 +09:00
snapshot: snapshot,
stats: task.stats.times
});
}
2012-12-05 03:28:25 +09:00
send('/submit_task_results', result);
}
function send(url, message) {
var r = new XMLHttpRequest();
// (The POST URI is ignored atm.)
2012-12-05 03:28:25 +09:00
r.open('POST', url, true);
r.setRequestHeader('Content-Type', 'application/json');
r.onreadystatechange = function sendTaskResultOnreadystatechange(e) {
if (r.readyState == 4) {
inFlightRequests--;
2012-04-04 07:19:03 +09:00
// Retry until successful
2012-12-05 03:28:25 +09:00
if (r.status !== 200) {
setTimeout(function() {
send(url, message);
});
}
}
2011-09-16 05:32:44 +09:00
};
document.getElementById('inFlightCount').innerHTML = inFlightRequests++;
2012-12-05 03:28:25 +09:00
r.send(message);
}
function info(message) {
send('/info', JSON.stringify({
browser: browser,
message: message
}));
}
function clear(ctx) {
2013-06-30 07:52:25 +09:00
ctx.beginPath();
2013-03-30 05:26:25 +09:00
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
/* Auto-scroll if the scrollbar is near the bottom, otherwise do nothing. */
function checkScrolling() {
if ((stdout.scrollHeight - stdout.scrollTop) <= stdout.offsetHeight) {
stdout.scrollTop = stdout.scrollHeight;
}
}
function log(str) {
2011-08-26 09:14:51 +09:00
if (stdout.insertAdjacentHTML)
stdout.insertAdjacentHTML('BeforeEnd', str);
else
stdout.innerHTML += str;
2011-08-25 01:11:38 +09:00
if (str.lastIndexOf('\n') >= 0)
checkScrolling();
}
2013-05-31 08:33:05 +09:00
})(); // DriverClosure