Merge pull request #4424 from Snuffleupagus/web-braces

Fix coding style in /web
This commit is contained in:
Tim van der Meij 2014-03-10 12:27:49 +01:00
commit ca918922f3
9 changed files with 202 additions and 123 deletions

View File

@ -35,7 +35,9 @@ var ChromeCom = (function ChromeComClosure() {
}; };
if (!chrome.runtime) { if (!chrome.runtime) {
console.error('chrome.runtime is undefined.'); console.error('chrome.runtime is undefined.');
if (callback) callback(); if (callback) {
callback();
}
} else if (callback) { } else if (callback) {
chrome.runtime.sendMessage(message, callback); chrome.runtime.sendMessage(message, callback);
} else { } else {

View File

@ -38,9 +38,9 @@ if (typeof PDFJS === 'undefined') {
} }
// some mobile version might not support Float64Array // some mobile version might not support Float64Array
if (typeof Float64Array === 'undefined') if (typeof Float64Array === 'undefined') {
window.Float64Array = Float32Array; window.Float64Array = Float32Array;
}
return; return;
} }
@ -49,18 +49,21 @@ if (typeof PDFJS === 'undefined') {
} }
function setArrayOffset(array, offset) { function setArrayOffset(array, offset) {
if (arguments.length < 2) if (arguments.length < 2) {
offset = 0; offset = 0;
for (var i = 0, n = array.length; i < n; ++i, ++offset) }
for (var i = 0, n = array.length; i < n; ++i, ++offset) {
this[offset] = array[i] & 0xFF; this[offset] = array[i] & 0xFF;
}
} }
function TypedArray(arg1) { function TypedArray(arg1) {
var result; var result;
if (typeof arg1 === 'number') { if (typeof arg1 === 'number') {
result = []; result = [];
for (var i = 0; i < arg1; ++i) for (var i = 0; i < arg1; ++i) {
result[i] = 0; result[i] = 0;
}
} else if ('slice' in arg1) { } else if ('slice' in arg1) {
result = arg1.slice(0); result = arg1.slice(0);
} else { } else {
@ -75,9 +78,9 @@ if (typeof PDFJS === 'undefined') {
result.byteLength = result.length; result.byteLength = result.length;
result.set = setArrayOffset; result.set = setArrayOffset;
if (typeof arg1 === 'object' && arg1.buffer) if (typeof arg1 === 'object' && arg1.buffer) {
result.buffer = arg1.buffer; result.buffer = arg1.buffer;
}
return result; return result;
} }
@ -101,8 +104,9 @@ if (typeof PDFJS === 'undefined') {
// Object.create() ? // Object.create() ?
(function checkObjectCreateCompatibility() { (function checkObjectCreateCompatibility() {
if (typeof Object.create !== 'undefined') if (typeof Object.create !== 'undefined') {
return; return;
}
Object.create = function objectCreate(proto) { Object.create = function objectCreate(proto) {
function Constructor() {} function Constructor() {}
@ -127,15 +131,19 @@ if (typeof PDFJS === 'undefined') {
} catch (e) { } catch (e) {
definePropertyPossible = false; definePropertyPossible = false;
} }
if (definePropertyPossible) return; if (definePropertyPossible) {
return;
}
} }
Object.defineProperty = function objectDefineProperty(obj, name, def) { Object.defineProperty = function objectDefineProperty(obj, name, def) {
delete obj[name]; delete obj[name];
if ('get' in def) if ('get' in def) {
obj.__defineGetter__(name, def['get']); obj.__defineGetter__(name, def['get']);
if ('set' in def) }
if ('set' in def) {
obj.__defineSetter__(name, def['set']); obj.__defineSetter__(name, def['set']);
}
if ('value' in def) { if ('value' in def) {
obj.__defineSetter__(name, function objectDefinePropertySetter(value) { obj.__defineSetter__(name, function objectDefinePropertySetter(value) {
this.__defineGetter__(name, function objectDefinePropertyGetter() { this.__defineGetter__(name, function objectDefinePropertyGetter() {
@ -150,14 +158,16 @@ if (typeof PDFJS === 'undefined') {
// Object.keys() ? // Object.keys() ?
(function checkObjectKeysCompatibility() { (function checkObjectKeysCompatibility() {
if (typeof Object.keys !== 'undefined') if (typeof Object.keys !== 'undefined') {
return; return;
}
Object.keys = function objectKeys(obj) { Object.keys = function objectKeys(obj) {
var result = []; var result = [];
for (var i in obj) { for (var i in obj) {
if (obj.hasOwnProperty(i)) if (obj.hasOwnProperty(i)) {
result.push(i); result.push(i);
}
} }
return result; return result;
}; };
@ -165,12 +175,14 @@ if (typeof PDFJS === 'undefined') {
// No readAsArrayBuffer ? // No readAsArrayBuffer ?
(function checkFileReaderReadAsArrayBuffer() { (function checkFileReaderReadAsArrayBuffer() {
if (typeof FileReader === 'undefined') if (typeof FileReader === 'undefined') {
return; // FileReader is not implemented return; // FileReader is not implemented
}
var frPrototype = FileReader.prototype; var frPrototype = FileReader.prototype;
// Older versions of Firefox might not have readAsArrayBuffer // Older versions of Firefox might not have readAsArrayBuffer
if ('readAsArrayBuffer' in frPrototype) if ('readAsArrayBuffer' in frPrototype) {
return; // readAsArrayBuffer is implemented return; // readAsArrayBuffer is implemented
}
Object.defineProperty(frPrototype, 'readAsArrayBuffer', { Object.defineProperty(frPrototype, 'readAsArrayBuffer', {
value: function fileReaderReadAsArrayBuffer(blob) { value: function fileReaderReadAsArrayBuffer(blob) {
var fileReader = new FileReader(); var fileReader = new FileReader();
@ -180,8 +192,9 @@ if (typeof PDFJS === 'undefined') {
var buffer = new ArrayBuffer(data.length); var buffer = new ArrayBuffer(data.length);
var uint8Array = new Uint8Array(buffer); var uint8Array = new Uint8Array(buffer);
for (var i = 0, ii = data.length; i < ii; i++) for (var i = 0, ii = data.length; i < ii; i++) {
uint8Array[i] = data.charCodeAt(i); uint8Array[i] = data.charCodeAt(i);
}
Object.defineProperty(originalReader, 'result', { Object.defineProperty(originalReader, 'result', {
value: buffer, value: buffer,
@ -211,8 +224,9 @@ if (typeof PDFJS === 'undefined') {
if ('response' in xhrPrototype || if ('response' in xhrPrototype ||
'mozResponseArrayBuffer' in xhrPrototype || 'mozResponseArrayBuffer' in xhrPrototype ||
'mozResponse' in xhrPrototype || 'mozResponse' in xhrPrototype ||
'responseArrayBuffer' in xhrPrototype) 'responseArrayBuffer' in xhrPrototype) {
return; return;
}
// IE9 ? // IE9 ?
if (typeof VBArray !== 'undefined') { if (typeof VBArray !== 'undefined') {
Object.defineProperty(xhrPrototype, 'response', { Object.defineProperty(xhrPrototype, 'response', {
@ -236,8 +250,9 @@ if (typeof PDFJS === 'undefined') {
var text = this.responseText; var text = this.responseText;
var i, n = text.length; var i, n = text.length;
var result = new Uint8Array(n); var result = new Uint8Array(n);
for (i = 0; i < n; ++i) for (i = 0; i < n; ++i) {
result[i] = text.charCodeAt(i) & 0xFF; result[i] = text.charCodeAt(i) & 0xFF;
}
return result; return result;
} }
Object.defineProperty(xhrPrototype, 'response', { get: responseGetter }); Object.defineProperty(xhrPrototype, 'response', { get: responseGetter });
@ -245,8 +260,9 @@ if (typeof PDFJS === 'undefined') {
// window.btoa (base64 encode function) ? // window.btoa (base64 encode function) ?
(function checkWindowBtoaCompatibility() { (function checkWindowBtoaCompatibility() {
if ('btoa' in window) if ('btoa' in window) {
return; return;
}
var digits = var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
@ -270,15 +286,18 @@ if (typeof PDFJS === 'undefined') {
// window.atob (base64 encode function) ? // window.atob (base64 encode function) ?
(function checkWindowAtobCompatibility() { (function checkWindowAtobCompatibility() {
if ('atob' in window) if ('atob' in window) {
return; return;
}
// https://github.com/davidchambers/Base64.js // https://github.com/davidchambers/Base64.js
var digits = var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
window.atob = function (input) { window.atob = function (input) {
input = input.replace(/=+$/, ''); input = input.replace(/=+$/, '');
if (input.length % 4 == 1) throw new Error('bad atob input'); if (input.length % 4 == 1) {
throw new Error('bad atob input');
}
for ( for (
// initialize result and counters // initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = ''; var bc = 0, bs, buffer, idx = 0, output = '';
@ -300,8 +319,9 @@ if (typeof PDFJS === 'undefined') {
// Function.prototype.bind ? // Function.prototype.bind ?
(function checkFunctionPrototypeBindCompatibility() { (function checkFunctionPrototypeBindCompatibility() {
if (typeof Function.prototype.bind !== 'undefined') if (typeof Function.prototype.bind !== 'undefined') {
return; return;
}
Function.prototype.bind = function functionPrototypeBind(obj) { Function.prototype.bind = function functionPrototypeBind(obj) {
var fn = this, headArgs = Array.prototype.slice.call(arguments, 1); var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);
@ -316,21 +336,26 @@ if (typeof PDFJS === 'undefined') {
// HTMLElement dataset property // HTMLElement dataset property
(function checkDatasetProperty() { (function checkDatasetProperty() {
var div = document.createElement('div'); var div = document.createElement('div');
if ('dataset' in div) if ('dataset' in div) {
return; // dataset property exists return; // dataset property exists
}
Object.defineProperty(HTMLElement.prototype, 'dataset', { Object.defineProperty(HTMLElement.prototype, 'dataset', {
get: function() { get: function() {
if (this._dataset) if (this._dataset) {
return this._dataset; return this._dataset;
}
var dataset = {}; var dataset = {};
for (var j = 0, jj = this.attributes.length; j < jj; j++) { for (var j = 0, jj = this.attributes.length; j < jj; j++) {
var attribute = this.attributes[j]; var attribute = this.attributes[j];
if (attribute.name.substring(0, 5) != 'data-') if (attribute.name.substring(0, 5) != 'data-') {
continue; continue;
}
var key = attribute.name.substring(5).replace(/\-([a-z])/g, var key = attribute.name.substring(5).replace(/\-([a-z])/g,
function(all, ch) { return ch.toUpperCase(); }); function(all, ch) {
return ch.toUpperCase();
});
dataset[key] = attribute.value; dataset[key] = attribute.value;
} }
@ -348,18 +373,23 @@ if (typeof PDFJS === 'undefined') {
// HTMLElement classList property // HTMLElement classList property
(function checkClassListProperty() { (function checkClassListProperty() {
var div = document.createElement('div'); var div = document.createElement('div');
if ('classList' in div) if ('classList' in div) {
return; // classList property exists return; // classList property exists
}
function changeList(element, itemName, add, remove) { function changeList(element, itemName, add, remove) {
var s = element.className || ''; var s = element.className || '';
var list = s.split(/\s+/g); var list = s.split(/\s+/g);
if (list[0] === '') list.shift(); if (list[0] === '') {
list.shift();
}
var index = list.indexOf(itemName); var index = list.indexOf(itemName);
if (index < 0 && add) if (index < 0 && add) {
list.push(itemName); list.push(itemName);
if (index >= 0 && remove) }
if (index >= 0 && remove) {
list.splice(index, 1); list.splice(index, 1);
}
element.className = list.join(' '); element.className = list.join(' ');
return (index >= 0); return (index >= 0);
} }
@ -381,8 +411,9 @@ if (typeof PDFJS === 'undefined') {
Object.defineProperty(HTMLElement.prototype, 'classList', { Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function() { get: function() {
if (this._classList) if (this._classList) {
return this._classList; return this._classList;
}
var classList = Object.create(classListPrototype, { var classList = Object.create(classListPrototype, {
element: { element: {

View File

@ -46,13 +46,17 @@ var FontInspector = (function FontInspectorClosure() {
} }
} }
function textLayerClick(e) { function textLayerClick(e) {
if (!e.target.dataset.fontName || e.target.tagName.toUpperCase() !== 'DIV') if (!e.target.dataset.fontName ||
e.target.tagName.toUpperCase() !== 'DIV') {
return; return;
}
var fontName = e.target.dataset.fontName; var fontName = e.target.dataset.fontName;
var selects = document.getElementsByTagName('input'); var selects = document.getElementsByTagName('input');
for (var i = 0; i < selects.length; ++i) { for (var i = 0; i < selects.length; ++i) {
var select = selects[i]; var select = selects[i];
if (select.dataset.fontName != fontName) continue; if (select.dataset.fontName != fontName) {
continue;
}
select.checked = !select.checked; select.checked = !select.checked;
selectFont(fontName, select.checked); selectFont(fontName, select.checked);
select.scrollIntoView(); select.scrollIntoView();
@ -140,8 +144,9 @@ var FontInspector = (function FontInspectorClosure() {
// Somewhat of a hack, should probably add a hook for when the text layer // Somewhat of a hack, should probably add a hook for when the text layer
// is done rendering. // is done rendering.
setTimeout(function() { setTimeout(function() {
if (this.active) if (this.active) {
resetSelection(); resetSelection();
}
}.bind(this), 2000); }.bind(this), 2000);
} }
}; };
@ -172,8 +177,9 @@ var StepperManager = (function StepperManagerClosure() {
stepperDiv = document.createElement('div'); stepperDiv = document.createElement('div');
this.panel.appendChild(stepperControls); this.panel.appendChild(stepperControls);
this.panel.appendChild(stepperDiv); this.panel.appendChild(stepperDiv);
if (sessionStorage.getItem('pdfjsBreakPoints')) if (sessionStorage.getItem('pdfjsBreakPoints')) {
breakPoints = JSON.parse(sessionStorage.getItem('pdfjsBreakPoints')); breakPoints = JSON.parse(sessionStorage.getItem('pdfjsBreakPoints'));
}
}, },
enabled: false, enabled: false,
active: false, active: false,
@ -191,19 +197,22 @@ var StepperManager = (function StepperManagerClosure() {
var initBreakPoints = breakPoints[pageIndex] || []; var initBreakPoints = breakPoints[pageIndex] || [];
var stepper = new Stepper(debug, pageIndex, initBreakPoints); var stepper = new Stepper(debug, pageIndex, initBreakPoints);
steppers.push(stepper); steppers.push(stepper);
if (steppers.length === 1) if (steppers.length === 1) {
this.selectStepper(pageIndex, false); this.selectStepper(pageIndex, false);
}
return stepper; return stepper;
}, },
selectStepper: function selectStepper(pageIndex, selectPanel) { selectStepper: function selectStepper(pageIndex, selectPanel) {
if (selectPanel) if (selectPanel) {
this.manager.selectPanel(1); this.manager.selectPanel(1);
}
for (var i = 0; i < steppers.length; ++i) { for (var i = 0; i < steppers.length; ++i) {
var stepper = steppers[i]; var stepper = steppers[i];
if (stepper.pageIndex == pageIndex) if (stepper.pageIndex == pageIndex) {
stepper.panel.removeAttribute('hidden'); stepper.panel.removeAttribute('hidden');
else } else {
stepper.panel.setAttribute('hidden', true); stepper.panel.setAttribute('hidden', true);
}
} }
var options = stepperChooser.options; var options = stepperChooser.options;
for (var i = 0; i < options.length; ++i) { for (var i = 0; i < options.length; ++i) {
@ -223,8 +232,9 @@ var Stepper = (function StepperClosure() {
// Shorter way to create element and optionally set textContent. // Shorter way to create element and optionally set textContent.
function c(tag, textContent) { function c(tag, textContent) {
var d = document.createElement(tag); var d = document.createElement(tag);
if (textContent) if (textContent) {
d.textContent = textContent; d.textContent = textContent;
}
return d; return d;
} }
@ -297,10 +307,11 @@ var Stepper = (function StepperClosure() {
cbox.checked = checked; cbox.checked = checked;
cbox.onclick = (function(x) { cbox.onclick = (function(x) {
return function() { return function() {
if (this.checked) if (this.checked) {
self.breakPoints.push(x); self.breakPoints.push(x);
else } else {
self.breakPoints.splice(self.breakPoints.indexOf(x), 1); self.breakPoints.splice(self.breakPoints.indexOf(x), 1);
}
StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints); StepperManager.saveBreakPoints(self.pageIndex, self.breakPoints);
}; };
})(i); })(i);
@ -336,8 +347,9 @@ var Stepper = (function StepperClosure() {
getNextBreakPoint: function getNextBreakPoint() { getNextBreakPoint: function getNextBreakPoint() {
this.breakPoints.sort(function(a, b) { return a - b; }); this.breakPoints.sort(function(a, b) { return a - b; });
for (var i = 0; i < this.breakPoints.length; i++) { for (var i = 0; i < this.breakPoints.length; i++) {
if (this.breakPoints[i] > this.currentIdx) if (this.breakPoints[i] > this.currentIdx) {
return this.breakPoints[i]; return this.breakPoints[i];
}
} }
return null; return null;
}, },
@ -385,13 +397,16 @@ var Stepper = (function StepperClosure() {
var Stats = (function Stats() { var Stats = (function Stats() {
var stats = []; var stats = [];
function clear(node) { function clear(node) {
while (node.hasChildNodes()) while (node.hasChildNodes()) {
node.removeChild(node.lastChild); node.removeChild(node.lastChild);
}
} }
function getStatIndex(pageNumber) { function getStatIndex(pageNumber) {
for (var i = 0, ii = stats.length; i < ii; ++i) for (var i = 0, ii = stats.length; i < ii; ++i) {
if (stats[i].pageNumber === pageNumber) if (stats[i].pageNumber === pageNumber) {
return i; return i;
}
}
return false; return false;
} }
return { return {
@ -408,8 +423,9 @@ var Stats = (function Stats() {
active: false, active: false,
// Stats specific functions. // Stats specific functions.
add: function(pageNumber, stat) { add: function(pageNumber, stat) {
if (!stat) if (!stat) {
return; return;
}
var statsIndex = getStatIndex(pageNumber); var statsIndex = getStatIndex(pageNumber);
if (statsIndex !== false) { if (statsIndex !== false) {
var b = stats[statsIndex]; var b = stats[statsIndex];
@ -428,8 +444,9 @@ var Stats = (function Stats() {
stats.push({ pageNumber: pageNumber, div: wrapper }); stats.push({ pageNumber: pageNumber, div: wrapper });
stats.sort(function(a, b) { return a.pageNumber - b.pageNumber; }); stats.sort(function(a, b) { return a.pageNumber - b.pageNumber; });
clear(this.panel); clear(this.panel);
for (var i = 0, ii = stats.length; i < ii; ++i) for (var i = 0, ii = stats.length; i < ii; ++i) {
this.panel.appendChild(stats[i].div); this.panel.appendChild(stats[i].div);
}
} }
}; };
})(); })();
@ -448,12 +465,14 @@ var PDFBug = (function PDFBugClosure() {
], ],
enable: function(ids) { enable: function(ids) {
var all = false, tools = this.tools; var all = false, tools = this.tools;
if (ids.length === 1 && ids[0] === 'all') if (ids.length === 1 && ids[0] === 'all') {
all = true; all = true;
}
for (var i = 0; i < tools.length; ++i) { for (var i = 0; i < tools.length; ++i) {
var tool = tools[i]; var tool = tools[i];
if (all || ids.indexOf(tool.id) !== -1) if (all || ids.indexOf(tool.id) !== -1) {
tool.enabled = true; tool.enabled = true;
}
} }
if (!all) { if (!all) {
// Sort the tools by the order they are enabled. // Sort the tools by the order they are enabled.
@ -509,19 +528,21 @@ var PDFBug = (function PDFBugClosure() {
panels.appendChild(panel); panels.appendChild(panel);
tool.panel = panel; tool.panel = panel;
tool.manager = this; tool.manager = this;
if (tool.enabled) if (tool.enabled) {
tool.init(); tool.init();
else } else {
panel.textContent = tool.name + ' is disabled. To enable add ' + panel.textContent = tool.name + ' is disabled. To enable add ' +
' "' + tool.id + '" to the pdfBug parameter ' + ' "' + tool.id + '" to the pdfBug parameter ' +
'and refresh (seperate multiple by commas).'; 'and refresh (seperate multiple by commas).';
}
buttons.push(panelButton); buttons.push(panelButton);
} }
this.selectPanel(0); this.selectPanel(0);
}, },
selectPanel: function selectPanel(index) { selectPanel: function selectPanel(index) {
if (index === activePanel) if (index === activePanel) {
return; return;
}
activePanel = index; activePanel = index;
var tools = this.tools; var tools = this.tools;
for (var j = 0; j < tools.length; ++j) { for (var j = 0; j < tools.length; ++j) {

View File

@ -52,8 +52,8 @@ var FirefoxCom = (function FirefoxComClosure() {
var request = document.createTextNode(''); var request = document.createTextNode('');
if (callback) { if (callback) {
document.addEventListener('pdf.js.response', function listener(event) { document.addEventListener('pdf.js.response', function listener(event) {
var node = event.target, var node = event.target;
response = event.detail.response; var response = event.detail.response;
document.documentElement.removeChild(node); document.documentElement.removeChild(node);

View File

@ -26,7 +26,6 @@
* searching is done by PDFFindController * searching is done by PDFFindController
*/ */
var PDFFindBar = { var PDFFindBar = {
opened: false, opened: false,
bar: null, bar: null,
toggleButton: null, toggleButton: null,
@ -40,7 +39,7 @@ var PDFFindBar = {
initialize: function(options) { initialize: function(options) {
if(typeof PDFFindController === 'undefined' || PDFFindController === null) { if(typeof PDFFindController === 'undefined' || PDFFindController === null) {
throw 'PDFFindBar cannot be initialized ' + throw 'PDFFindBar cannot be initialized ' +
'without a PDFFindController instance.'; 'without a PDFFindController instance.';
} }
@ -155,8 +154,9 @@ var PDFFindBar = {
}, },
close: function() { close: function() {
if (!this.opened) return; if (!this.opened) {
return;
}
this.opened = false; this.opened = false;
this.toggleButton.classList.remove('toggled'); this.toggleButton.classList.remove('toggled');
this.bar.classList.add('hidden'); this.bar.classList.add('hidden');

View File

@ -13,11 +13,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom, Promise */
'use strict'; 'use strict';
/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom, Promise */
/** /**
* Provides a "search" or "find" functionality for the PDF. * Provides a "search" or "find" functionality for the PDF.
* This object actually performs the search for a given string. * This object actually performs the search for a given string.
@ -157,8 +156,9 @@ var PDFFindController = {
self.pageContents.push(str); self.pageContents.push(str);
extractTextPromisesResolves[pageIndex](pageIndex); extractTextPromisesResolves[pageIndex](pageIndex);
if ((pageIndex + 1) < self.pdfPageSource.pages.length) if ((pageIndex + 1) < self.pdfPageSource.pages.length) {
extractPageText(pageIndex + 1); extractPageText(pageIndex + 1);
}
} }
); );
} }

View File

@ -41,12 +41,12 @@ var TextLayerBuilder = function textLayerBuilder(options) {
this.viewport = options.viewport; this.viewport = options.viewport;
this.isViewerInPresentationMode = options.isViewerInPresentationMode; this.isViewerInPresentationMode = options.isViewerInPresentationMode;
if(typeof PDFFindController === 'undefined') { if (typeof PDFFindController === 'undefined') {
window.PDFFindController = null; window.PDFFindController = null;
} }
if(typeof this.lastScrollSource === 'undefined') { if (typeof this.lastScrollSource === 'undefined') {
this.lastScrollSource = null; this.lastScrollSource = null;
} }
this.beginLayout = function textLayerBuilderBeginLayout() { this.beginLayout = function textLayerBuilderBeginLayout() {
@ -67,8 +67,9 @@ var TextLayerBuilder = function textLayerBuilder(options) {
// No point in rendering so many divs as it'd make the browser unusable // No point in rendering so many divs as it'd make the browser unusable
// even after the divs are rendered // even after the divs are rendered
var MAX_TEXT_DIVS_TO_RENDER = 100000; var MAX_TEXT_DIVS_TO_RENDER = 100000;
if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) {
return; return;
}
for (var i = 0, ii = textDivs.length; i < ii; i++) { for (var i = 0, ii = textDivs.length; i < ii; i++) {
var textDiv = textDivs[i]; var textDiv = textDivs[i];
@ -100,16 +101,17 @@ var TextLayerBuilder = function textLayerBuilder(options) {
// run it right away // run it right away
var RENDER_DELAY = 200; // in ms var RENDER_DELAY = 200; // in ms
var self = this; var self = this;
var lastScroll = this.lastScrollSource === null ? var lastScroll = (this.lastScrollSource === null ?
0 : this.lastScrollSource.lastScroll; 0 : this.lastScrollSource.lastScroll);
if (Date.now() - lastScroll > RENDER_DELAY) { if (Date.now() - lastScroll > RENDER_DELAY) {
// Render right away // Render right away
this.renderLayer(); this.renderLayer();
} else { } else {
// Schedule // Schedule
if (this.renderTimer) if (this.renderTimer) {
clearTimeout(this.renderTimer); clearTimeout(this.renderTimer);
}
this.renderTimer = setTimeout(function() { this.renderTimer = setTimeout(function() {
self.setupRenderLayoutTimer(); self.setupRenderLayoutTimer();
}, RENDER_DELAY); }, RENDER_DELAY);
@ -127,8 +129,8 @@ var TextLayerBuilder = function textLayerBuilder(options) {
textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontSize = fontHeight + 'px';
textDiv.style.fontFamily = geom.fontFamily; textDiv.style.fontFamily = geom.fontFamily;
var fontAscent = geom.ascent ? geom.ascent * fontHeight : var fontAscent = (geom.ascent ? geom.ascent * fontHeight :
geom.descent ? (1 + geom.descent) * fontHeight : fontHeight; (geom.descent ? (1 + geom.descent) * fontHeight : fontHeight));
textDiv.style.left = (geom.x + (fontAscent * Math.sin(geom.angle))) + 'px'; textDiv.style.left = (geom.x + (fontAscent * Math.sin(geom.angle))) + 'px';
textDiv.style.top = (geom.y - (fontAscent * Math.cos(geom.angle))) + 'px'; textDiv.style.top = (geom.y - (fontAscent * Math.cos(geom.angle))) + 'px';
@ -140,8 +142,9 @@ var TextLayerBuilder = function textLayerBuilder(options) {
this.insertDivContent = function textLayerUpdateTextContent() { this.insertDivContent = function textLayerUpdateTextContent() {
// Only set the content of the divs once layout has finished, the content // Only set the content of the divs once layout has finished, the content
// for the divs is available and content is not yet set on the divs. // for the divs is available and content is not yet set on the divs.
if (!this.layoutDone || this.divContentDone || !this.textContent) if (!this.layoutDone || this.divContentDone || !this.textContent) {
return; return;
}
this.divContentDone = true; this.divContentDone = true;
@ -180,8 +183,8 @@ var TextLayerBuilder = function textLayerBuilder(options) {
var iIndex = 0; var iIndex = 0;
var bidiTexts = this.textContent; var bidiTexts = this.textContent;
var end = bidiTexts.length - 1; var end = bidiTexts.length - 1;
var queryLen = PDFFindController === null ? var queryLen = (PDFFindController === null ?
0 : PDFFindController.state.query.length; 0 : PDFFindController.state.query.length);
var lastDivIdx = -1; var lastDivIdx = -1;
var pos; var pos;
@ -240,14 +243,14 @@ var TextLayerBuilder = function textLayerBuilder(options) {
var bidiTexts = this.textContent; var bidiTexts = this.textContent;
var textDivs = this.textDivs; var textDivs = this.textDivs;
var prevEnd = null; var prevEnd = null;
var isSelectedPage = PDFFindController === null ? var isSelectedPage = (PDFFindController === null ?
false : (this.pageIdx === PDFFindController.selected.pageIdx); false : (this.pageIdx === PDFFindController.selected.pageIdx));
var selectedMatchIdx = PDFFindController === null ? var selectedMatchIdx = (PDFFindController === null ?
-1 : PDFFindController.selected.matchIdx; -1 : PDFFindController.selected.matchIdx);
var highlightAll = PDFFindController === null ? var highlightAll = (PDFFindController === null ?
false : PDFFindController.state.highlightAll; false : PDFFindController.state.highlightAll);
var infty = { var infty = {
divIdx: -1, divIdx: -1,
@ -346,8 +349,9 @@ var TextLayerBuilder = function textLayerBuilder(options) {
this.updateMatches = function textLayerUpdateMatches() { this.updateMatches = function textLayerUpdateMatches() {
// Only show matches, once all rendering is done. // Only show matches, once all rendering is done.
if (!this.renderingDone) if (!this.renderingDone) {
return; return;
}
// Clear out all matches. // Clear out all matches.
var matches = this.matches; var matches = this.matches;
@ -367,14 +371,14 @@ var TextLayerBuilder = function textLayerBuilder(options) {
clearedUntilDivIdx = match.end.divIdx + 1; clearedUntilDivIdx = match.end.divIdx + 1;
} }
if (PDFFindController === null || !PDFFindController.active) if (PDFFindController === null || !PDFFindController.active) {
return; return;
}
// Convert the matches on the page controller into the match format used // Convert the matches on the page controller into the match format used
// for the textLayer. // for the textLayer.
this.matches = matches = this.matches = matches = (this.convertMatches(PDFFindController === null ?
this.convertMatches(PDFFindController === null ? [] : (PDFFindController.pageMatches[this.pageIdx] || [])));
[] : (PDFFindController.pageMatches[this.pageIdx] || []));
this.renderMatches(this.matches); this.renderMatches(this.matches);
}; };

View File

@ -24,10 +24,9 @@ var CustomStyle = (function CustomStyleClosure() {
// in some versions of IE9 it is critical that ms appear in this list // in some versions of IE9 it is critical that ms appear in this list
// before Moz // before Moz
var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
var _cache = { }; var _cache = {};
function CustomStyle() { function CustomStyle() {}
}
CustomStyle.getProp = function get(propName, element) { CustomStyle.getProp = function get(propName, element) {
// check cache only when no element is given // check cache only when no element is given
@ -60,8 +59,9 @@ var CustomStyle = (function CustomStyleClosure() {
CustomStyle.setProp = function set(propName, element, str) { CustomStyle.setProp = function set(propName, element, str) {
var prop = this.getProp(propName); var prop = this.getProp(propName);
if (prop != 'undefined') if (prop != 'undefined') {
element.style[prop] = str; element.style[prop] = str;
}
}; };
return CustomStyle; return CustomStyle;
@ -247,11 +247,13 @@ var Cache = function cacheCache(size) {
var data = []; var data = [];
this.push = function cachePush(view) { this.push = function cachePush(view) {
var i = data.indexOf(view); var i = data.indexOf(view);
if (i >= 0) if (i >= 0) {
data.splice(i); data.splice(i);
}
data.push(view); data.push(view);
if (data.length > size) if (data.length > size) {
data.shift().destroy(); data.shift().destroy();
}
}; };
}; };

View File

@ -225,10 +225,11 @@ var PDFView = {
viewAreaElement.addEventListener('scroll', function webViewerScroll(evt) { viewAreaElement.addEventListener('scroll', function webViewerScroll(evt) {
var currentY = viewAreaElement.scrollTop; var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY; var lastY = state.lastY;
if (currentY > lastY) if (currentY > lastY) {
state.down = true; state.down = true;
else if (currentY < lastY) } else if (currentY < lastY) {
state.down = false; state.down = false;
}
// else do nothing and use previous value // else do nothing and use previous value
state.lastY = currentY; state.lastY = currentY;
callback(); callback();
@ -491,8 +492,9 @@ var PDFView = {
} }
var args = e.data; var args = e.data;
if (typeof args !== 'object' || !('pdfjsLoadAction' in args)) if (typeof args !== 'object' || !('pdfjsLoadAction' in args)) {
return; return;
}
switch (args.pdfjsLoadAction) { switch (args.pdfjsLoadAction) {
case 'supportsRangedLoading': case 'supportsRangedLoading':
PDFView.open(args.pdfUrl, 0, undefined, pdfDataRangeTransport, { PDFView.open(args.pdfUrl, 0, undefined, pdfDataRangeTransport, {
@ -703,8 +705,9 @@ var PDFView = {
}, },
getDestinationHash: function pdfViewGetDestinationHash(dest) { getDestinationHash: function pdfViewGetDestinationHash(dest) {
if (typeof dest === 'string') if (typeof dest === 'string') {
return PDFView.getAnchorUrl('#' + escape(dest)); return PDFView.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) { if (dest instanceof Array) {
var destRef = dest[0]; // see navigateTo method for dest format var destRef = dest[0]; // see navigateTo method for dest format
var pageNumber = destRef instanceof Object ? var pageNumber = destRef instanceof Object ?
@ -864,15 +867,18 @@ var PDFView = {
var thumbsView = document.getElementById('thumbnailView'); var thumbsView = document.getElementById('thumbnailView');
thumbsView.parentNode.scrollTop = 0; thumbsView.parentNode.scrollTop = 0;
while (thumbsView.hasChildNodes()) while (thumbsView.hasChildNodes()) {
thumbsView.removeChild(thumbsView.lastChild); thumbsView.removeChild(thumbsView.lastChild);
}
if ('_loadingInterval' in thumbsView) if ('_loadingInterval' in thumbsView) {
clearInterval(thumbsView._loadingInterval); clearInterval(thumbsView._loadingInterval);
}
var container = document.getElementById('viewer'); var container = document.getElementById('viewer');
while (container.hasChildNodes()) while (container.hasChildNodes()) {
container.removeChild(container.lastChild); container.removeChild(container.lastChild);
}
var pagesCount = pdfDocument.numPages; var pagesCount = pdfDocument.numPages;
@ -1041,16 +1047,17 @@ var PDFView = {
(PDFJS.version ? ' (PDF.js: ' + PDFJS.version + ')' : '')); (PDFJS.version ? ' (PDF.js: ' + PDFJS.version + ')' : ''));
var pdfTitle; var pdfTitle;
if (metadata) { if (metadata && metadata.has('dc:title')) {
if (metadata.has('dc:title')) pdfTitle = metadata.get('dc:title');
pdfTitle = metadata.get('dc:title');
} }
if (!pdfTitle && info && info['Title']) if (!pdfTitle && info && info['Title']) {
pdfTitle = info['Title']; pdfTitle = info['Title'];
}
if (pdfTitle) if (pdfTitle) {
self.setTitle(pdfTitle + ' - ' + document.title); self.setTitle(pdfTitle + ' - ' + document.title);
}
if (info.IsAcroFormPresent) { if (info.IsAcroFormPresent) {
console.warn('Warning: AcroForm/XFA is not supported'); console.warn('Warning: AcroForm/XFA is not supported');
@ -1178,21 +1185,24 @@ var PDFView = {
} }
for (var i = 0; i < numVisible; ++i) { for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view; var view = visibleViews[i].view;
if (!this.isViewFinished(view)) if (!this.isViewFinished(view)) {
return view; return view;
}
} }
// All the visible views have rendered, try to render next/previous pages. // All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) { if (scrolledDown) {
var nextPageIndex = visible.last.id; var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1. // ID's start at 1 so no need to add 1.
if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex]; return views[nextPageIndex];
}
} else { } else {
var previousPageIndex = visible.first.id - 2; var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] && if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex])) !this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex]; return views[previousPageIndex];
}
} }
// Everything that needs to be rendered has been. // Everything that needs to be rendered has been.
return false; return false;
@ -1225,8 +1235,9 @@ var PDFView = {
}, },
setHash: function pdfViewSetHash(hash) { setHash: function pdfViewSetHash(hash) {
if (!hash) if (!hash) {
return; return;
}
if (hash.indexOf('=') >= 0) { if (hash.indexOf('=') >= 0) {
var params = PDFView.parseQueryString(hash); var params = PDFView.parseQueryString(hash);
@ -1314,8 +1325,9 @@ var PDFView = {
thumbsView.classList.add('hidden'); thumbsView.classList.add('hidden');
outlineView.classList.remove('hidden'); outlineView.classList.remove('hidden');
if (outlineButton.getAttribute('disabled')) if (outlineButton.getAttribute('disabled')) {
return; return;
}
break; break;
} }
}, },
@ -1432,8 +1444,9 @@ var PDFView = {
afterPrint: function pdfViewSetupAfterPrint() { afterPrint: function pdfViewSetupAfterPrint() {
var div = document.getElementById('printContainer'); var div = document.getElementById('printContainer');
while (div.hasChildNodes()) while (div.hasChildNodes()) {
div.removeChild(div.lastChild); div.removeChild(div.lastChild);
}
}, },
rotatePages: function pdfViewRotatePages(delta) { rotatePages: function pdfViewRotatePages(delta) {
@ -1475,14 +1488,16 @@ var PDFView = {
// In case one page has already been flipped there is a cooldown time // In case one page has already been flipped there is a cooldown time
// which has to expire before next page can be scrolled on to. // which has to expire before next page can be scrolled on to.
if (currentTime > storedTime && if (currentTime > storedTime &&
currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) currentTime - storedTime < MOUSE_SCROLL_COOLDOWN_TIME) {
return; return;
}
// In case the user decides to scroll to the opposite direction than before // In case the user decides to scroll to the opposite direction than before
// clear the accumulated delta. // clear the accumulated delta.
if ((this.mouseScrollDelta > 0 && mouseScrollDelta < 0) || if ((this.mouseScrollDelta > 0 && mouseScrollDelta < 0) ||
(this.mouseScrollDelta < 0 && mouseScrollDelta > 0)) (this.mouseScrollDelta < 0 && mouseScrollDelta > 0)) {
this.clearMouseScrollState(); this.clearMouseScrollState();
}
this.mouseScrollDelta += mouseScrollDelta; this.mouseScrollDelta += mouseScrollDelta;
@ -1505,8 +1520,9 @@ var PDFView = {
// to do anything. // to do anything.
if ((currentPage == 1 && pageFlipDirection == PageFlipDirection.UP) || if ((currentPage == 1 && pageFlipDirection == PageFlipDirection.UP) ||
(currentPage == this.pages.length && (currentPage == this.pages.length &&
pageFlipDirection == PageFlipDirection.DOWN)) pageFlipDirection == PageFlipDirection.DOWN)) {
return; return;
}
this.page += pageFlipDirection; this.page += pageFlipDirection;
this.mouseScrollTimeStamp = currentTime; this.mouseScrollTimeStamp = currentTime;
@ -1532,13 +1548,14 @@ var PDFView = {
var DocumentOutlineView = function documentOutlineView(outline) { var DocumentOutlineView = function documentOutlineView(outline) {
var outlineView = document.getElementById('outlineView'); var outlineView = document.getElementById('outlineView');
var outlineButton = document.getElementById('viewOutline'); var outlineButton = document.getElementById('viewOutline');
while (outlineView.firstChild) while (outlineView.firstChild) {
outlineView.removeChild(outlineView.firstChild); outlineView.removeChild(outlineView.firstChild);
}
if (!outline) { if (!outline) {
if (!outlineView.classList.contains('hidden')) if (!outlineView.classList.contains('hidden')) {
PDFView.switchSidebarView('thumbs'); PDFView.switchSidebarView('thumbs');
}
return; return;
} }
@ -1667,8 +1684,9 @@ function webViewerLoad(evt) {
//#if !(FIREFOX || MOZCENTRAL) //#if !(FIREFOX || MOZCENTRAL)
var locale = PDFJS.locale || navigator.language; var locale = PDFJS.locale || navigator.language;
if ('locale' in hashParams) if ('locale' in hashParams) {
locale = hashParams['locale']; locale = hashParams['locale'];
}
mozL10n.setLanguage(locale); mozL10n.setLanguage(locale);
//#endif //#endif
//#if (FIREFOX || MOZCENTRAL) //#if (FIREFOX || MOZCENTRAL)
@ -1855,8 +1873,9 @@ document.addEventListener('DOMContentLoaded', webViewerLoad, true);
function updateViewarea() { function updateViewarea() {
if (!PDFView.initialized) if (!PDFView.initialized) {
return; return;
}
var visible = PDFView.getVisiblePages(); var visible = PDFView.getVisiblePages();
var visiblePages = visible.views; var visiblePages = visible.views;
if (visiblePages.length === 0) { if (visiblePages.length === 0) {
@ -1872,9 +1891,9 @@ function updateViewarea() {
i < ii; ++i) { i < ii; ++i) {
var page = visiblePages[i]; var page = visiblePages[i];
if (page.percent < 100) if (page.percent < 100) {
break; break;
}
if (page.id === PDFView.page) { if (page.id === PDFView.page) {
stillFullyVisible = true; stillFullyVisible = true;
break; break;
@ -1951,9 +1970,9 @@ window.addEventListener('hashchange', function webViewerHashchange(evt) {
//#if !(FIREFOX || MOZCENTRAL || CHROME) //#if !(FIREFOX || MOZCENTRAL || CHROME)
window.addEventListener('change', function webViewerChange(evt) { window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files; var files = evt.target.files;
if (!files || files.length === 0) if (!files || files.length === 0) {
return; return;
}
var file = files[0]; var file = files[0];
if (!PDFJS.disableCreateObjectURL && if (!PDFJS.disableCreateObjectURL &&