TagSpaces is an offline, open source, document manager with tagging support
Downgrading to a old pdf.js lib, due incorpartabilities in PDF rendering of images
Iliana715bff2733d
diff --git a/data/ext/viewerPDF/pdfjs/LICENSE[apache2].txt b/data/ext/viewerPDF/LICENSE[apache2].txtsimilarity index 100%rename from data/ext/viewerPDF/pdfjs/LICENSE[apache2].txtrename to data/ext/viewerPDF/LICENSE[apache2].txtdiff --git a/data/ext/viewerPDF/README.md b/data/ext/viewerPDF/README.mddeleted file mode 100644index afbaf7933..000000000--- a/data/ext/viewerPDF/README.md+++ /dev/null@@ -1,33 +0,0 @@--## Introduction--`TagSpaces` is a open source application for managing of your local files. You can find more information about it on its website [tagspaces.org](http://tagspaces.org/). For a quick TagSpaces introduction please see this [video](https://www.youtube.com/embed/CJ2hYU6U-C8) on youtube.--- [TagSpaces blog](http://tagspaces.org/blog/) for any news about tagspaces-- [the issues tracker](https://github.com/uggrock/tagspaces/issues) for developer support requests-- [the TagSpaces wiki](https://github.com/uggrock/tagspaces/wiki) for end-users and implementors (currently not really used)--To get updates you can:-- Subscribe to GitHub updates by clicking the "watch" button up the top right of this page.-- Subscribe to RSS feed updates for the [master branch](https://github.com/uggrock/tagspaces/commits/master.atom)--## Features--* **open pdf files:**--## Screenshots----## Documentation--## License--`TagSpaces`'s code uses the AGPL (GNU Affero General Public License) Version 3, see our `LICENSE` file.--## Feeds-- Subscribe to RSS feed updates for the [tagspaces blog](http://tagspaces.org/blog/feed.xml)-- Subscribe to RSS feed updates for the [master branch](https://github.com/uggrock/tagspace/commits/master.atom)--- - --This files is created and edited in `TagSpaces`, using the `viewerMD` and `[editorText]()` extensions.\ No newline at end of filediff --git a/data/ext/viewerPDF/pdfjs/web/compatibility.js b/data/ext/viewerPDF/compatibility.jssimilarity index 84%rename from data/ext/viewerPDF/pdfjs/web/compatibility.jsrename to data/ext/viewerPDF/compatibility.jsindex 64ce745bd..e9b69ed07 100644--- a/data/ext/viewerPDF/pdfjs/web/compatibility.js+++ b/data/ext/viewerPDF/compatibility.js@@ -92,13 +92,6 @@ if (typeof PDFJS === 'undefined') {window.Float64Array = TypedArray;})();-// URL = URL || webkitURL-(function normalizeURLObject() {- if (!window.URL) {- window.URL = window.webkitURL;- }-})();-// Object.create() ?(function checkObjectCreateCompatibility() {if (typeof Object.create !== 'undefined')@@ -268,36 +261,6 @@ if (typeof PDFJS === 'undefined') {};})();-// window.atob (base64 encode function) ?-(function checkWindowAtobCompatibility() {- if ('atob' in window)- return;-- // https://github.com/davidchambers/Base64.js- var digits =- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';- window.atob = function (input) {- input = input.replace(/=+$/, '');- if (input.length % 4 == 1) throw new Error('bad atob input');- for (- // initialize result and counters- var bc = 0, bs, buffer, idx = 0, output = '';- // get next character- buffer = input.charAt(idx++);- // character found in table?- // initialize bit storage and add its ascii value- ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,- // and if not first of each 4 characters,- // convert the first 8 bits to one ascii character- bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0- ) {- // try to find character in table (0-63, not found => -1)- buffer = digits.indexOf(buffer);- }- return output;- };-})();-// Function.prototype.bind ?(function checkFunctionPrototypeBindCompatibility() {if (typeof Function.prototype.bind !== 'undefined')@@ -306,13 +269,42 @@ if (typeof PDFJS === 'undefined') {Function.prototype.bind = function functionPrototypeBind(obj) {var fn = this, headArgs = Array.prototype.slice.call(arguments, 1);var bound = function functionPrototypeBindBound() {- var args = headArgs.concat(Array.prototype.slice.call(arguments));+ var args = Array.prototype.concat.apply(headArgs, arguments);return fn.apply(obj, args);};return bound;};})();+// IE9-11 text/html data URI+(function checkDataURICompatibility() {+ if (!('documentMode' in document) || document.documentMode > 11)+ return;+ // overriding the src property+ var originalSrcDescriptor = Object.getOwnPropertyDescriptor(+ HTMLIFrameElement.prototype, 'src');+ Object.defineProperty(HTMLIFrameElement.prototype, 'src', {+ get: function htmlIFrameElementPrototypeSrcGet() { return this.$src; },+ set: function htmlIFrameElementPrototypeSrcSet(src) {+ this.$src = src;+ if (src.substr(0, 14) != 'data:text/html') {+ originalSrcDescriptor.set.call(this, src);+ return;+ }+ // for text/html, using blank document and then+ // document's open, write, and close operations+ originalSrcDescriptor.set.call(this, 'about:blank');+ setTimeout((function htmlIFrameElementPrototypeSrcOpenWriteClose() {+ var doc = this.contentDocument;+ doc.open('text/html');+ doc.write(src.substr(src.indexOf(',') + 1));+ doc.close();+ }).bind(this), 0);+ },+ enumerable: true+ });+})();+// HTMLElement dataset property(function checkDatasetProperty() {var div = document.createElement('div');@@ -361,16 +353,12 @@ if (typeof PDFJS === 'undefined') {if (index >= 0 && remove)list.splice(index, 1);element.className = list.join(' ');- return (index >= 0);}var classListPrototype = {add: function(name) {changeList(this.element, name, true, false);},- contains: function(name) {- return changeList(this.element, name, false, false);- },remove: function(name) {changeList(this.element, name, false, true);},@@ -442,30 +430,18 @@ if (typeof PDFJS === 'undefined') {}})();-// Checks if possible to use URL.createObjectURL()-(function checkOnBlobSupport() {- // sometimes IE loosing the data created with createObjectURL(), see #3977- if (navigator.userAgent.indexOf('Trident') >= 0) {- PDFJS.disableCreateObjectURL = true;- }-})();-// Checks if navigator.language is supported(function checkNavigatorLanguage() {- if ('language' in navigator &&- /^[a-z]+(-[A-Z]+)?$/.test(navigator.language)) {+ if ('language' in navigator)return;- }- function formatLocale(locale) {- var split = locale.split(/[-_]/);- split[0] = split[0].toLowerCase();- if (split.length > 1) {- split[1] = split[1].toUpperCase();- }- return split.join('-');- }- var language = navigator.language || navigator.userLanguage || 'en-US';- PDFJS.locale = formatLocale(language);+ Object.defineProperty(navigator, 'language', {+ get: function navigatorLanguage() {+ var language = navigator.userLanguage || 'en-US';+ return language.substring(0, 2).toLowerCase() ++ language.substring(2).toUpperCase();+ },+ enumerable: true+ });})();(function checkRangeRequests() {@@ -474,15 +450,7 @@ if (typeof PDFJS === 'undefined') {// Last tested with version 6.0.4.var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;-- // Older versions of Android (pre 3.0) has issues with range requests, see:- // https://github.com/mozilla/pdf.js/issues/3381.- // Make sure that we only match webkit-based Android browsers,- // since Firefox/Fennec works as expected.- var regex = /Android\s[0-2][^\d]/;- var isOldAndroid = regex.test(navigator.userAgent);-- if (isSafari || isOldAndroid) {+ if (isSafari) {PDFJS.disableRange = true;}})();diff --git a/data/ext/viewerPDF/pdfjs/web/debugger.js b/data/ext/viewerPDF/debugger.jssimilarity index 89%rename from data/ext/viewerPDF/pdfjs/web/debugger.jsrename to data/ext/viewerPDF/debugger.jsindex a70ad0cd9..2305bb773 100644--- a/data/ext/viewerPDF/pdfjs/web/debugger.js+++ b/data/ext/viewerPDF/debugger.js@@ -220,47 +220,26 @@ var StepperManager = (function StepperManagerClosure() {// The stepper for each page's IRQueue.var Stepper = (function StepperClosure() {- // Shorter way to create element and optionally set textContent.- function c(tag, textContent) {- var d = document.createElement(tag);- if (textContent)- d.textContent = textContent;- return d;- }-- function glyphsToString(glyphs) {- var out = '';- for (var i = 0; i < glyphs.length; i++) {- if (glyphs[i] === null) {- out += ' ';- } else {- out += glyphs[i].fontChar;- }- }- return out;- }-- var opMap = null;-- var glyphCommands = {- 'showText': 0,- 'showSpacedText': 0,- 'nextLineShowText': 0,- 'nextLineSetSpacingShowText': 2- };-function Stepper(panel, pageIndex, initialBreakPoints) {this.panel = panel;+ this.len = 0;this.breakPoint = 0;this.nextBreakPoint = null;this.pageIndex = pageIndex;this.breakPoints = initialBreakPoints;this.currentIdx = -1;- this.operatorListIdx = 0;}Stepper.prototype = {- init: function init() {+ init: function init(IRQueue) {+ // Shorter way to create element and optionally set textContent.+ function c(tag, textContent) {+ var d = document.createElement(tag);+ if (textContent)+ d.textContent = textContent;+ return d;+ }var panel = this.panel;+ this.len = IRQueue.fnArray.length;var content = c('div', 'c=continue, s=step');var table = c('table');content.appendChild(table);@@ -271,24 +250,15 @@ var Stepper = (function StepperClosure() {headerRow.appendChild(c('th', 'Idx'));headerRow.appendChild(c('th', 'fn'));headerRow.appendChild(c('th', 'args'));- panel.appendChild(content);- this.table = table;- if (!opMap) {- opMap = Object.create(null);- for (var key in PDFJS.OPS) {- opMap[PDFJS.OPS[key]] = key;- }- }- },- updateOperatorList: function updateOperatorList(operatorList) {+var self = this;- for (var i = this.operatorListIdx; i < operatorList.fnArray.length; i++) {+ for (var i = 0; i < IRQueue.fnArray.length; i++) {var line = c('tr');line.className = 'line';line.dataset.idx = i;- this.table.appendChild(line);+ table.appendChild(line);var checked = this.breakPoints.indexOf(i) != -1;- var args = operatorList.argsArray[i] ? operatorList.argsArray[i] : [];+ var args = IRQueue.argsArray[i] ? IRQueue.argsArray[i] : [];var breakCell = c('td');var cbox = c('input');@@ -308,30 +278,11 @@ var Stepper = (function StepperClosure() {breakCell.appendChild(cbox);line.appendChild(breakCell);line.appendChild(c('td', i.toString()));- var fn = opMap[operatorList.fnArray[i]];- var decArgs = args;- if (fn in glyphCommands) {- var glyphIndex = glyphCommands[fn];- var glyphs = args[glyphIndex];- var decArgs = args.slice();- var newArg;- if (fn === 'showSpacedText') {- newArg = [];- for (var j = 0; j < glyphs.length; j++) {- if (typeof glyphs[j] === 'number') {- newArg.push(glyphs[j]);- } else {- newArg.push(glyphsToString(glyphs[j]));- }- }- } else {- newArg = glyphsToString(glyphs);- }- decArgs[glyphIndex] = newArg;- }- line.appendChild(c('td', fn));- line.appendChild(c('td', JSON.stringify(decArgs)));+ line.appendChild(c('td', IRQueue.fnArray[i]));+ line.appendChild(c('td', args.join(', ')));}+ panel.appendChild(content);+ var self = this;},getNextBreakPoint: function getNextBreakPoint() {this.breakPoints.sort(function(a, b) { return a - b; });diff --git a/data/ext/viewerPDF/extension.js b/data/ext/viewerPDF/extension.jsindex 0db7102dd..ab214cca0 100644--- a/data/ext/viewerPDF/extension.js+++ b/data/ext/viewerPDF/extension.js@@ -16,32 +16,26 @@ define(function(require, exports, module) {var extensionDirectory = TSCORE.Config.getExtensionPath()+"/"+exports.id;- exports.init = function(filePath, elementID) {- console.log("Initalization Browser PDF Viewer...");- var extPath = extensionDirectory+"/pdfjs/web/viewer.html";+ exports.init = function(filePath, elementID) {+ console.log("Initalization Browser PDF Viewer...");+ var extPath = extensionDirectory+"/index.html";$('#'+elementID).append($('<iframe>', {id: "iframeViewer",src: extPath+"?cp="+filePath,"nwdisable": "",- "nwfaketop": "",- }));-- // TODO ext lib integration- // require([extensionDirectory+'/croppr.js'], function() {- //- // });+ "nwfaketop": ""+ }));};- exports.viewerMode = function(isViewerMode) {+ exports.viewerMode = function() {console.log("viewerMode not supported on this extension");- }+ };- exports.setContent = function(content) {+ exports.setContent = function() {console.log("setContent not supported on this extension");- }+ };exports.getContent = function() {console.log("getContent not supported on this extension");- }--});\ No newline at end of file+ };+});diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-check.svg b/data/ext/viewerPDF/images/annotation-check.svgsimilarity index 90%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-check.svgrename to data/ext/viewerPDF/images/annotation-check.svgindex 71cd16df5..f28f0e89a 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-check.svg+++ b/data/ext/viewerPDF/images/annotation-check.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40"- viewBox="0 0 40 40">+ height="40"><pathd="M 1.5006714,23.536225 6.8925879,18.994244 14.585721,26.037937 34.019683,4.5410479 38.499329,9.2235032 14.585721,35.458952 z"id="path4"diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svg b/data/ext/viewerPDF/images/annotation-comment.svgsimilarity index 95%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svgrename to data/ext/viewerPDF/images/annotation-comment.svgindex 86f1f1724..b2aee63e5 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-comment.svg+++ b/data/ext/viewerPDF/images/annotation-comment.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"height="40"- width="40"- viewBox="0 0 40 40">+ width="40"><rectstyle="fill:#ffff00;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"width="33.76017"diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-help.svg b/data/ext/viewerPDF/images/annotation-help.svgsimilarity index 98%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-help.svgrename to data/ext/viewerPDF/images/annotation-help.svgindex 00938fefe..349112ef3 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-help.svg+++ b/data/ext/viewerPDF/images/annotation-help.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40"- viewBox="0 0 40 40">+ height="40"><gtransform="translate(0,-60)"id="layer1">diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svg b/data/ext/viewerPDF/images/annotation-insert.svgsimilarity index 90%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svgrename to data/ext/viewerPDF/images/annotation-insert.svgindex 519ef6826..60fbf954c 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-insert.svg+++ b/data/ext/viewerPDF/images/annotation-insert.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64"- viewBox="0 0 64 64">+ height="64"><pathd="M 32.003143,1.4044602 57.432701,62.632577 6.5672991,62.627924 z"style="fill:#ffff00;fill-opacity:0.94117647;fill-rule:nonzero;stroke:#000000;stroke-width:1.00493038;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-key.svg b/data/ext/viewerPDF/images/annotation-key.svgsimilarity index 97%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-key.svgrename to data/ext/viewerPDF/images/annotation-key.svgindex 8d09d5378..c0bbb09c5 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-key.svg+++ b/data/ext/viewerPDF/images/annotation-key.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64"- viewBox="0 0 64 64">+ height="64"><pathd="M 25.470843,9.4933766 C 25.30219,12.141818 30.139101,14.445969 34.704831,13.529144 40.62635,12.541995 41.398833,7.3856498 35.97505,5.777863 31.400921,4.1549155 25.157674,6.5445892 25.470843,9.4933766 z M 4.5246282,17.652051 C 4.068249,11.832873 9.2742983,5.9270407 18.437379,3.0977088 29.751911,-0.87185184 45.495663,1.4008022 53.603953,7.1104009 c 9.275765,6.1889221 7.158128,16.2079421 -3.171076,21.5939521 -1.784316,1.635815 -6.380222,1.21421 -7.068351,3.186186 -1.04003,0.972427 -1.288046,2.050158 -1.232864,3.168203 1.015111,2.000108 -3.831548,1.633216 -3.270553,3.759574 0.589477,5.264544 -0.179276,10.53738 -0.362842,15.806257 -0.492006,2.184998 1.163456,4.574232 -0.734888,6.610642 -2.482919,2.325184 -7.30604,2.189143 -9.193497,-0.274767 -2.733688,-1.740626 -8.254447,-3.615254 -6.104247,-6.339626 3.468112,-1.708686 -2.116197,-3.449897 0.431242,-5.080274 5.058402,-1.39256 -2.393215,-2.304318 -0.146889,-4.334645 3.069198,-0.977415 2.056986,-2.518352 -0.219121,-3.540397 1.876567,-1.807151 1.484149,-4.868919 -2.565455,-5.942205 0.150866,-1.805474 2.905737,-4.136876 -1.679967,-5.20493 C 10.260902,27.882167 4.6872697,22.95045 4.5245945,17.652051 z"id="path604"diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svg b/data/ext/viewerPDF/images/annotation-newparagraph.svgsimilarity index 90%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svgrename to data/ext/viewerPDF/images/annotation-newparagraph.svgindex 38d2497da..6c179fd3f 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-newparagraph.svg+++ b/data/ext/viewerPDF/images/annotation-newparagraph.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="64"- height="64"- viewBox="0 0 64 64">+ height="64"><pathd="M 32.003143,10.913072 57.432701,53.086929 6.567299,53.083723 z"id="path2985"diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-note.svg b/data/ext/viewerPDF/images/annotation-note.svgsimilarity index 96%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-note.svgrename to data/ext/viewerPDF/images/annotation-note.svgindex 70173651c..ed169439b 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-note.svg+++ b/data/ext/viewerPDF/images/annotation-note.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40"- viewBox="0 0 40 40">+ height="40"><rectwidth="36.075428"height="31.096582"diff --git a/data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svg b/data/ext/viewerPDF/images/annotation-paragraph.svgsimilarity index 96%rename from data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svgrename to data/ext/viewerPDF/images/annotation-paragraph.svgindex 6ae5212b7..6fd90c19f 100644--- a/data/ext/viewerPDF/pdfjs/web/images/annotation-paragraph.svg+++ b/data/ext/viewerPDF/images/annotation-paragraph.svg@@ -2,8 +2,7 @@<svgxmlns="http://www.w3.org/2000/svg"width="40"- height="40"- viewBox="0 0 40 40">+ height="40"><rectwidth="33.76017"height="33.76017"diff --git a/data/ext/viewerPDF/images/findbarButton-next-rtl.png b/data/ext/viewerPDF/images/findbarButton-next-rtl.pngnew file mode 100644index 000000000..08a2c2532Binary files /dev/null and b/data/ext/viewerPDF/images/findbarButton-next-rtl.png differdiff --git a/data/ext/viewerPDF/images/findbarButton-next.png b/data/ext/viewerPDF/images/findbarButton-next.pngnew file mode 100644index 000000000..beef8cceaBinary files /dev/null and b/data/ext/viewerPDF/images/findbarButton-next.png differdiff --git a/data/ext/viewerPDF/images/findbarButton-previous-rtl.png b/data/ext/viewerPDF/images/findbarButton-previous-rtl.pngnew file mode 100644index 000000000..beef8cceaBinary files /dev/null and b/data/ext/viewerPDF/images/findbarButton-previous-rtl.png differdiff --git a/data/ext/viewerPDF/images/findbarButton-previous.png b/data/ext/viewerPDF/images/findbarButton-previous.pngnew file mode 100644index 000000000..08a2c2532Binary files /dev/null and b/data/ext/viewerPDF/images/findbarButton-previous.png differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/loading-icon.gif b/data/ext/viewerPDF/images/loading-icon.gifsimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/images/loading-icon.gifrename to data/ext/viewerPDF/images/loading-icon.gifdiff --git a/data/ext/viewerPDF/images/loading-small.png b/data/ext/viewerPDF/images/loading-small.pngnew file mode 100644index 000000000..1b2df8093Binary files /dev/null and b/data/ext/viewerPDF/images/loading-small.png differdiff --git a/data/ext/viewerPDF/images/shadow.png b/data/ext/viewerPDF/images/shadow.pngnew file mode 100644index 000000000..dd009dc4eBinary files /dev/null and b/data/ext/viewerPDF/images/shadow.png differdiff --git a/data/ext/viewerPDF/images/test.pdf b/data/ext/viewerPDF/images/test.pdfnew file mode 100644index 000000000..0b83684e4Binary files /dev/null and b/data/ext/viewerPDF/images/test.pdf differdiff --git a/data/ext/viewerPDF/images/texture.png b/data/ext/viewerPDF/images/texture.pngnew file mode 100644index 000000000..df0086493Binary files /dev/null and b/data/ext/viewerPDF/images/texture.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-bookmark.png b/data/ext/viewerPDF/images/toolbarButton-bookmark.pngnew file mode 100644index 000000000..1e5259a97Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-bookmark.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-download.png b/data/ext/viewerPDF/images/toolbarButton-download.pngnew file mode 100644index 000000000..8676d8e2cBinary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-download.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-menuArrows.png b/data/ext/viewerPDF/images/toolbarButton-menuArrows.pngnew file mode 100644index 000000000..31b06b5afBinary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-menuArrows.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-openFile.png b/data/ext/viewerPDF/images/toolbarButton-openFile.pngnew file mode 100644index 000000000..fc7023f2aBinary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-openFile.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.png b/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.pngnew file mode 100644index 000000000..c0051f8f0Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-pageDown-rtl.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageDown.png b/data/ext/viewerPDF/images/toolbarButton-pageDown.pngnew file mode 100644index 000000000..762ac43e0Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-pageDown.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.png b/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.pngnew file mode 100644index 000000000..0d49d8e95Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-pageUp-rtl.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-pageUp.png b/data/ext/viewerPDF/images/toolbarButton-pageUp.pngnew file mode 100644index 000000000..3155b8bd2Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-pageUp.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-presentationMode.png b/data/ext/viewerPDF/images/toolbarButton-presentationMode.pngnew file mode 100644index 000000000..fa7309550Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-presentationMode.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-print.png b/data/ext/viewerPDF/images/toolbarButton-print.pngnew file mode 100644index 000000000..fef84dd59Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-print.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-search.png b/data/ext/viewerPDF/images/toolbarButton-search.pngnew file mode 100644index 000000000..604e652e5Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-search.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.png b/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.pngnew file mode 100644index 000000000..5a937c712Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-sidebarToggle.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-viewOutline.png b/data/ext/viewerPDF/images/toolbarButton-viewOutline.pngnew file mode 100644index 000000000..cb3967b7fBinary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-viewOutline.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.png b/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.pngnew file mode 100644index 000000000..3a27f0439Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-viewThumbnail.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-zoomIn.png b/data/ext/viewerPDF/images/toolbarButton-zoomIn.pngnew file mode 100644index 000000000..670acd93fBinary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-zoomIn.png differdiff --git a/data/ext/viewerPDF/images/toolbarButton-zoomOut.png b/data/ext/viewerPDF/images/toolbarButton-zoomOut.pngnew file mode 100644index 000000000..810fbf989Binary files /dev/null and b/data/ext/viewerPDF/images/toolbarButton-zoomOut.png differdiff --git a/data/ext/viewerPDF/index.html b/data/ext/viewerPDF/index.htmlnew file mode 100644index 000000000..50f2e5336--- /dev/null+++ b/data/ext/viewerPDF/index.html@@ -0,0 +1,215 @@++<!DOCTYPE html>+<!--+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.+-->+<html dir="ltr" mozdisallowselectionprint moznomarginboxes>+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">+ <title>PDF.js viewer</title>+++ <link rel="stylesheet" href="viewer.css"/>++ <script type="text/javascript">+ function getParameterByName(name) {+ name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");+ var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),+ results = regex.exec(location.search);+ return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));+ }+ var DEFAULT_URL = getParameterByName("cp");+ </script>++ <script type="text/javascript" src="compatibility.js"></script>+++<!-- This snippet is used in production, see Makefile -->+<link rel="resource" type="application/l10n" href="locale/locale.properties"/>+<script type="text/javascript" src="locale/l10n.js"></script>+<script type="text/javascript" src="pdf.js"></script>++++ <script type="text/javascript" src="debugger.js"></script>+ <script type="text/javascript" src="viewer.js"></script>++ </head>++ <body tabindex="1">+ <div id="outerContainer" class="loadingInProgress">++ <div id="sidebarContainer">+ <div id="toolbarSidebar">+ <div class="splitToolbarButton toggled">+ <button id="viewThumbnail" class="toolbarButton group toggled" title="Show Thumbnails" tabindex="2" data-l10n-id="thumbs">+ <span data-l10n-id="thumbs_label">Thumbnails</span>+ </button>+ <button id="viewOutline" class="toolbarButton group" title="Show Document Outline" tabindex="3" data-l10n-id="outline">+ <span data-l10n-id="outline_label">Document Outline</span>+ </button>+ </div>+ </div>+ <div id="sidebarContent">+ <div id="thumbnailView">+ </div>+ <div id="outlineView" class="hidden">+ </div>+ </div>+ </div> <!-- sidebarContainer -->++ <div id="mainContainer">+ <div class="findbar hidden doorHanger hiddenSmallView" id="findbar">+ <label for="findInput" class="toolbarLabel" data-l10n-id="find_label">Find:</label>+ <input id="findInput" class="toolbarField" tabindex="21">+ <div class="splitToolbarButton">+ <button class="toolbarButton findPrevious" title="" id="findPrevious" tabindex="22" data-l10n-id="find_previous">+ <span data-l10n-id="find_previous_label">Previous</span>+ </button>+ <div class="splitToolbarButtonSeparator"></div>+ <button class="toolbarButton findNext" title="" id="findNext" tabindex="23" data-l10n-id="find_next">+ <span data-l10n-id="find_next_label">Next</span>+ </button>+ </div>+ <input type="checkbox" id="findHighlightAll" class="toolbarField">+ <label for="findHighlightAll" class="toolbarLabel" tabindex="24" data-l10n-id="find_highlight">Highlight all</label>+ <input type="checkbox" id="findMatchCase" class="toolbarField">+ <label for="findMatchCase" class="toolbarLabel" tabindex="25" data-l10n-id="find_match_case_label">Match case</label>+ <span id="findMsg" class="toolbarLabel"></span>+ </div>+ <div class="toolbar">+ <div id="toolbarContainer">+ <div id="toolbarViewer">+ <div id="toolbarViewerLeft">+ <button id="sidebarToggle" class="toolbarButton" title="Toggle Sidebar" tabindex="4" data-l10n-id="toggle_sidebar">+ <span data-l10n-id="toggle_sidebar_label">Toggle Sidebar</span>+ </button>+ <div class="toolbarButtonSpacer"></div>+ <button id="viewFind" class="toolbarButton group hiddenSmallView" title="Find in Document" tabindex="5" data-l10n-id="findbar">+ <span data-l10n-id="findbar_label">Find</span>+ </button>+ <div class="splitToolbarButton">+ <button class="toolbarButton pageUp" title="Previous Page" id="previous" tabindex="6" data-l10n-id="previous">+ <span data-l10n-id="previous_label">Previous</span>+ </button>+ <div class="splitToolbarButtonSeparator"></div>+ <button class="toolbarButton pageDown" title="Next Page" id="next" tabindex="7" data-l10n-id="next">+ <span data-l10n-id="next_label">Next</span>+ </button>+ </div>+ <label id="pageNumberLabel" class="toolbarLabel" for="pageNumber" data-l10n-id="page_label">Page: </label>+ <input type="number" id="pageNumber" class="toolbarField pageNumber" value="1" size="4" min="1" tabindex="8">+ </input>+ <span id="numPages" class="toolbarLabel"></span>+ </div>+ <div id="toolbarViewerRight">+ <input id="fileInput" class="fileInput" type="file" oncontextmenu="return false;" style="visibility: hidden; position: fixed; right: 0; top: 0" />++ <button id="presentationMode" class="toolbarButton presentationMode hiddenSmallView" title="Switch to Presentation Mode" tabindex="12" data-l10n-id="presentation_mode">+ <span data-l10n-id="presentation_mode_label">Presentation Mode</span>+ </button>++ <button id="openFile" class="toolbarButton openFile hiddenSmallView" title="Open File" tabindex="13" data-l10n-id="open_file">+ <span data-l10n-id="open_file_label">Open</span>+ </button>++ <button id="print" class="toolbarButton print" title="Print" tabindex="14" data-l10n-id="print">+ <span data-l10n-id="print_label">Print</span>+ </button>++ <button id="download" class="toolbarButton download" title="Download" tabindex="15" data-l10n-id="download">+ <span data-l10n-id="download_label">Download</span>+ </button>+ <!-- <div class="toolbarButtonSpacer"></div> -->+ <a href="#" id="viewBookmark" class="toolbarButton bookmark hiddenSmallView" title="Current view (copy or open in new window)" tabindex="16" data-l10n-id="bookmark"><span data-l10n-id="bookmark_label">Current View</span></a>+ </div>+ <div class="outerCenter">+ <div class="innerCenter" id="toolbarViewerMiddle">+ <div class="splitToolbarButton">+ <button id="zoomOut" class="toolbarButton zoomOut" title="Zoom Out" tabindex="9" data-l10n-id="zoom_out">+ <span data-l10n-id="zoom_out_label">Zoom Out</span>+ </button>+ <div class="splitToolbarButtonSeparator"></div>+ <button id="zoomIn" class="toolbarButton zoomIn" title="Zoom In" tabindex="10" data-l10n-id="zoom_in">+ <span data-l10n-id="zoom_in_label">Zoom In</span>+ </button>+ </div>+ <span id="scaleSelectContainer" class="dropdownToolbarButton">+ <select id="scaleSelect" title="Zoom" oncontextmenu="return false;" tabindex="11" data-l10n-id="zoom">+ <option id="pageAutoOption" value="auto" selected="selected" data-l10n-id="page_scale_auto">Automatic Zoom</option>+ <option id="pageActualOption" value="page-actual" data-l10n-id="page_scale_actual">Actual Size</option>+ <option id="pageFitOption" value="page-fit" data-l10n-id="page_scale_fit">Fit Page</option>+ <option id="pageWidthOption" value="page-width" data-l10n-id="page_scale_width">Full Width</option>+ <option id="customScaleOption" value="custom"></option>+ <option value="0.5">50%</option>+ <option value="0.75">75%</option>+ <option value="1">100%</option>+ <option value="1.25">125%</option>+ <option value="1.5">150%</option>+ <option value="2">200%</option>+ </select>+ </span>+ </div>+ </div>+ </div>+ <div id="loadingBar">+ <div class="progress">+ <div class="glimmer">+ </div>+ </div>+ </div>+ </div>+ </div>++ <menu type="context" id="viewerContextMenu">+ <menuitem id="firstPage" label="First Page"+ data-l10n-id="first_page" ></menuitem>+ <menuitem id="lastPage" label="Last Page"+ data-l10n-id="last_page" ></menuitem>+ <menuitem id="pageRotateCcw" label="Rotate Counter-Clockwise"+ data-l10n-id="page_rotate_ccw" ></menuitem>+ <menuitem id="pageRotateCw" label="Rotate Clockwise"+ data-l10n-id="page_rotate_cw" ></menuitem>+ </menu>++ <div id="viewerContainer">+ <div id="viewer" contextmenu="viewerContextMenu"></div>+ </div>++ <div id="errorWrapper" hidden='true'>+ <div id="errorMessageLeft">+ <span id="errorMessage"></span>+ <button id="errorShowMore" onclick="" oncontextmenu="return false;" data-l10n-id="error_more_info">+ More Information+ </button>+ <button id="errorShowLess" onclick="" oncontextmenu="return false;" data-l10n-id="error_less_info" hidden='true'>+ Less Information+ </button>+ </div>+ <div id="errorMessageRight">+ <button id="errorClose" oncontextmenu="return false;" data-l10n-id="error_close">+ Close+ </button>+ </div>+ <div class="clearBoth"></div>+ <textarea id="errorMoreInfo" hidden='true' readonly="readonly"></textarea>+ </div>+ </div> <!-- mainContainer -->++ </div> <!-- outerContainer -->+ <div id="printContainer"></div>+ </body>+</html>\ No newline at end of filediff --git a/data/ext/viewerPDF/pdfjs/web/locale/locale.properties b/data/ext/viewerPDF/locale.propertiessimilarity index 82%rename from data/ext/viewerPDF/pdfjs/web/locale/locale.propertiesrename to data/ext/viewerPDF/locale.propertiesindex ead305ca5..79271226e 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/locale.properties+++ b/data/ext/viewerPDF/locale.properties@@ -1,18 +1,12 @@[ar]@import url(ar/viewer.properties)-[bn-BD]-@import url(bn-BD/viewer.properties)-[ca]@import url(ca/viewer.properties)[cs]@import url(cs/viewer.properties)-[cy]-@import url(cy/viewer.properties)-[da]@import url(da/viewer.properties)@@ -28,9 +22,6 @@[es]@import url(es/viewer.properties)-[fa]-@import url(fa/viewer.properties)-[fi]@import url(fi/viewer.properties)@@ -55,9 +46,6 @@[nl]@import url(nl/viewer.properties)-[no]-@import url(no/viewer.properties)-[pl]@import url(pl/viewer.properties)@@ -73,8 +61,8 @@[sr]@import url(sr/viewer.properties)-[sv-SE]-@import url(sv-SE/viewer.properties)+[sv]+@import url(sv/viewer.properties)[tr]@import url(tr/viewer.properties)diff --git a/data/ext/viewerPDF/locale/ar/metadata.inc b/data/ext/viewerPDF/locale/ar/metadata.incnew file mode 100644index 000000000..f1a7106a6--- /dev/null+++ b/data/ext/viewerPDF/locale/ar/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ar</em:locale>+ <em:name>عارض PDF</em:name>+ <em:description>يستخدم HTML5 لعرض ملفات PDF مباشره من خلال Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.properties b/data/ext/viewerPDF/locale/ar/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.propertiesrename to data/ext/viewerPDF/locale/ar/viewer.propertiesindex 0c6e943e5..6d22d27cb 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/ar/viewer.properties+++ b/data/ext/viewerPDF/locale/ar/viewer.properties@@ -30,25 +30,17 @@ zoom_out_label=تصغيرzoom_in.title=تكبيرzoom_in_label=تكبيرzoom.title=التكبير+print.title=طباعة+print_label=طباعةfullscreen.title=ملء الشاشةfullscreen_label=ملء الشاشةopen_file.title=فتح الملفopen_file_label=فتح-print.title=طباعة-print_label=طباعةdownload.title=تحميلdownload_label=تحميلbookmark.title=المشهد الحالي (نسخ أو فتح في نافذة جديدة)bookmark_label=المشهد الحالي-# Secondary toolbar and context menu-page_rotate_cw.title=تدوير مع عقارب الساعة-page_rotate_cw.label=تدوير مع عقارب الساعة-page_rotate_cw_label=تدوير مع عقارب الساعة-page_rotate_ccw.title=تدوير عكس عقارب الساعة-page_rotate_ccw.label=تدوير عكس عقارب الساعة-page_rotate_ccw_label=تدوير عكس عقارب الساعة-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -69,6 +61,10 @@ thumb_page_title=الصفحة {{page}}# number.thumb_page_canvas=صورة مصغرة من الصفحة {{page}}+# Context menu+page_rotate_cw.label=تدوير مع عقارب الساعة+page_rotate_ccw.label=تدوير عكس عقارب الساعة+# Find panel button title and messagesfind=بحثfind_terms_not_found=(لا يوجد)diff --git a/data/ext/viewerPDF/locale/ca/chrome.properties b/data/ext/viewerPDF/locale/ca/chrome.propertiesnew file mode 100644index 000000000..2fb6413f1--- /dev/null+++ b/data/ext/viewerPDF/locale/ca/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=No es pot visualitzar el docuement.+open_with_different_viewer=Obri-ho amb un altre visor.+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/ca/metadata.inc b/data/ext/viewerPDF/locale/ca/metadata.incnew file mode 100644index 000000000..86ade19c4--- /dev/null+++ b/data/ext/viewerPDF/locale/ca/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ca</em:locale>+ <em:name>Visor d'arxius PDF</em:name>+ <em:description>HTML5 per veure documents</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.properties b/data/ext/viewerPDF/locale/ca/viewer.propertiessimilarity index 92%rename from data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.propertiesrename to data/ext/viewerPDF/locale/ca/viewer.propertiesindex e2f026027..b8c81675a 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/ca/viewer.properties+++ b/data/ext/viewerPDF/locale/ca/viewer.properties@@ -30,31 +30,19 @@ zoom_out_label=Reduirzoom_in.title=Ampliarzoom_in_label=Ampliarzoom.title=Ampliació+print.title=Imprimir+print_label=Imprimir+fullscreen.title=Pantalla completa+fullscreen_label=Pantalla completapresentation_mode.title=Canviar a mode de Presentaciópresentation_mode_label=Mode de Presentacióopen_file.title=Obrir arxiuopen_file_label=Obrir-print.title=Imprimir-print_label=Imprimirdownload.title=Descarregardownload_label=Descarregarbookmark.title=Vista actual (copiï o obri en una finestra nova)bookmark_label=Vista actual-# Secondary toolbar and context menu-first_page.title=Primera pàgina-first_page.label=Primera pàgina-first_page_label=Primera pàgina-last_page.title=Darrera pàgina-last_page.label=Darrera pàgina-last_page_label=Darrera pàgina-page_rotate_cw.title=Rotar sentit horari-page_rotate_cw.label=Rotar sentit horari-page_rotate_cw_label=Rotar sentit horari-page_rotate_ccw.title=Rotar sentit anti-horari-page_rotate_ccw.label=Rotar sentit anti-horari-page_rotate_ccw_label=Rotar sentit anti-horari-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -78,6 +66,11 @@ thumb_page_canvas=Miniatura de la pàgina {{page}}# Find panel button title and messagesfind=Cercarfind_terms_not_found=(No trobat)+# Context menu+first_page.label=Primera pàgina+last_page.label=Darrera pàgina+page_rotate_cw.label=Rotar sentit horari+page_rotate_ccw.label=Rotar sentit anti-horari# Find panel button title and messagesfind_label=Cerca:diff --git a/data/ext/viewerPDF/locale/cs/metadata.inc b/data/ext/viewerPDF/locale/cs/metadata.incnew file mode 100644index 000000000..ed5c2a1c7--- /dev/null+++ b/data/ext/viewerPDF/locale/cs/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>cs</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Používá HTML5 pro zobrazení PDF souborů přímo ve Firefoxu.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/locale/cs/viewer.properties b/data/ext/viewerPDF/locale/cs/viewer.propertiesnew file mode 100644index 000000000..beac468ac--- /dev/null+++ b/data/ext/viewerPDF/locale/cs/viewer.properties@@ -0,0 +1,58 @@+# 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.++bookmark.title=Aktuální zobrazení (zkopírovat nebo otevřít v novém okně)+previous.title=Předchozí stránka+next.title=Další stránka+print.title=Tisk+download.title=Stáhnout+zoom_out.title=Zmenšit+zoom_in.title=Zvětšit+error_more_info=Více informací+error_less_info=Méně informací+error_close=Zavřít+error_build=PDF.JS Build: {{build}}+error_message=Zpráva:{{message}}+error_stack=Stack:{{stack}}+error_file=Soubor:{{file}}+error_line=Řádek:{{line}}+page_scale_width=Šířka stránky+page_scale_fit=Stránka+page_scale_auto=Automatické přibližení+page_scale_actual=Skutečná velikost+toggle_slider.title=Přepnout posuvník+thumbs.title=Zobrazit náhledy+outline.title=Zobrazit osnovu dokumentu+loading=Načítám... {{percent}}%+loading_error_indicator=Chyba+loading_error=Došlo k chybě při načítání PDF.+rendering_error=Došlo k chybě při vykreslování stránky.+page_label=Stránka:+page_of=z{{pageCount}}+open_file.title=Otevřít soubor+text_annotation_type.alt=[{{type}}Anotace]+toggle_slider_label=Přepnout posuvník+thumbs_label=Náhledy+outline_label=Přehled dokumentu+bookmark_label=Aktuální zobrazení+previous_label=Předchozí+next_label=Další+print_label=Tisk+download_label=Stáhnout+zoom_out_label=Zmenšit+zoom_in_label=Přiblížit+zoom.title=Zvětšit+thumb_page_title=Stránka{{page}}+thumb_page_canvas=Náhled stránky {{page}}+request_password=PDF je chráněn heslem:diff --git a/data/ext/viewerPDF/locale/da/chrome.properties b/data/ext/viewerPDF/locale/da/chrome.propertiesnew file mode 100644index 000000000..24c943bb1--- /dev/null+++ b/data/ext/viewerPDF/locale/da/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notifikationsbar beskeder og knapper+unsupported_feature=Denne PDF bliver måske ikke vist korrekt+open_with_different_viewer=Åbn med en anden PDF-fremviser+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/da/metadata.inc b/data/ext/viewerPDF/locale/da/metadata.incnew file mode 100644index 000000000..58b76b644--- /dev/null+++ b/data/ext/viewerPDF/locale/da/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>da</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Benytter HTML5 til at vise PDF-filer direkte i Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/da/viewer.properties b/data/ext/viewerPDF/locale/da/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/da/viewer.propertiesrename to data/ext/viewerPDF/locale/da/viewer.propertiesindex fe97b4b4f..e1d43ee43 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/da/viewer.properties+++ b/data/ext/viewerPDF/locale/da/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Zoom udzoom_in.title=Zoom indzoom_in_label=Zoom indzoom.title=Zoom+print_label=Udskriv+print.title=Udskrivfullscreen.title=Fuldskærmfullscreen_label=Fuldskærmopen_file.title=Åbn filopen_file_label=Åbn-print_label=Udskriv-print.title=Udskrivdownload.title=Hentdownload_label=Hentbookmark.title=Aktuel visning (kopier eller åbn i et nyt vindue)bookmark_label=Aktuel visning-# Secondary toolbar and context menu-first_page.title=Gå til første side-first_page.label=Gå til første side-first_page_label=Gå til første side-last_page.title=Gå til sidste side-last_page.label=Gå til sidste side-last_page_label=Gå til sidste side-page_rotate_cw.title=Rotér med uret-page_rotate_cw.label=Rotér med uret-page_rotate_cw_label=Rotér med uret-page_rotate_ccw.title=Roéer mod uret-page_rotate_ccw.label=Roéer mod uret-page_rotate_ccw_label=Roéer mod uret-# Tooltips of alternativ billedtekst til sidepanelet# (_label strengene er den alternative billedtekst, mens .title# strengene er tooltips@@ -75,6 +61,12 @@ thumb_page_title=Side {{page}}# egentlige sidetalthumb_page_canvas=Thumbnail af side {{page}}+# Popup menu+first_page.label=Gå til første side+last_page.label=Gå til sidste side+page_rotate_cw.label=Rotér med uret+page_rotate_ccw.label=Roéer mod uret+# Søgepanelet samt knapper og beskederfind_label=Find:find_previous.title=Find den forrige forekomstdiff --git a/data/ext/viewerPDF/locale/de/metadata.inc b/data/ext/viewerPDF/locale/de/metadata.incnew file mode 100644index 000000000..d934291ef--- /dev/null+++ b/data/ext/viewerPDF/locale/de/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>de</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Nutzt HTML5 um PDFs direkt in Firefox anzuzeigen.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/de/viewer.properties b/data/ext/viewerPDF/locale/de/viewer.propertiessimilarity index 64%rename from data/ext/viewerPDF/pdfjs/web/locale/de/viewer.propertiesrename to data/ext/viewerPDF/locale/de/viewer.propertiesindex cb7761b01..c38fb6a67 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/de/viewer.properties+++ b/data/ext/viewerPDF/locale/de/viewer.properties@@ -30,63 +30,22 @@ zoom_out_label=Verkleinernzoom_in.title=Vergrößernzoom_in_label=Vergrößernzoom.title=Zoom+print.title=Drucken+print_label=Druckenpresentation_mode.title=Zum Präsentationsmodus wechselnpresentation_mode_label=Bildschirmpräsentationopen_file.title=Datei öffnenopen_file_label=Öffnen-print.title=Drucken-print_label=Druckendownload.title=Herunterladendownload_label=Herunterladenbookmark.title=Aktuelle Ansicht (Kopieren oder in einem neuen Fenster öffnen)bookmark_label=Aktuelle Ansicht-# Secondary toolbar and context menu-tools.title=Werkzeuge-tools_label=Werkzeuge-first_page.title=Erste Seite-first_page.label=Erste Seite-first_page_label=Erste Seite-last_page.title=Letzte Seite-last_page.label=Letzte Seite-last_page_label=Letzte Seite-page_rotate_cw.title=Im Uhrzeigersinn drehen-page_rotate_cw.label=Im Uhrzeigersinn drehen-page_rotate_cw_label=Im Uhrzeigersinn drehen-page_rotate_ccw.title=Gegen den Uhrzeigersinn drehen-page_rotate_ccw.label=Gegen den Uhrzeigersinn drehen-page_rotate_ccw_label=Gegen den Uhrzeigersinn drehen--hand_tool_enable.title=Hand-Werkzeug aktivieren-hand_tool_enable_label=Hand-Werkzeug aktivieren-hand_tool_disable.title=Hand-Werkzeug deaktivieren-hand_tool_disable_label=Hand-Werkzeug deaktivieren--# Document properties dialog box-document_properties.title=Dokumenteigenschaften…-document_properties_label=Dokumenteigenschaften…-document_properties_file_name=Dateiname:-document_properties_file_size=Dateigröße:-document_properties_kb={{size_kb}} KB ({{size_b}} bytes)-document_properties_mb={{size_mb}} MB ({{size_b}} bytes)-document_properties_title=Titel:-document_properties_author=Verfasser:-document_properties_subject=Thema:-document_properties_keywords=Stichwörter:-document_properties_creation_date=Erstellt am:-document_properties_modification_date=Geändert am:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=Anwendung:-document_properties_producer=PDF erstellt mit:-document_properties_version=PDF-Version:-document_properties_page_count=Seitenanzahl:-document_properties_close=OK-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)-toggle_sidebar.title=Seitenleiste anzeigen-toggle_sidebar_label=Seitenleiste+toggle_slider.title=Seitenleiste anzeigen+toggle_slider_label=Seitenleisteoutline.title=Zeige Inhaltsverzeichnisoutline_label=Inhaltsverzeichnisthumbs.title=Zeige Vorschaubilder@@ -102,6 +61,12 @@ thumb_page_title=Seite {{page}}# number.thumb_page_canvas=Vorschau von Seite {{page}}+# Context menu+first_page.label=Erste Seite+last_page.label=Letzte Seite+page_rotate_cw.label=Im Uhrzeigersinn drehen+page_rotate_ccw.label=Entgegen dem Uhrzeigersinn drehen+# Find panel button title and messagesfind_label=Suchen:find_previous.title=Das vorherige Auftreten des Ausdrucks suchen@@ -118,9 +83,9 @@ find_not_found=Ausdruck nicht gefundenerror_more_info=Mehr Infoerror_less_info=Weniger Infoerror_close=Schließen-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=PDF.js v{{version}} (build: {{build}})+# LOCALIZATION NOTE (error_build): "{{build}}" will be replaced by the PDF.JS+# build ID.+error_build=PDF.JS Build: {{build}}# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an# english string describing the error.error_message=Nachricht: {{message}}@@ -131,7 +96,7 @@ error_stack=Stack: {{stack}}error_file=Datei: {{file}}# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line numbererror_line=Zeile: {{line}}-rendering_error=Die PDF-Datei konnte nicht angezeigt werden.+rendering_error=Das PDF konnte nicht angezeigt werden.# Predefined zoom valuespage_scale_width=Seitenbreite@@ -141,21 +106,15 @@ page_scale_actual=Originalgröße# Loading indicator messagesloading_error_indicator=Fehler-loading_error=Die PDF-Datei konnte nicht geladen werden.+loading_error=Das PDF konnte nicht geladen werden.invalid_file_error=Ungültige oder beschädigte PDF-Datei.-missing_file_error=Fehlende PDF-Datei.# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.# "{{type}}" will be replaced with an annotation type from a list defined in# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}} Annotation]-password_label=Geben Sie das Passwort ein, um diese Datei zu öffnen.-password_invalid=Ungültiges Passwort. Versuchen Sie es erneut.-password_ok=OK-password_cancel=Abbrechen+request_password=Das PDF ist passwortgeschützt:printing_not_supported=Warnung: Drucken wird durch diesen Browser nicht vollständig unterstützt.-printing_not_ready=Warnung: Die PDF-Datei ist zum Drucken noch nicht vollständig geladen.web_fonts_disabled=Webfonts sind deaktiviert: Eingebundene PDF-Schriftarten können nicht verwendet werden.-document_colors_disabled=PDF-Dateien können eigene Farben nicht verwenden: \'Seiten das Verwenden von eigenen Farben erlauben\' ist im Browser deaktiviert.diff --git a/data/ext/viewerPDF/locale/el/chrome.properties b/data/ext/viewerPDF/locale/el/chrome.propertiesnew file mode 100644index 000000000..ae4568b16--- /dev/null+++ b/data/ext/viewerPDF/locale/el/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Αυτό το έγγραφο PDF ίσως να μην εμφανιστεί σωστά.+open_with_different_viewer=Άνοιγμα με άλλο πρόγραμμα ανάγνωσης PDF+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/el/metadata.inc b/data/ext/viewerPDF/locale/el/metadata.incnew file mode 100644index 000000000..3beb0b980--- /dev/null+++ b/data/ext/viewerPDF/locale/el/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>el</em:locale>+ <em:name>Πρόγραμμα ανάγνωσης PDF</em:name>+ <em:description>Χρήση HTML5 για εμφάνιση αρχείων PDF κατευθείαν μέσα στο Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/el/viewer.properties b/data/ext/viewerPDF/locale/el/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/el/viewer.propertiesrename to data/ext/viewerPDF/locale/el/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/en-US/chrome.properties b/data/ext/viewerPDF/locale/en-US/chrome.propertiesnew file mode 100644index 000000000..0b469195c--- /dev/null+++ b/data/ext/viewerPDF/locale/en-US/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=This PDF document might not be displayed correctly.+open_with_different_viewer=Open With Different Viewer+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/en-US/metadata.inc b/data/ext/viewerPDF/locale/en-US/metadata.incnew file mode 100644index 000000000..8d9d94b04--- /dev/null+++ b/data/ext/viewerPDF/locale/en-US/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>en-US</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Uses HTML5 to display PDF files directly in Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.properties b/data/ext/viewerPDF/locale/en-US/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.propertiesrename to data/ext/viewerPDF/locale/en-US/viewer.propertiesindex a10bb8f22..ffc025362 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/en-US/viewer.properties+++ b/data/ext/viewerPDF/locale/en-US/viewer.properties@@ -30,58 +30,17 @@ zoom_out_label=Zoom Outzoom_in.title=Zoom Inzoom_in_label=Zoom Inzoom.title=Zoom+print.title=Print+print_label=Printpresentation_mode.title=Switch to Presentation Modepresentation_mode_label=Presentation Modeopen_file.title=Open Fileopen_file_label=Open-print.title=Print-print_label=Printdownload.title=Downloaddownload_label=Downloadbookmark.title=Current view (copy or open in new window)bookmark_label=Current View-# Secondary toolbar and context menu-tools.title=Tools-tools_label=Tools-first_page.title=Go to First Page-first_page.label=Go to First Page-first_page_label=Go to First Page-last_page.title=Go to Last Page-last_page.label=Go to Last Page-last_page_label=Go to Last Page-page_rotate_cw.title=Rotate Clockwise-page_rotate_cw.label=Rotate Clockwise-page_rotate_cw_label=Rotate Clockwise-page_rotate_ccw.title=Rotate Counterclockwise-page_rotate_ccw.label=Rotate Counterclockwise-page_rotate_ccw_label=Rotate Counterclockwise--hand_tool_enable.title=Enable hand tool-hand_tool_enable_label=Enable hand tool-hand_tool_disable.title=Disable hand tool-hand_tool_disable_label=Disable hand tool--# Document properties dialog box-document_properties.title=Document Properties…-document_properties_label=Document Properties…-document_properties_file_name=File name:-document_properties_file_size=File size:-document_properties_kb={{size_kb}} KB ({{size_b}} bytes)-document_properties_mb={{size_mb}} MB ({{size_b}} bytes)-document_properties_title=Title:-document_properties_author=Author:-document_properties_subject=Subject:-document_properties_keywords=Keywords:-document_properties_creation_date=Creation Date:-document_properties_modification_date=Modification Date:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=Creator:-document_properties_producer=PDF Producer:-document_properties_version=PDF Version:-document_properties_page_count=Page Count:-document_properties_close=Close-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -102,6 +61,12 @@ thumb_page_title=Page {{page}}# number.thumb_page_canvas=Thumbnail of Page {{page}}+# Context menu+first_page.label=Go to First Page+last_page.label=Go to Last Page+page_rotate_cw.label=Rotate Clockwise+page_rotate_ccw.label=Rotate Counterclockwise+# Find panel button title and messagesfind_label=Find:find_previous.title=Find the previous occurrence of the phrase@@ -150,10 +115,8 @@ missing_file_error=Missing PDF file.# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}} Annotation]-password_label=Enter the password to open this PDF file.-password_invalid=Invalid password. Please try again.-password_ok=OK-password_cancel=Cancel+request_password=PDF is protected by a password:+invalid_password=Invalid Password.printing_not_supported=Warning: Printing is not fully supported by this browser.printing_not_ready=Warning: The PDF is not fully loaded for printing.diff --git a/data/ext/viewerPDF/locale/es/chrome.properties b/data/ext/viewerPDF/locale/es/chrome.propertiesnew file mode 100644index 000000000..31c36187c--- /dev/null+++ b/data/ext/viewerPDF/locale/es/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Es posible que este documento PDF no se muestre correctamente.+open_with_different_viewer=Abrir con un visor diferente+open_with_different_viewer.accessKey=adiff --git a/data/ext/viewerPDF/locale/es/metadata.inc b/data/ext/viewerPDF/locale/es/metadata.incnew file mode 100644index 000000000..93cf82287--- /dev/null+++ b/data/ext/viewerPDF/locale/es/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>es</em:locale>+ <em:name>Visor de PDF</em:name>+ <em:description>Usa HTML5 para mostrar archivos PDF directamente en Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/es/viewer.properties b/data/ext/viewerPDF/locale/es/viewer.propertiessimilarity index 80%rename from data/ext/viewerPDF/pdfjs/web/locale/es/viewer.propertiesrename to data/ext/viewerPDF/locale/es/viewer.propertiesindex fc8848f8b..eda8354fb 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/es/viewer.properties+++ b/data/ext/viewerPDF/locale/es/viewer.properties@@ -30,38 +30,17 @@ zoom_out_label=Reducirzoom_in.title=Aumentarzoom_in_label=Aumentarzoom.title=Ampliación+print.title=Imprimir+print_label=Imprimirpresentation_mode.title=Cambiar al modo de presentaciónpresentation_mode_label=Modo de presentaciónopen_file.title=Abrir un archivoopen_file_label=Abrir-print.title=Imprimir-print_label=Imprimirdownload.title=Descargardownload_label=Descargar-bookmark.title=Vista actual (para copiar o abrir en otra ventana)+bookmark.title=Vista actual (copie o abra en una ventana nueva)bookmark_label=Vista actual-# Secondary toolbar and context menu-tools.title=Herramientas-tools_label=Herramientas-first_page.title=Ir a la primera página-first_page.label=Ir a la primera página-first_page_label=Ir a la primera página-last_page.title=Ir a la última página-last_page.label=Ir a la última página-last_page_label=Ir a la última página-page_rotate_cw.title=Girar a la derecha-page_rotate_cw.label=Girar a la derecha-page_rotate_cw_label=Girar a la derecha-page_rotate_ccw.title=Girar a la izquierda-page_rotate_ccw.label=Girar a la izquierda-page_rotate_ccw_label=Girar a la izquierda--hand_tool_enable.title=Activar la herramienta Mano-hand_tool_enable_label=Activar la herramienta Mano-hand_tool_disable.title=Desactivar la herramienta Mano-hand_tool_disable_label=Desactivar la herramienta Mano-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -82,6 +61,12 @@ thumb_page_title=Página {{page}}# number.thumb_page_canvas=Miniatura de la página {{page}}+# Context menu+first_page.label=Ir a la primera página+last_page.label=Ir a la última página+page_rotate_cw.label=Girar a la derecha+page_rotate_ccw.label=Girar a la izquierda+# Find panel button title and messagesfind_label=Buscar:find_previous.title=Ir a la frase encontrada anterior@@ -125,17 +110,14 @@ loading_error=Ocurrió un error al cargar el PDF.invalid_file_error=El archivo PDF no es válido o está dañado.missing_file_error=Falta el archivo PDF.-# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.+# LOCALIZATION NOTE (text_annotation_type): This is used as a tooltip.# "{{type}}" will be replaced with an annotation type from a list defined in# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[Anotación {{type}}]-password_label=Escriba la contraseña para abrir este archivo PDF.-password_invalid=La contraseña no es válida. Inténtelo de nuevo.-password_ok=Aceptar-password_cancel=Cancelar+request_password=El archivo PDF está protegido por una contraseña:printing_not_supported=Aviso: Este navegador no es compatible completamente con la impresión.printing_not_ready=Aviso: El PDF no se ha cargado completamente para su impresión.web_fonts_disabled=Se han desactivado los tipos de letra web: no se pueden usar los tipos de letra incrustados en el PDF.-document_colors_disabled=No se permite que los documentos PDF usen sus propios colores: la opción «Permitir que las páginas elijan sus propios colores» está desactivada en el navegador.+web_colors_disabled=Se han desactivado los colores web.diff --git a/data/ext/viewerPDF/locale/fi/chrome.properties b/data/ext/viewerPDF/locale/fi/chrome.propertiesnew file mode 100644index 000000000..529da81dd--- /dev/null+++ b/data/ext/viewerPDF/locale/fi/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Tämä PDF-asiakirja ei ehkä näy oikeanlaisena.+open_with_different_viewer=Avaa toisella ohjelmalla+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/fi/metadata.inc b/data/ext/viewerPDF/locale/fi/metadata.incnew file mode 100644index 000000000..1b8d8b613--- /dev/null+++ b/data/ext/viewerPDF/locale/fi/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>fi</em:locale>+ <em:name>PDF Lukuohjelma</em:name>+ <em:description>Näyttää PDF tiedostot suoraan Firefox:ssa HTML5:n avulla.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.properties b/data/ext/viewerPDF/locale/fi/viewer.propertiessimilarity index 92%rename from data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.propertiesrename to data/ext/viewerPDF/locale/fi/viewer.propertiesindex 560c948eb..d032bcc10 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/fi/viewer.properties+++ b/data/ext/viewerPDF/locale/fi/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Suurennazoom_in.title=Pienennäzoom_in_label=Pienennäzoom.title=Sivun suurennus+print.title=Tulosta+print_label=Tulostapresentation_mode.title=Esitystilapresentation_mode_label=Esitystilaopen_file.title=Avaa tiedostoopen_file_label=Avaa-print.title=Tulosta-print_label=Tulostadownload.title=Lataadownload_label=Lataabookmark.title=Nykyinen näkymä (kopioi tai avaa uuteen ikkunaan)bookmark_label=Nykyinen näkymä-# Secondary toolbar and context menu-first_page.title=Ensimmäinen sivu-first_page.label=Ensimmäinen sivu-first_page_label=Ensimmäinen sivu-last_page.title=Viimeinen sivu-last_page.label=Viimeinen sivu-last_page_label=Viimeinen sivu-page_rotate_cw.title=Kierrä myötäpäivään-page_rotate_cw.label=Kierrä myötäpäivään-page_rotate_cw_label=Kierrä myötäpäivään-page_rotate_ccw.title=Kierrä vastapäivään-page_rotate_ccw.label=Kierrä vastapäivään-page_rotate_ccw_label=Kierrä vastapäivään-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title=Sivu {{page}}# number.thumb_page_canvas=Sivun {{page}} esikatselukuva+# Context menu+first_page.label=Ensimmäinen sivu+last_page.label=Viimeinen sivu+page_rotate_cw.label=Kierrä myötäpäivään+page_rotate_ccw.label=Kierrä vastapäivään+# Find panel button title and messagesfind_label=Etsifind_previous.title=Etsi edellinendiff --git a/data/ext/viewerPDF/locale/fr/chrome.properties b/data/ext/viewerPDF/locale/fr/chrome.propertiesnew file mode 100644index 000000000..2e354ffbf--- /dev/null+++ b/data/ext/viewerPDF/locale/fr/chrome.properties@@ -0,0 +1,17 @@+# 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.++unsupported_feature=Il est possible que ce document PDF ne s'affiche pas correctement.+open_with_different_viewer=Ouvrir avec un autre lecteur PDF+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/fr/metadata.inc b/data/ext/viewerPDF/locale/fr/metadata.incnew file mode 100644index 000000000..874e93a18--- /dev/null+++ b/data/ext/viewerPDF/locale/fr/metadata.inc@@ -0,0 +1,7 @@+ <em:localized>+ <Description>+ <em:locale>fr</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Utilise HTML5 pour afficher les documents PDF directement dans Firefox.</em:description>+ </Description>+ </em:localized>diff --git a/data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.properties b/data/ext/viewerPDF/locale/fr/viewer.propertiessimilarity index 70%rename from data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.propertiesrename to data/ext/viewerPDF/locale/fr/viewer.propertiesindex 8c4da8204..2a0094b2b 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/fr/viewer.properties+++ b/data/ext/viewerPDF/locale/fr/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Zoom arrièrezoom_in.title=Zoom avantzoom_in_label=Zoom avantzoom.title=Zoom+print.title=Imprimer+print_label=Imprimerpresentation_mode.title=Basculer en mode présentationpresentation_mode_label=Mode présentationopen_file.title=Ouvrir le fichier-open_file_label=Ouvrir le fichier-print.title=Imprimer-print_label=Imprimer+open_file_label=Ouvrirdownload.title=Téléchargerdownload_label=Téléchargerbookmark.title=Affichage courant (copier ou ouvrir dans une nouvelle fenêtre)bookmark_label=Affichage actuel-# Secondary toolbar and context menu-first_page.title=Aller à la première page-first_page.label=Aller à la première page-first_page_label=Aller à la première page-last_page.title=Aller à la dernière page-last_page.label=Aller à la dernière page-last_page_label=Aller à la dernière page-page_rotate_cw.title=Rotation horaire-page_rotate_cw.label=Rotation horaire-page_rotate_cw_label=Rotation horaire-page_rotate_ccw.title=Rotation anti-horaire-page_rotate_ccw.label=Rotation anti-horaire-page_rotate_ccw_label=Rotation anti-horaire-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,30 +61,11 @@ thumb_page_title=Page {{page}}# number.thumb_page_canvas=Vignette de la page {{page}}-hand_tool_enable.title=Activer l'outil main-hand_tool_enable_label=Activer l'outil main-hand_tool_disable.title=Désactiver l'outil main-hand_tool_disable_label=Désactiver l'outil main--# Document properties dialog box-document_properties.title=Propriétés du document…-document_properties_label=Propriétés du document…-document_properties_file_name=Nom du fichier :-document_properties_file_size=Taille du fichier :-document_properties_kb={{size_kb}} Ko ({{size_b}} octets)-document_properties_mb={{size_mb}} Mo ({{size_b}} octets)-document_properties_title=Titre :-document_properties_author=Auteur :-document_properties_subject=Sujet :-document_properties_keywords=Mots-clés :-document_properties_creation_date=Date de création :-document_properties_modification_date=Modifié le :-document_properties_date_string={{date}} à {{time}}-document_properties_creator=Créé par :-document_properties_producer=Outil de conversion PDF :-document_properties_version=Version PDF :-document_properties_page_count=Nombre de pages :-document_properties_close=Fermer+# Context menu+first_page.label=Aller à la première page+last_page.label=Aller à la dernière page+page_rotate_cw.label=Rotation horaire+page_rotate_ccw.label=Rotation anti-horaire# Find panel button title and messagesfind_label=Rechercher :@@ -143,17 +110,13 @@ loading_error=Une erreur s'est produite lors du chargement du fichier PDF.invalid_file_error=Fichier PDF invalide ou corrompu.missing_file_error=Fichier PDF manquant.-# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.+# LOCALIZATION NOTE (text_annotation_type): This is used as a tooltip.# "{{type}}" will be replaced with an annotation type from a list defined in# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[Annotation {{type}}]-password_label=Veuillez saisir le mot de passe pour ouvrir ce fichier PDF.-password_invalid=Mot de passe incorrect. Veuillez réessayer.-password_ok=OK-password_cancel=Annuler+request_password=Le PDF est protégé par un mot de passe :printing_not_supported=Attention : l'impression n'est pas totalement prise en charge par ce navigateur.printing_not_ready=Attention : le PDF n'est pas entièrement chargé pour pouvoir l'imprimer.web_fonts_disabled=Les polices web sont désactivées : impossible d'utiliser les polices intégrées au PDF.-document_colors_disabled=Les documents PDF ne peuvent pas utiliser leurs propres couleurs : « Autoriser les pages web à utiliser leurs propres couleurs » est désactivé dans le navigateur.diff --git a/data/ext/viewerPDF/locale/he/metadata.inc b/data/ext/viewerPDF/locale/he/metadata.incnew file mode 100644index 000000000..3493c0b7c--- /dev/null+++ b/data/ext/viewerPDF/locale/he/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>he</em:locale>+ <em:name>קורא PDF</em:name>+ <em:description>הצגת קבצי PDF ישירות ב־Firefox באמצעות HTML5.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/he/viewer.properties b/data/ext/viewerPDF/locale/he/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/he/viewer.propertiesrename to data/ext/viewerPDF/locale/he/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/it/metadata.inc b/data/ext/viewerPDF/locale/it/metadata.incnew file mode 100644index 000000000..e09d807b1--- /dev/null+++ b/data/ext/viewerPDF/locale/it/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>it</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Usa HTML5 per visualizzare i file PDF direttamente in Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/it/viewer.properties b/data/ext/viewerPDF/locale/it/viewer.propertiessimilarity index 86%rename from data/ext/viewerPDF/pdfjs/web/locale/it/viewer.propertiesrename to data/ext/viewerPDF/locale/it/viewer.propertiesindex a9311d7e9..79331b452 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/it/viewer.properties+++ b/data/ext/viewerPDF/locale/it/viewer.properties@@ -19,7 +19,7 @@ print.title=Stampadownload.title=Downloadzoom_out.title=Riduci Zoomzoom_in.title=Aumenta Zoom-error_more_info=Più Informazioni+error_more_info=Pi� Informazionierror_less_info=Meno Informazionierror_close=Chiudierror_build=PDF.JS Build: {{build}}@@ -36,9 +36,9 @@ thumbs.title=Mostra Miniatureoutline.title=Mostra Indice Documentoloading=Caricamento... {{percent}}%loading_error_indicator=Errore-loading_error=È accaduto un errore durante il caricamento del PDF.-rendering_error=È accaduto un errore durante il rendering della pagina.+loading_error=� accaduto un errore durante il caricamento del PDF.+rendering_error=� accaduto un errore durante il rendering della pagina.page_label=Pagina:page_of=di {{pageCount}}open_file.title=Apri File-text_annotation_type.alt=[{{type}} Annotazione]\ No newline at end of file+text_annotation_type.alt=[{{type}} Annotazione]diff --git a/data/ext/viewerPDF/locale/ja/chrome.properties b/data/ext/viewerPDF/locale/ja/chrome.propertiesnew file mode 100644index 000000000..b7237c63c--- /dev/null+++ b/data/ext/viewerPDF/locale/ja/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=この PDF 文書はサポートされていないため正しく表示できない可能性があります。+open_with_different_viewer=ほかのビューアで開く+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/ja/metadata.inc b/data/ext/viewerPDF/locale/ja/metadata.incnew file mode 100644index 000000000..7ca474685--- /dev/null+++ b/data/ext/viewerPDF/locale/ja/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ja</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>HTML5を使用して、Firefoxで直接PDFファイルを表示します。</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.properties b/data/ext/viewerPDF/locale/ja/viewer.propertiessimilarity index 74%rename from data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.propertiesrename to data/ext/viewerPDF/locale/ja/viewer.propertiesindex 39c705626..db0a99700 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/ja/viewer.properties+++ b/data/ext/viewerPDF/locale/ja/viewer.properties@@ -23,65 +23,24 @@ next_label=次へ# Do not translate "{{pageCount}}", it will be substituted with a number# representing the total number of pages.page_label=ページ:-page_of=/ {{pageCount}}+page_of=of {{pageCount}}zoom_out.title=縮小zoom_out_label=縮小zoom_in.title=拡大zoom_in_label=拡大zoom.title=ズーム+print.title=印刷+print_label=印刷presentation_mode.title=プレゼンテーションモードに切り替えますpresentation_mode_label=プレゼンテーションモードopen_file.title=ファイルを開くopen_file_label=開く-print.title=印刷-print_label=印刷download.title=ダウンロードdownload_label=ダウンロードbookmark.title=現在のビューをブックマークbookmark_label=現在のビューをブックマーク-# Secondary toolbar and context menu-tools.title=ツール-tools_label=ツール-first_page.title=最初のページへ移動-first_page.label=最初のページへ移動-first_page_label=最初のページへ移動-last_page.title=最後のページへ移動-last_page.label=最後のページへ移動-last_page_label=最後のページへ移動-page_rotate_cw.title=右回転-page_rotate_cw.label=右回転-page_rotate_cw_label=右回転-page_rotate_ccw.title=左回転-page_rotate_ccw.label=左回転-page_rotate_ccw_label=左回転--hand_tool_enable.title=手のひらツールを有効にする-hand_tool_enable_label=手のひらツールを有効にする-hand_tool_disable.title=手のひらツールを無効にする-hand_tool_disable_label=手のひらツールを無効にする--# Document properties dialog box-document_properties.title=文書のプロパティ…-document_properties_label=文書のプロパティ…-document_properties_file_name=ファイル名:-document_properties_file_size=ファイルサイズ:-document_properties_kb={{size_kb}} KB ({{size_b}} bytes)-document_properties_mb={{size_mb}} MB ({{size_b}} bytes)-document_properties_title=タイトル:-document_properties_author=作成者:-document_properties_subject=件名:-document_properties_keywords=キーワード:-document_properties_creation_date=作成日:-document_properties_modification_date=更新日:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=アプリケーション:-document_properties_producer=PDF 変換:-document_properties_version=PDFのバージョン:-document_properties_page_count=ページ数:-document_properties_close=閉じる-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -102,6 +61,12 @@ thumb_page_title={{page}} ページ# number.thumb_page_canvas=ページの縮小版 {{page}}+# Context menu+first_page.label=最初のページへ移動+last_page.label=最後のページへ移動+page_rotate_cw.label=右回転+page_rotate_ccw.label=左回転+# Find panel button title and messagesfind_label=検索:find_previous.title=指定文字列に一致する 1 つ前の部分を検索します@@ -150,10 +115,8 @@ missing_file_error=PDF ファイルが見つかりません。# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}} 注釈]-password_label=この PDF ファイルを開くためのパスワードを入力してください。-password_invalid=無効なパスワードです。もう一度やり直してください。-password_ok=OK-password_cancel=キャンセル+request_password=PDF はパスワードによって保護されています+invalid_password=無効なパスワードですprinting_not_supported=警告:このブラウザでは印刷が完全にサポートされていませんprinting_not_ready=警告:PDF を印刷するための読み込みが終了していませんdiff --git a/data/ext/viewerPDF/locale/ko/chrome.properties b/data/ext/viewerPDF/locale/ko/chrome.propertiesnew file mode 100644index 000000000..fcd2f8f4f--- /dev/null+++ b/data/ext/viewerPDF/locale/ko/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=이 PDF 문서는 제대로 표시되지 않을 수 있습니다.+open_with_different_viewer=다른 뷰어로 열기+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/ko/metadata.inc b/data/ext/viewerPDF/locale/ko/metadata.incnew file mode 100644index 000000000..04a8f0786--- /dev/null+++ b/data/ext/viewerPDF/locale/ko/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ko</em:locale>+ <em:name>PDF 뷰어</em:name>+ <em:description>Firefox가 PDF 파일을 HTML5를 이용하여 직접 보여줍니다.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.properties b/data/ext/viewerPDF/locale/ko/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.propertiesrename to data/ext/viewerPDF/locale/ko/viewer.propertiesindex 4454f822d..240a15138 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/ko/viewer.properties+++ b/data/ext/viewerPDF/locale/ko/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=축소zoom_in.title=확대zoom_in_label=확대zoom.title=확대 비율+print.title=출력+print_label=출력presentation_mode.title=프레젠테이션 모드로 전환presentation_mode_label=프레젠테이션 모드open_file.title=파일 열기open_file_label=열기-print.title=출력-print_label=출력download.title=내려받기download_label=내려받기bookmark.title=현 화면 (복사하거나 새 창에서 열기)bookmark_label=현 화면-# Secondary toolbar and context menu-first_page.title=첫 쪽으로-first_page.label=첫 쪽으로-first_page_label=첫 쪽으로-last_page.title=끝 쪽으로-last_page.label=끝 쪽으로-last_page_label=끝 쪽으로-page_rotate_cw.title=시계방향 회전-page_rotate_cw.label=시계방향 회전-page_rotate_cw_label=시계방향 회전-page_rotate_ccw.title=반시계방향 회전-page_rotate_ccw.label=반시계방향 회전-page_rotate_ccw_label=반시계방향 회전-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title={{page}} 쪽# number.thumb_page_canvas={{page}}쪽의 썸네일+# Context menu+first_page.label=첫 쪽으로+last_page.label=끝 쪽으로+page_rotate_cw.label=시계방향 회전+page_rotate_ccw.label=반시계방향 회전+# Find panel button title and messagesfind_label=찾기:find_previous.title=이전 구절 찾기diff --git a/data/ext/viewerPDF/pdfjs/web/l10n.js b/data/ext/viewerPDF/locale/l10n.jssimilarity index 75%rename from data/ext/viewerPDF/pdfjs/web/l10n.jsrename to data/ext/viewerPDF/locale/l10n.jsindex 37f3950c5..543563165 100644--- a/data/ext/viewerPDF/pdfjs/web/l10n.js+++ b/data/ext/viewerPDF/locale/l10n.js@@ -1,32 +1,31 @@-/**- * Copyright (c) 2011-2013 Fabien Cazenave, Mozilla.- *- * Permission is hereby granted, free of charge, to any person obtaining a copy- * of this software and associated documentation files (the "Software"), to- * deal in the Software without restriction, including without limitation the- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or- * sell copies of the Software, and to permit persons to whom the Software is- * furnished to do so, subject to the following conditions:- *- * The above copyright notice and this permission notice shall be included in- * all copies or substantial portions of the Software.- *- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS- * IN THE SOFTWARE.- */+/** Copyright (c) 2011-2012 Fabien Cazenave, Mozilla.+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to+ * deal in the Software without restriction, including without limitation the+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or+ * sell copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS+ * IN THE SOFTWARE.+ *//*Additional modifications for PDF.js project:- Disables language initialization on page loading;- - Removes consoleWarn and consoleLog and use console.log/warn directly.+ - Adds fallback argument to the getL10nData;+ - Removes consoleLog and simplifies consoleWarn;- Removes window._ assignment.*/--/*jshint browser: true, devel: true, globalstrict: true */+/*jshint browser: true, devel: true, es5: true, globalstrict: true */'use strict';document.webL10n = (function(window, document, undefined) {@@ -37,21 +36,13 @@ document.webL10n = (function(window, document, undefined) {var gMacros = {};var gReadyState = 'loading';+ // read-only setting -- we recommend to load l10n resources synchronously+ var gAsyncResourceLoading = true;- /**- * Synchronously loading l10n resources significantly minimizes flickering- * from displaying the app with non-localized strings and then updating the- * strings. Although this will block all script execution on this page, we- * expect that the l10n resources are available locally on flash-storage.- *- * As synchronous XHR is generally considered as a bad idea, we're still- * loading l10n resources asynchronously -- but we keep this in a setting,- * just in case... and applications using this library should hide their- * content until the `localized' event happens.- */-- var gAsyncResourceLoading = true; // read-only-+ // debug helpers+ function consoleWarn(message) {+ console.log('[l10n] ' + message);+ };/*** DOM helpers for the so-called "HTML API".@@ -64,12 +55,6 @@ document.webL10n = (function(window, document, undefined) {return document.querySelectorAll('link[type="application/l10n"]');}- function getL10nDictionary() {- var script = document.querySelector('script[type="application/l10n"]');- // TODO: support multiple and external JSON dictionaries- return script ? JSON.parse(script.innerHTML) : null;- }-function getTranslatableChildren(element) {return element ? element.querySelectorAll('*[data-l10n-id]') : [];}@@ -85,7 +70,7 @@ document.webL10n = (function(window, document, undefined) {try {args = JSON.parse(l10nArgs);} catch (e) {- console.warn('could not parse arguments for #' + l10nId);+ consoleWarn('could not parse arguments for #' + l10nId);}}return { id: l10nId, args: args };@@ -93,41 +78,9 @@ document.webL10n = (function(window, document, undefined) {function fireL10nReadyEvent(lang) {var evtObject = document.createEvent('Event');- evtObject.initEvent('localized', true, false);+ evtObject.initEvent('localized', false, false);evtObject.language = lang;- document.dispatchEvent(evtObject);- }-- function xhrLoadText(url, onSuccess, onFailure, asynchronous) {- onSuccess = onSuccess || function _onSuccess(data) {};- onFailure = onFailure || function _onFailure() {- console.warn(url + ' not found.');- };-- var xhr = new XMLHttpRequest();- xhr.open('GET', url, asynchronous);- if (xhr.overrideMimeType) {- xhr.overrideMimeType('text/plain; charset=utf-8');- }- xhr.onreadystatechange = function() {- if (xhr.readyState == 4) {- if (xhr.status == 200 || xhr.status === 0) {- onSuccess(xhr.responseText);- } else {- onFailure();- }- }- };- xhr.onerror = onFailure;- xhr.ontimeout = onFailure;-- // in Firefox OS with the app:// protocol, trying to XHR a non-existing- // URL will raise an exception here -- hence this ugly try...catch.- try {- xhr.send(null);- } catch (e) {- onFailure();- }+ window.dispatchEvent(evtObject);}@@ -155,7 +108,7 @@ document.webL10n = (function(window, document, undefined) {*/function parseResource(href, lang, successCallback, failureCallback) {- var baseURL = href.replace(/[^\/]*$/, '') || './';+ var baseURL = href.replace(/\/[^\/]*$/, '/');// handle escaped characters (backslashes) in a stringfunction evalString(text) {@@ -218,17 +171,16 @@ document.webL10n = (function(window, document, undefined) {// key-value pairvar tmp = line.match(reSplit);- if (tmp && tmp.length == 3) {+ if (tmp && tmp.length == 3)dictionary[tmp[1]] = evalString(tmp[2]);- }}}// import another *.properties filefunction loadImport(url) {- xhrLoadText(url, function(content) {+ loadResource(url, function(content) {parseRawLines(content, false); // don't allow recursive imports- }, null, false); // load synchronously+ }, false, false); // load synchronously}// fill the dictionary@@ -236,8 +188,29 @@ document.webL10n = (function(window, document, undefined) {return dictionary;}+ // load the specified resource file+ function loadResource(url, onSuccess, onFailure, asynchronous) {+ var xhr = new XMLHttpRequest();+ xhr.open('GET', url, asynchronous);+ if (xhr.overrideMimeType) {+ xhr.overrideMimeType('text/plain; charset=utf-8');+ }+ xhr.onreadystatechange = function() {+ if (xhr.readyState == 4) {+ if (xhr.status == 200 || xhr.status === 0) {+ if (onSuccess)+ onSuccess(xhr.responseText);+ } else {+ if (onFailure)+ onFailure();+ }+ }+ };+ xhr.send(null);+ }+// load and parse l10n data (warning: global variables are used here)- xhrLoadText(href, function(response) {+ loadResource(href, function(response) {gTextData += response; // mostly for debug// parse *.properties text data into an l10n dictionary@@ -260,16 +233,13 @@ document.webL10n = (function(window, document, undefined) {}// trigger callback- if (successCallback) {+ if (successCallback)successCallback();- }}, failureCallback, gAsyncResourceLoading);- }+ };// load and parse all resources for the specified localefunction loadLocale(lang, callback) {- callback = callback || function _callback() {};-clear();gLanguage = lang;@@ -277,17 +247,8 @@ document.webL10n = (function(window, document, undefined) {// and load the resource filesvar langLinks = getL10nResourceLinks();var langCount = langLinks.length;- if (langCount === 0) {- // we might have a pre-compiled dictionary instead- var dict = getL10nDictionary();- if (dict && dict.locales && dict.default_locale) {- console.log('using the embedded JSON directory, early way out');- gL10nData = dict.locales[lang] || dict.locales[dict.default_locale];- callback();- } else {- console.log('no resource to load, early way out');- }- // early way out+ if (langCount == 0) {+ consoleWarn('no resource to load, early way out');fireL10nReadyEvent(lang);gReadyState = 'complete';return;@@ -299,20 +260,21 @@ document.webL10n = (function(window, document, undefined) {onResourceLoaded = function() {gResourceCount++;if (gResourceCount >= langCount) {- callback();+ if (callback) // execute the [optional] callback+ callback();fireL10nReadyEvent(lang);gReadyState = 'complete';}};// load all resource files- function L10nResourceLink(link) {+ function l10nResourceLink(link) {var href = link.href;var type = link.type;this.load = function(lang, callback) {var applied = lang;parseResource(href, lang, callback, function() {- console.warn(href + ' not found.');+ consoleWarn(href + ' not found.');applied = '';});return applied; // return lang if found, an empty string if not found@@ -320,10 +282,10 @@ document.webL10n = (function(window, document, undefined) {}for (var i = 0; i < langCount; i++) {- var resource = new L10nResourceLink(langLinks[i]);+ var resource = new l10nResourceLink(langLinks[i]);var rv = resource.load(lang, onResourceLoaded);if (rv != lang) { // lang not found, used default resource instead- console.warn('"' + lang + '" resource not found');+ consoleWarn('"' + lang + '" resource not found');gLanguage = '';}}@@ -744,7 +706,7 @@ document.webL10n = (function(window, document, undefined) {// return a function that gives the plural form name for a given integervar index = locales2rules[lang.replace(/-.*$/, '')];if (!(index in pluralRules)) {- console.warn('plural form unknown for [' + lang + ']');+ consoleWarn('plural form unknown for [' + lang + ']');return function() { return 'other'; };}return pluralRules[index];@@ -761,9 +723,8 @@ document.webL10n = (function(window, document, undefined) {return str;// initialize _pluralRules- if (!gMacros._pluralRules) {+ if (!gMacros._pluralRules)gMacros._pluralRules = getPluralRules(gLanguage);- }var index = '[' + gMacros._pluralRules(n) + ']';// try to find a [zero|one|two] key if it's defined@@ -775,8 +736,6 @@ document.webL10n = (function(window, document, undefined) {str = gL10nData[key + '[two]'][prop];} else if ((key + index) in gL10nData) {str = gL10nData[key + index][prop];- } else if ((key + '[other]') in gL10nData) {- str = gL10nData[key + '[other]'][prop];}return str;@@ -791,7 +750,7 @@ document.webL10n = (function(window, document, undefined) {function getL10nData(key, args, fallback) {var data = gL10nData[key];if (!data) {- console.warn('#' + key + ' is undefined.');+ consoleWarn('#' + key + ' missing for [' + gLanguage + ']');if (!fallback) {return null;}@@ -807,7 +766,7 @@ document.webL10n = (function(window, document, undefined) {for (var prop in data) {var str = data[prop];str = substIndexes(str, args, key, prop);- str = substArguments(str, args, key);+ str = substArguments(str, args);rv[prop] = str;}return rv;@@ -840,8 +799,8 @@ document.webL10n = (function(window, document, undefined) {}// replace {{arguments}} with their values- function substArguments(str, args, key) {- var reArgs = /\{\{\s*(.+?)\s*\}\}/;+ function substArguments(str, args) {+ var reArgs = /\{\{\s*([a-zA-Z\.]+)\s*\}\}/;var match = reArgs.exec(str);while (match) {if (!match || match.length < 2)@@ -849,12 +808,12 @@ document.webL10n = (function(window, document, undefined) {var arg = match[1];var sub = '';- if (args && arg in args) {+ if (arg in args) {sub = args[arg];} else if (arg in gL10nData) {sub = gL10nData[arg][gTextProp];} else {- console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');+ consoleWarn('could not find argument {{' + arg + '}}');return str;}@@ -874,21 +833,23 @@ document.webL10n = (function(window, document, undefined) {// get the related l10n objectvar data = getL10nData(l10n.id, l10n.args);if (!data) {- console.warn('#' + l10n.id + ' is undefined.');+ consoleWarn('#' + l10n.id + ' missing for [' + gLanguage + ']');return;}// translate element (TODO: security checks?)+ // for the node content, replace the content of the first child textNode+ // and clear other child textNodesif (data[gTextProp]) { // XXX- if (getChildElementCount(element) === 0) {+ if (element.children.length === 0) {element[gTextProp] = data[gTextProp];} else {- // this element has element children: replace the content of the first- // (non-empty) child textNode and clear other child textNodes- var children = element.childNodes;- var found = false;+ var children = element.childNodes,+ found = false;for (var i = 0, l = children.length; i < l; i++) {- if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {+ if (children[i].nodeType === 3 &&+ /\S/.test(children[i].textContent)) { // XXX+ // using nodeValue seems cross-browserif (found) {children[i].nodeValue = '';} else {@@ -897,11 +858,8 @@ document.webL10n = (function(window, document, undefined) {}}}- // if no (non-empty) textNode is found, insert a textNode before the- // first element child.if (!found) {- var textNode = document.createTextNode(data[gTextProp]);- element.insertBefore(textNode, element.firstChild);+ consoleWarn('unexpected error, could not translate element content');}}delete data[gTextProp];@@ -912,21 +870,6 @@ document.webL10n = (function(window, document, undefined) {}}- // webkit browsers don't currently support 'children' on SVG elements...- function getChildElementCount(element) {- if (element.children) {- return element.children.length;- }- if (typeof element.childElementCount !== 'undefined') {- return element.childElementCount;- }- var count = 0;- for (var i = 0; i < element.childNodes.length; i++) {- count += element.nodeType === 1 ? 1 : 0;- }- return count;- }-// translate an HTML subtreefunction translateFragment(element) {element = element || document.documentElement;@@ -945,21 +888,10 @@ document.webL10n = (function(window, document, undefined) {// cross-browser API (sorry, oldIE doesn't support getters & setters)return {// get a localized string- get: function(key, args, fallbackString) {- var index = key.lastIndexOf('.');- var prop = gTextProp;- if (index > 0) { // An attribute has been specified- prop = key.substr(index + 1);- key = key.substring(0, index);- }- var fallback;- if (fallbackString) {- fallback = {};- fallback[prop] = fallbackString;- }- var data = getL10nData(key, args, fallback);- if (data && prop in data) {- return data[prop];+ get: function(key, args, fallback) {+ var data = getL10nData(key, args, {textContent: fallback});+ if (data) { // XXX double-check this+ return 'textContent' in data ? data.textContent : '';}return '{{' + key + '}}';},@@ -984,21 +916,7 @@ document.webL10n = (function(window, document, undefined) {translate: translateFragment,// this can be used to prevent race conditions- getReadyState: function() { return gReadyState; },- ready: function(callback) {- if (!callback) {- return;- } else if (gReadyState == 'complete' || gReadyState == 'interactive') {- window.setTimeout(callback);- } else if (document.addEventListener) {- document.addEventListener('localized', callback);- } else if (document.attachEvent) {- document.documentElement.attachEvent('onpropertychange', function(e) {- if (e.propertyName === 'localized') {- callback();- }- });- }- }+ getReadyState: function() { return gReadyState; }};+}) (window, document);diff --git a/data/ext/viewerPDF/locale/lt/chrome.properties b/data/ext/viewerPDF/locale/lt/chrome.propertiesnew file mode 100644index 000000000..228012b4a--- /dev/null+++ b/data/ext/viewerPDF/locale/lt/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=PDF dokumentas gali būti atvaizduojamas neteisingai.+open_with_different_viewer=Atidaryti su kita programa+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/lt/metadata.inc b/data/ext/viewerPDF/locale/lt/metadata.incnew file mode 100644index 000000000..e0841577c--- /dev/null+++ b/data/ext/viewerPDF/locale/lt/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>lt</em:locale>+ <em:name>PDF peržiūros programa</em:name>+ <em:description>PDF bylos vaizduojamos tiesiogiai, naudojant HTML5 Firefox naršyklėje.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.properties b/data/ext/viewerPDF/locale/lt/viewer.propertiessimilarity index 91%rename from data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.propertiesrename to data/ext/viewerPDF/locale/lt/viewer.propertiesindex a1c35d7b2..c2e457712 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/lt/viewer.properties+++ b/data/ext/viewerPDF/locale/lt/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Mažintizoom_in.title=Didintizoom_in_label=Didintizoom.title=Mastelis+print.title=Spausdinti+print_label=Spausdintipresentation_mode.title=Įjungti pateikimo būsenąpresentation_mode_label=Pateikimo būsenaopen_file.title=Atverti byląopen_file_label=Atverti-print.title=Spausdinti-print_label=Spausdintidownload.title=Atsiųstidownload_label=Atsiųstibookmark.title=Dabartinis rodymas (kopijuoti arba atidaryti naudojame lange)bookmark_label=Dabartinis rodymas-# Secondary toolbar and context menu-first_page.title=Nukreipimas į pirmą puslapį-first_page.label=Nukreipimas į pirmą puslapį-first_page_label=Nukreipimas į pirmą puslapį-last_page.title=Nukreipimas į paskutinį puslapį-last_page.label=Nukreipimas į paskutinį puslapį-last_page_label=Nukreipimas į paskutinį puslapį-page_rotate_cw.title=Sukimas pagal laikrodžio rodyklę-page_rotate_cw.label=Sukimas pagal laikrodžio rodyklę-page_rotate_cw_label=Sukimas pagal laikrodžio rodyklę-page_rotate_ccw.title=Sukimas prieš laikrodžio rodyklę-page_rotate_ccw.label=Sukimas prieš laikrodžio rodyklę-page_rotate_ccw_label=Sukimas prieš laikrodžio rodyklę-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title=Puslapis {{page}}# number.thumb_page_canvas=Miniatūra iš {{page}} puslapio+# Context menu+first_page.label=Nukreipimas į pirmą puslapį+last_page.label=Nukreipimas į paskutinį puslapį+page_rotate_cw.label=Sukimas pagal laikrodžio rodyklę+page_rotate_ccw.label=Sukimas prieš laikrodžio rodyklę+# Find panel button title and messagesfind_label=Paieška:find_previous.title=Ankstesnis paieškos atitikmuodiff --git a/data/ext/viewerPDF/locale/nl/chrome.properties b/data/ext/viewerPDF/locale/nl/chrome.propertiesnew file mode 100644index 000000000..6dd858e96--- /dev/null+++ b/data/ext/viewerPDF/locale/nl/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Dit PDF-document wordt mogelijk niet juist weergegeven.+open_with_different_viewer=Openen met andere viewer+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/nl/metadata.inc b/data/ext/viewerPDF/locale/nl/metadata.incnew file mode 100644index 000000000..8f0015557--- /dev/null+++ b/data/ext/viewerPDF/locale/nl/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>nl</em:locale>+ <em:name>PDF-viewer</em:name>+ <em:description>Gebruikt HTML5 om PDF-bestanden direct in Firefox te openen.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.properties b/data/ext/viewerPDF/locale/nl/viewer.propertiessimilarity index 74%rename from data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.propertiesrename to data/ext/viewerPDF/locale/nl/viewer.propertiesindex 9058c1534..10e953d81 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/nl/viewer.properties+++ b/data/ext/viewerPDF/locale/nl/viewer.properties@@ -30,58 +30,17 @@ zoom_out_label=Uitzoomenzoom_in.title=Inzoomenzoom_in_label=Inzoomenzoom.title=Zoomen+print.title=Afdrukken+print_label=Afdrukkenpresentation_mode.title=Omschakelen naar presentatiemoduspresentation_mode_label=Presentatiemodusopen_file.title=Bestand openenopen_file_label=Openen-print.title=Afdrukken-print_label=Afdrukkendownload.title=Downloadendownload_label=Downloadenbookmark.title=Huidige weergave (kopiëren of openen in nieuw venster)bookmark_label=Huidige weergave-# Secondary toolbar and context menu-tools.title=Hulpmiddelen-tools_label=Hulpmiddelen-first_page.title=Naar de eerste pagina gaan-first_page.label=Naar de eerste pagina gaan-first_page_label=Naar de eerste pagina gaan-last_page.title=Naar de laatste pagina gaan-last_page.label=Naar de laatste pagina gaan-last_page_label=Naar de laatste pagina gaan-page_rotate_cw.title=Met de klok mee roteren-page_rotate_cw.label=Met de klok mee roteren-page_rotate_cw_label=Met de klok mee roteren-page_rotate_ccw.title=Tegen de klok in roteren-page_rotate_ccw.label=Tegen de klok in roteren-page_rotate_ccw_label=Tegen de klok in roteren--hand_tool_enable.title=Handcursor inschakelen-hand_tool_enable_label=Handcursor inschakelen-hand_tool_disable.title=Handcursor uitschakelen-hand_tool_disable_label=Handcursor uitschakelen--# Document properties dialog box-document_properties.title=Documenteigenschappen…-document_properties_label=Documenteigenschappen…-document_properties_file_name=Bestandsnaam:-document_properties_file_size=Bestandsgrootte:-document_properties_kb={{size_kb}} KB ({{size_b}} bytes)-document_properties_mb={{size_mb}} MB ({{size_b}} bytes)-document_properties_title=Titel:-document_properties_author=Auteur:-document_properties_subject=Onderwerp:-document_properties_keywords=Trefwoorden:-document_properties_creation_date=Aanmaakdatum:-document_properties_modification_date=Wijzigingsdatum:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=Toepassing:-document_properties_producer=PDF-producent:-document_properties_version=PDF-versie:-document_properties_page_count=Aantal pagina's:-document_properties_close=Sluiten-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -102,6 +61,12 @@ thumb_page_title=Pagina {{page}}# number.thumb_page_canvas=Miniatuur van pagina {{page}}+# Context menu+first_page.label=Naar de eerste pagina gaan+last_page.label=Naar de laatste pagina gaan+page_rotate_cw.label=Met de klok mee roteren+page_rotate_ccw.label=Tegen de klok in roteren+# Find panel button title and messagesfind_label=Zoeken:find_previous.title=Het vorige voorkomen van de tekst zoeken@@ -150,10 +115,8 @@ missing_file_error=Ontbrekend PDF-bestand.# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}}-aantekening]-password_label=Voer het wachtwoord in om dit PDF-bestand te openen.-password_invalid=Onjuist wachtwoord. Probeer het opnieuw.-password_ok=OK-password_cancel=Annuleren+request_password=Dit PDF-bestand is beveiligd met een wachtwoord:+invalid_password=Onjuist wachtwoord.printing_not_supported=Waarschuwing: afdrukken wordt niet volledig ondersteund door deze browser.printing_not_ready=Waarschuwing: het PDF-bestand is niet volledig geladen en kan daarom nog niet afgedrukt worden.diff --git a/data/ext/viewerPDF/locale/pl/chrome.properties b/data/ext/viewerPDF/locale/pl/chrome.propertiesnew file mode 100644index 000000000..3bafa77b0--- /dev/null+++ b/data/ext/viewerPDF/locale/pl/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Ten plik PDF może nie być poprawnie wyświetlony.+open_with_different_viewer=Otwórz w innym programie.+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/pl/metadata.inc b/data/ext/viewerPDF/locale/pl/metadata.incnew file mode 100644index 000000000..0cc701d69--- /dev/null+++ b/data/ext/viewerPDF/locale/pl/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>pl</em:locale>+ <em:name>Przeglądarka PDF</em:name>+ <em:description>Używa HTML5 do wyświetlania plików PDF bezpośrednio w Firefoksie.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.properties b/data/ext/viewerPDF/locale/pl/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.propertiesrename to data/ext/viewerPDF/locale/pl/viewer.propertiesindex 61c384776..ab9d48f54 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/pl/viewer.properties+++ b/data/ext/viewerPDF/locale/pl/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Pomniejszzoom_in.title=Powiększzoom_in_label=Powiększzoom.title=Powiększenie+print.title=Drukuj+print_label=Drukujpresentation_mode.title=Przełącz do trybu prezentacjipresentation_mode_label=Tryb prezentacjiopen_file.title=Otwórz plikopen_file_label=Otwórz-print.title=Drukuj-print_label=Drukujdownload.title=Pobierzdownload_label=Pobierzbookmark.title=Aktualny widok (kopiuj lub otwórz w nowym oknie)bookmark_label=Aktualny widok-# Secondary toolbar and context menu-first_page.title=Idź do pierwszej strony-first_page.label=Idź do pierwszej strony-first_page_label=Idź do pierwszej strony-last_page.title=Idź do ostatniej strony-last_page.label=Idź do ostatniej strony-last_page_label=Idź do ostatniej strony-page_rotate_cw.title=Obróć w prawo-page_rotate_cw.label=Obróć w prawo-page_rotate_cw_label=Obróć w prawo-page_rotate_ccw.title=Obróć w lewo-page_rotate_ccw.label=Obróć w lewo-page_rotate_ccw_label=Obróć w lewo-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title=Strona {{page}}# number.thumb_page_canvas=Miniatura strony {{page}}+# Context menu+first_page.label=Idź do pierwszej strony+last_page.label=Idź do ostatniej strony+page_rotate_cw.label=Obróć w prawo+page_rotate_ccw.label=Obróć w lewo+# Find panel button title and messagesfind_label=Znajdź:find_previous.title=Znajdź poprzednie wystąpienie ostatnio szukanej frazydiff --git a/data/ext/viewerPDF/locale/pt-BR/metadata.inc b/data/ext/viewerPDF/locale/pt-BR/metadata.incnew file mode 100644index 000000000..179af8b31--- /dev/null+++ b/data/ext/viewerPDF/locale/pt-BR/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>pt-BR</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Aprensenta PDFs no browser usando a tecnologia HTML5.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/pt-BR/viewer.properties b/data/ext/viewerPDF/locale/pt-BR/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/pt-BR/viewer.propertiesrename to data/ext/viewerPDF/locale/pt-BR/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/ro/metadata.inc b/data/ext/viewerPDF/locale/ro/metadata.incnew file mode 100644index 000000000..e2c72eca5--- /dev/null+++ b/data/ext/viewerPDF/locale/ro/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ro</em:locale>+ <em:name>Cititor PDF</em:name>+ <em:description>Afișează fișierele PDF direct în Firefox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ro/viewer.properties b/data/ext/viewerPDF/locale/ro/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/ro/viewer.propertiesrename to data/ext/viewerPDF/locale/ro/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/ru/metadata.inc b/data/ext/viewerPDF/locale/ru/metadata.incnew file mode 100644index 000000000..410814c5d--- /dev/null+++ b/data/ext/viewerPDF/locale/ru/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>ru</em:locale>+ <em:name>PDF Viewer</em:name>+ <em:description>Показывает файлы PDF непосредственно в Firefox используя HTML5.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/ru/viewer.properties b/data/ext/viewerPDF/locale/ru/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/ru/viewer.propertiesrename to data/ext/viewerPDF/locale/ru/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/sr/metadata.inc b/data/ext/viewerPDF/locale/sr/metadata.incnew file mode 100644index 000000000..c8ab2d857--- /dev/null+++ b/data/ext/viewerPDF/locale/sr/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>sr</em:locale>+ <em:name>ПДФ читач</em:name>+ <em:description>Користи ХТМЛ5 да би приказао ПДФ датотеке директно у Фајерфоксу.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/sr/viewer.properties b/data/ext/viewerPDF/locale/sr/viewer.propertiessimilarity index 100%rename from data/ext/viewerPDF/pdfjs/web/locale/sr/viewer.propertiesrename to data/ext/viewerPDF/locale/sr/viewer.propertiesdiff --git a/data/ext/viewerPDF/locale/sv/chrome.properties b/data/ext/viewerPDF/locale/sv/chrome.propertiesnew file mode 100644index 000000000..fe6415d86--- /dev/null+++ b/data/ext/viewerPDF/locale/sv/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Detta PDF-dokument kanske inte visas korrekt.+open_with_different_viewer=Öppna med ett annat program+open_with_different_viewer.accessKey=ödiff --git a/data/ext/viewerPDF/locale/sv/metadata.inc b/data/ext/viewerPDF/locale/sv/metadata.incnew file mode 100644index 000000000..ec82bc1fb--- /dev/null+++ b/data/ext/viewerPDF/locale/sv/metadata.inc@@ -0,0 +1,7 @@+ <em:localized>+ <Description>+ <em:locale>sv</em:locale>+ <em:name>PDF-läsare</em:name>+ <em:description>Använder HTML5 för att visa PDF-filer direkt i Firefox.</em:description>+ </Description>+ </em:localized>diff --git a/data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.properties b/data/ext/viewerPDF/locale/sv/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.propertiesrename to data/ext/viewerPDF/locale/sv/viewer.propertiesindex cd145524e..24320bb9c 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/sv-SE/viewer.properties+++ b/data/ext/viewerPDF/locale/sv/viewer.properties@@ -30,58 +30,17 @@ zoom_out_label=Zooma utzoom_in.title=Zooma inzoom_in_label=Zooma inzoom.title=Zooma+print.title=Skriv ut+print_label=Skriv utpresentation_mode.title=Presentationslägepresentation_mode_label=Presentationslägeopen_file.title=Öppna filopen_file_label=Öppna-print.title=Skriv ut-print_label=Skriv utdownload.title=Ladda nerdownload_label=Ladda nerbookmark.title=Aktuell vy (kopiera eller öppna i nytt fönster)bookmark_label=Aktuell vy-# Secondary toolbar and context menu-tools.title=Verktyg-tools_label=Verktyg-first_page.title=Gå till första sidan-first_page.label=Gå till första sidan-first_page_label=Gå till första sidan-last_page.title=Gå till sista sidan-last_page.label=Gå till sista sidan-last_page_label=Gå till sista sidan-page_rotate_cw.title=Rotera medurs-page_rotate_cw.label=Rotera medurs-page_rotate_cw_label=Rotera medurs-page_rotate_ccw.title=Rotera moturs-page_rotate_ccw.label=Rotera moturs-page_rotate_ccw_label=Rotera moturs--hand_tool_enable.title=Aktivera handverktyget-hand_tool_enable_label=Aktivera handverktyget-hand_tool_disable.title=Avaktivera handverktyget-hand_tool_disable_label=Avaktivera handverktyget--# Document properties dialog box-document_properties.title=Dokumentegenskaper…-document_properties_label=Dokumentegenskaper…-document_properties_file_name=Filnamn:-document_properties_file_size=Filstorlek:-document_properties_kb={{size_kb}} kB ({{size_b}} byte)-document_properties_mb={{size_mb}} MB ({{size_b}} byte)-document_properties_title=Titel:-document_properties_author=Författare:-document_properties_subject=Ämne:-document_properties_keywords=Nyckelord:-document_properties_creation_date=Skapades:-document_properties_modification_date=Ändrades:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=Program:-document_properties_producer=PDF-framställning:-document_properties_version=PDF-version:-document_properties_page_count=Antal sidor:-document_properties_close=Stäng-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -102,6 +61,12 @@ thumb_page_title=Sida {{page}}# number.thumb_page_canvas=Miniatyr av sida {{page}}+# Context menu+first_page.label=Gå till första sidan+last_page.label=Gå till sista sidan+page_rotate_cw.label=Rotera medurs+page_rotate_ccw.label=Rotera moturs+# Find panel button title and messagesfind_label=Sök:find_previous.title=Hitta föregående förekomst av frasen@@ -150,11 +115,8 @@ missing_file_error=PDF-filen saknas.# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}}-anteckning]--password_label=Ange lösenordet för att öppna PDF-filen.-password_invalid=Felaktigt lösenord. Försök igen.-password_ok=OK-password_cancel=Avbryt+request_password=PDF-filen är lösenordsskyddad:+invalid_password=Felaktigt lösenord.printing_not_supported=Varning: Utskrifter stöds inte fullt ut av denna webbläsare.printing_not_ready=Varning: Hela PDF-filen måste laddas innan utskrift kan ske.diff --git a/data/ext/viewerPDF/locale/tr/chrome.properties b/data/ext/viewerPDF/locale/tr/chrome.propertiesnew file mode 100644index 000000000..0d4f10da6--- /dev/null+++ b/data/ext/viewerPDF/locale/tr/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Bu PDF Dosyası düzgün görüntülenemeyebilir.+open_with_different_viewer=Lütfen başka bir gösterici deneyin+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/tr/metadata.inc b/data/ext/viewerPDF/locale/tr/metadata.incnew file mode 100644index 000000000..13bc25384--- /dev/null+++ b/data/ext/viewerPDF/locale/tr/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>tr</em:locale>+ <em:name>PDF Gösterici</em:name>+ <em:description>Firefox içerisinde PDFleri göstermek için HTML5 kullanır.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.properties b/data/ext/viewerPDF/locale/tr/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.propertiesrename to data/ext/viewerPDF/locale/tr/viewer.propertiesindex c4b172c7f..ecd51c6cc 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/tr/viewer.properties+++ b/data/ext/viewerPDF/locale/tr/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Uzaklaşzoom_in.title=Yakınlaşzoom_in_label=Yakınlaşzoom.title=Yakınlaştır+print.title=Yazdır+print_label=Yazdırpresentation_mode.title=Sunum moduna geçiş yappresentation_mode_label=Sunum Moduopen_file.title=Dosya Açopen_file_label=Aç-print.title=Yazdır-print_label=Yazdırdownload.title=İndirdownload_label=İndirbookmark.title=Mevcut görünüm (kopyala yada yeni sayfada aç)bookmark_label=Mevcut Görünüm-# Secondary toolbar and context menu-first_page.title=İlk Sayfaya Git-first_page.label=İlk Sayfaya Git-first_page_label=İlk Sayfaya Git-last_page.title=Son Sayfaya Git-last_page.label=Son Sayfaya Git-last_page_label=Son Sayfaya Git-page_rotate_cw.title=Sağa Çevir-page_rotate_cw.label=Sağa Çevir-page_rotate_cw_label=Sağa Çevir-page_rotate_ccw.title=Sola Çevir-page_rotate_ccw.label=Sola Çevir-page_rotate_ccw_label=Sola Çevir-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title=Sayfa {{page}}# number.thumb_page_canvas={{page}} sayfasının ön izlemesi+# Context menu+first_page.label=İlk Sayfaya Git+last_page.label=Son Sayfaya Git+page_rotate_cw.label=Sağa Çevir+page_rotate_ccw.label=Sola Çevir+# Find panel button title and messagesfind_label=Bul:find_previous.title=Önceki cümleyi buldiff --git a/data/ext/viewerPDF/locale/vi/chrome.properties b/data/ext/viewerPDF/locale/vi/chrome.propertiesnew file mode 100644index 000000000..0770f7a9e--- /dev/null+++ b/data/ext/viewerPDF/locale/vi/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=Tài liệu PDF có thể hiện thị không chính xác.+open_with_different_viewer=Mở với chương trình xem khác+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/vi/metadata.inc b/data/ext/viewerPDF/locale/vi/metadata.incnew file mode 100644index 000000000..0c8653cd9--- /dev/null+++ b/data/ext/viewerPDF/locale/vi/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>vi-VN</em:locale>+ <em:name>Trình Xem PDF</em:name>+ <em:description>Dùng HTML5 để hiện trị PDF trực giao trên FireFox.</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.properties b/data/ext/viewerPDF/locale/vi/viewer.propertiessimilarity index 93%rename from data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.propertiesrename to data/ext/viewerPDF/locale/vi/viewer.propertiesindex a92af2537..fa473234e 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/vi/viewer.properties+++ b/data/ext/viewerPDF/locale/vi/viewer.properties@@ -30,31 +30,17 @@ zoom_out_label=Phóng tozoom_in.title=Thu nhỏzoom_in_label=Thu nhỏzoom.title=Thu phóng+print.title=In+print_label=Inpresentation_mode.title=Chuyển sang chế độ thuyết trìnhpresentation_mode_label=Chế độ Thuyết trìnhopen_file.title=Mở Tệpopen_file_label=Tệp-print.title=In-print_label=Indownload.title=Tải xuốngdownload_label=Tải xuốngbookmark.title=Đánh dấu (sao chép hoặc mở cửa sổ mới)bookmark_label=Đánh dấu-# Secondary toolbar and context menu-first_page.title=Đến trang đầu tiên-first_page.label=Đến trang đầu tiên-first_page_label=Đến trang đầu tiên-last_page.title=Đến trang cuối cùng-last_page.label=Đến trang cuối cùng-last_page_label=Đến trang cuối cùng-page_rotate_cw.title=Quay sang phải-page_rotate_cw.label=Quay sang phải-page_rotate_cw_label=Quay sang phải-page_rotate_ccw.title=Quay sang trái-page_rotate_ccw.label=Quay sang trái-page_rotate_ccw_label=Quay sang trái-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -75,6 +61,12 @@ thumb_page_title=Page {{page}}# number.thumb_page_canvas=Thumbnail of Page {{page}}+# Context menu+first_page.label=Đến trang đầu tiên+last_page.label=Đến trang cuối cùng+page_rotate_cw.label=Quay sang phải+page_rotate_ccw.label=Quay sang trái+# Find panel button title and messagesfind_label=Tìm:find_previous.title=Tìm kiếm câu xuất hiện phía trướcdiff --git a/data/ext/viewerPDF/locale/zh-CN/chrome.properties b/data/ext/viewerPDF/locale/zh-CN/chrome.propertiesnew file mode 100644index 000000000..c8ea0236d--- /dev/null+++ b/data/ext/viewerPDF/locale/zh-CN/chrome.properties@@ -0,0 +1,18 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=该 PDF 文档可能无法被正确显示+open_with_different_viewer=使用另一个 PDF 查看器打开+open_with_different_viewer.accessKey=odiff --git a/data/ext/viewerPDF/locale/zh-CN/metadata.inc b/data/ext/viewerPDF/locale/zh-CN/metadata.incnew file mode 100644index 000000000..04be27c78--- /dev/null+++ b/data/ext/viewerPDF/locale/zh-CN/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>zh-CN</em:locale>+ <em:name>PDF 查看器</em:name>+ <em:description>使用 HTML5 来支持在 Firefox 中直接显示 PDF 文件。</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.properties b/data/ext/viewerPDF/locale/zh-CN/viewer.propertiessimilarity index 83%rename from data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.propertiesrename to data/ext/viewerPDF/locale/zh-CN/viewer.propertiesindex bbc77c270..c27e60973 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/zh-CN/viewer.properties+++ b/data/ext/viewerPDF/locale/zh-CN/viewer.properties@@ -30,38 +30,17 @@ zoom_out_label=缩小zoom_in.title=放大zoom_in_label=放大zoom.title=缩放+print.title=打印+print_label=打印presentation_mode.title=切换至幻灯模式presentation_mode_label=幻灯模式open_file.title=打开文件open_file_label=打开-print.title=打印-print_label=打印download.title=下载download_label=下载bookmark.title=当前视图(复制或在新窗口中打开)bookmark_label=当前视图-# Secondary toolbar and context menu-tools.title=工具-tools_label=工具-first_page.title=转到第一页-first_page.label=转到第一页-first_page_label=转到第一页-last_page.title=转到结尾页-last_page.label=转到结尾页-last_page_label=转到结尾页-page_rotate_cw.title=顺时针旋转-page_rotate_cw.label=顺时针旋转-page_rotate_cw_label=顺时针旋转-page_rotate_ccw.title=逆时针旋转-page_rotate_ccw.label=逆时针旋转-page_rotate_ccw_label=逆时针旋转--hand_tool_enable.title=启用掌型工具-hand_tool_enable_label=启用掌型工具-hand_tool_disable.title=禁用掌型工具-hand_tool_disable_label=禁用掌型工具-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -82,6 +61,12 @@ thumb_page_title=页码 {{page}}# number.thumb_page_canvas=页面 {{page}} 的缩略图+# Context menu+first_page.label=转到第一页+last_page.label=转到结尾页+page_rotate_cw.label=顺时针旋转+page_rotate_ccw.label=逆时针旋转+# Find panel button title and messagesfind_label=查找:find_previous.title=查找该短语上一次出现的位置@@ -130,12 +115,7 @@ missing_file_error=缺失 PDF 文件。# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}} 注解]-password_label=输入 PDF 文件的密码。-password_invalid=密码无效,请重新输入。-password_ok=确定-password_cancel=取消+request_password=该 PDF 文档受密码保护:printing_not_supported=警告:该浏览器不能完全支持打印。-printing_not_ready=警告:此 PDF 没有完全被载入以供打印。web_fonts_disabled=Web 页面字体已被禁用,无法使用嵌入到 PDF 中的字体。-document_colors_disabled=PDF 文件不被允许使用自己的颜色:\‘允许页面选择自己的颜色’\没有在该浏览器中被激活。diff --git a/data/ext/viewerPDF/locale/zh-TW/chrome.properties b/data/ext/viewerPDF/locale/zh-TW/chrome.propertiesnew file mode 100644index 000000000..52399309c--- /dev/null+++ b/data/ext/viewerPDF/locale/zh-TW/chrome.properties@@ -0,0 +1,19 @@+# 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.++# Chrome notification bar messages and buttons+unsupported_feature=此 PDF 文件可能並未正確顯示。+open_with_different_viewer=使用其他檢視器開啟+open_with_different_viewer.accessKey=o+diff --git a/data/ext/viewerPDF/locale/zh-TW/metadata.inc b/data/ext/viewerPDF/locale/zh-TW/metadata.incnew file mode 100644index 000000000..6ef722be8--- /dev/null+++ b/data/ext/viewerPDF/locale/zh-TW/metadata.inc@@ -0,0 +1,8 @@+ <em:localized>+ <Description>+ <em:locale>zh-TW</em:locale>+ <em:name>PDF 瀏覽器</em:name>+ <em:description>利用 HTML5 技術在 Firefox 中直接顯示 PDF 格式檔案。</em:description>+ </Description>+ </em:localized>+diff --git a/data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.properties b/data/ext/viewerPDF/locale/zh-TW/viewer.propertiessimilarity index 75%rename from data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.propertiesrename to data/ext/viewerPDF/locale/zh-TW/viewer.propertiesindex 8bb223613..f83a13314 100644--- a/data/ext/viewerPDF/pdfjs/web/locale/zh-TW/viewer.properties+++ b/data/ext/viewerPDF/locale/zh-TW/viewer.properties@@ -30,58 +30,17 @@ zoom_out_label=縮小zoom_in.title=放大zoom_in_label=放大zoom.title=縮放+print.title=列印+print_label=列印presentation_mode.title=切換至簡報模式presentation_mode_label=簡報模式open_file.title=開啟檔案open_file_label=開啟-print.title=列印-print_label=列印download.title=下載download_label=下載bookmark.title=目前檢視的內容(複製或開啟於新視窗)bookmark_label=目前檢視-# Secondary toolbar and context menu-tools.title=工具-tools_label=工具-first_page.title=跳到第一頁-first_page.label=跳到第一頁-first_page_label=跳到第一頁-last_page.title=跳到最後一頁-last_page.label=跳到最後一頁-last_page_label=跳到最後一頁-page_rotate_cw.title=順時針旋轉-page_rotate_cw.label=順時針旋轉-page_rotate_cw_label=順時針旋轉-page_rotate_ccw.title=逆時針旋轉-page_rotate_ccw.label=逆時針旋轉-page_rotate_ccw_label=逆時針旋轉--hand_tool_enable.title=啟用掌型工具-hand_tool_enable_label=啟用掌型工具-hand_tool_disable.title=停用掌型工具-hand_tool_disable_label=停用掌型工具--# Document properties dialog box-document_properties.title=文件內容…-document_properties_label=文件內容…-document_properties_file_name=檔案名稱:-document_properties_file_size=檔案大小:-document_properties_kb={{size_kb}} KB({{size_b}} 位元組)-document_properties_mb={{size_kb}} MB({{size_b}} 位元組)-document_properties_title=標題:-document_properties_author=作者:-document_properties_subject=主旨:-document_properties_keywords=關鍵字:-document_properties_creation_date=建立日期:-document_properties_modification_date=修改日期:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=建立者:-document_properties_producer=PDF 產生器:-document_properties_version=PDF 版本:-document_properties_page_count=頁數:-document_properties_close=關閉-# Tooltips and alt text for side panel toolbar buttons# (the _label strings are alt text for the buttons, the .title strings are# tooltips)@@ -102,6 +61,12 @@ thumb_page_title=頁 {{page}}# number.thumb_page_canvas=頁 {{page}} 的縮圖+# Context menu+first_page.label=跳到第一頁+last_page.label=跳到最後一頁+page_rotate_cw.label=順時針旋轉+page_rotate_ccw.label=逆時針旋轉+# Find panel button title and messagesfind_label=尋找:find_previous.title=尋找文字前次出現的位置@@ -150,10 +115,8 @@ missing_file_error=找不到 PDF 檔案。# the PDF spec (32000-1:2008 Table 169 – Annotation types).# Some common types are e.g.: "Check", "Text", "Comment", "Note"text_annotation_type.alt=[{{type}} 註解]-password_label=請輸入用來開啟此 PDF 檔案的密碼。-password_invalid=密碼不正確,請再試一次。-password_ok=確定-password_cancel=取消+request_password=PDF 已被密碼保護:+invalid_password=密碼無效。printing_not_supported=警告: 此瀏覽器未完整支援列印功能。printing_not_ready=警告: 此 PDF 未完成下載以供列印。diff --git a/data/ext/viewerPDF/pdfjs/build/pdf.worker.js b/data/ext/viewerPDF/pdf.jssimilarity index 80%rename from data/ext/viewerPDF/pdfjs/build/pdf.worker.jsrename to data/ext/viewerPDF/pdf.jsindex aa7ccc136..f3030b63f 100644--- a/data/ext/viewerPDF/pdfjs/build/pdf.worker.js+++ b/data/ext/viewerPDF/pdf.js@@ -14,15 +14,14 @@* See the License for the specific language governing permissions and* limitations under the License.*/-/*jshint globalstrict: false */// Initializing PDFJS global object (if still undefined)if (typeof PDFJS === 'undefined') {(typeof window !== 'undefined' ? window : this).PDFJS = {};}-PDFJS.version = '1.0.21';-PDFJS.build = 'f954cde';+PDFJS.version = '0.8.298';+PDFJS.build = '81fa4a0';(function pdfjsWrapper() {// Use strict in our context only - users might not want it@@ -44,6728 +43,7813 @@ PDFJS.build = 'f954cde';* See the License for the specific language governing permissions and* limitations under the License.*/-/* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,- Promise */++// NOTE: Be careful what goes in this file, as it is also used from the context+// of the addon. So using warn/error in here will break the addon.'use strict';-var globalScope = (typeof window === 'undefined') ? this : window;-var isWorker = (typeof window == 'undefined');-var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];+var NetworkManager = (function NetworkManagerClosure() {-var TextRenderingMode = {- FILL: 0,- STROKE: 1,- FILL_STROKE: 2,- INVISIBLE: 3,- FILL_ADD_TO_PATH: 4,- STROKE_ADD_TO_PATH: 5,- FILL_STROKE_ADD_TO_PATH: 6,- ADD_TO_PATH: 7,- FILL_STROKE_MASK: 3,- ADD_TO_PATH_FLAG: 4-};+ var OK_RESPONSE = 200;+ var PARTIAL_CONTENT_RESPONSE = 206;-var ImageKind = {- GRAYSCALE_1BPP: 1,- RGB_24BPP: 2,- RGBA_32BPP: 3-};+ function NetworkManager(url, args) {+ this.url = url;+ args = args || {};+ this.httpHeaders = args.httpHeaders || {};+ this.getXhr = args.getXhr ||+ function NetworkManager_getXhr() {+ return new XMLHttpRequest();+ };-// The global PDFJS object exposes the API-// In production, it will be declared outside a global wrapper-// In development, it will be declared here-if (!globalScope.PDFJS) {- globalScope.PDFJS = {};-}+ this.currXhrId = 0;+ this.pendingRequests = {};+ this.loadedRequests = {};+ }-globalScope.PDFJS.pdfBug = false;+ function getArrayBuffer(xhr) {+ var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||+ xhr.responseArrayBuffer || xhr.response);+ if (typeof data !== 'string') {+ return data;+ }+ var length = data.length;+ var buffer = new Uint8Array(length);+ for (var i = 0; i < length; i++) {+ buffer[i] = data.charCodeAt(i) & 0xFF;+ }+ return buffer;+ }-PDFJS.VERBOSITY_LEVELS = {- errors: 0,- warnings: 1,- infos: 5-};+ NetworkManager.prototype = {+ requestRange: function NetworkManager_requestRange(begin, end, listeners) {+ var args = {+ begin: begin,+ end: end+ };+ for (var prop in listeners) {+ args[prop] = listeners[prop];+ }+ return this.request(args);+ },-// All the possible operations for an operator list.-var OPS = PDFJS.OPS = {- // Intentionally start from 1 so it is easy to spot bad operators that will be- // 0's.- dependency: 1,- setLineWidth: 2,- setLineCap: 3,- setLineJoin: 4,- setMiterLimit: 5,- setDash: 6,- setRenderingIntent: 7,- setFlatness: 8,- setGState: 9,- save: 10,- restore: 11,- transform: 12,- moveTo: 13,- lineTo: 14,- curveTo: 15,- curveTo2: 16,- curveTo3: 17,- closePath: 18,- rectangle: 19,- stroke: 20,- closeStroke: 21,- fill: 22,- eoFill: 23,- fillStroke: 24,- eoFillStroke: 25,- closeFillStroke: 26,- closeEOFillStroke: 27,- endPath: 28,- clip: 29,- eoClip: 30,- beginText: 31,- endText: 32,- setCharSpacing: 33,- setWordSpacing: 34,- setHScale: 35,- setLeading: 36,- setFont: 37,- setTextRenderingMode: 38,- setTextRise: 39,- moveText: 40,- setLeadingMoveText: 41,- setTextMatrix: 42,- nextLine: 43,- showText: 44,- showSpacedText: 45,- nextLineShowText: 46,- nextLineSetSpacingShowText: 47,- setCharWidth: 48,- setCharWidthAndBounds: 49,- setStrokeColorSpace: 50,- setFillColorSpace: 51,- setStrokeColor: 52,- setStrokeColorN: 53,- setFillColor: 54,- setFillColorN: 55,- setStrokeGray: 56,- setFillGray: 57,- setStrokeRGBColor: 58,- setFillRGBColor: 59,- setStrokeCMYKColor: 60,- setFillCMYKColor: 61,- shadingFill: 62,- beginInlineImage: 63,- beginImageData: 64,- endInlineImage: 65,- paintXObject: 66,- markPoint: 67,- markPointProps: 68,- beginMarkedContent: 69,- beginMarkedContentProps: 70,- endMarkedContent: 71,- beginCompat: 72,- endCompat: 73,- paintFormXObjectBegin: 74,- paintFormXObjectEnd: 75,- beginGroup: 76,- endGroup: 77,- beginAnnotations: 78,- endAnnotations: 79,- beginAnnotation: 80,- endAnnotation: 81,- paintJpegXObject: 82,- paintImageMaskXObject: 83,- paintImageMaskXObjectGroup: 84,- paintImageXObject: 85,- paintInlineImageXObject: 86,- paintInlineImageXObjectGroup: 87,- paintImageXObjectRepeat: 88,- paintImageMaskXObjectRepeat: 89,- paintSolidColorImageMask: 90-};+ requestFull: function NetworkManager_requestRange(listeners) {+ return this.request(listeners);+ },-// A notice for devs. These are good for things that are helpful to devs, such-// as warning that Workers were disabled, which is important to devs but not-// end users.-function info(msg) {- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {- console.log('Info: ' + msg);- }-}+ request: function NetworkManager_requestRange(args) {+ var xhr = this.getXhr();+ var xhrId = this.currXhrId++;+ var pendingRequest = this.pendingRequests[xhrId] = {+ xhr: xhr+ };-// Non-fatal warnings.-function warn(msg) {- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {- console.log('Warning: ' + msg);- }-}+ xhr.open('GET', this.url);+ for (var property in this.httpHeaders) {+ var value = this.httpHeaders[property];+ if (typeof value === 'undefined') {+ continue;+ }+ xhr.setRequestHeader(property, value);+ }+ if ('begin' in args && 'end' in args) {+ var rangeStr = args.begin + '-' + (args.end - 1);+ xhr.setRequestHeader('Range', 'bytes=' + rangeStr);+ pendingRequest.expectedStatus = 206;+ } else {+ pendingRequest.expectedStatus = 200;+ }-// Fatal errors that should trigger the fallback UI and halt execution by-// throwing an exception.-function error(msg) {- // If multiple arguments were passed, pass them all to the log function.- if (arguments.length > 1) {- var logArguments = ['Error:'];- logArguments.push.apply(logArguments, arguments);- console.log.apply(console, logArguments);- // Join the arguments into a single string for the lines below.- msg = [].join.call(arguments, ' ');- } else {- console.log('Error: ' + msg);- }- console.log(backtrace());- UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);- throw new Error(msg);-}+ xhr.mozResponseType = xhr.responseType = 'arraybuffer';-function backtrace() {- try {- throw new Error();- } catch (e) {- return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';- }-}+ if (args.onProgress) {+ xhr.onprogress = args.onProgress;+ }+ if (args.onError) {+ xhr.onerror = function(evt) {+ args.onError(xhr.status);+ };+ }+ xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);-function assert(cond, msg) {- if (!cond) {- error(msg);- }-}+ pendingRequest.onHeadersReceived = args.onHeadersReceived;+ pendingRequest.onDone = args.onDone;+ pendingRequest.onError = args.onError;-var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {- unknown: 'unknown',- forms: 'forms',- javaScript: 'javaScript',- smask: 'smask',- shadingPattern: 'shadingPattern',- font: 'font'-};+ xhr.send(null);-var UnsupportedManager = PDFJS.UnsupportedManager =- (function UnsupportedManagerClosure() {- var listeners = [];- return {- listen: function (cb) {- listeners.push(cb);+ return xhrId;},- notify: function (featureId) {- warn('Unsupported feature "' + featureId + '"');- for (var i = 0, ii = listeners.length; i < ii; i++) {- listeners[i](featureId);++ onStateChange: function NetworkManager_onStateChange(xhrId, evt) {+ var pendingRequest = this.pendingRequests[xhrId];+ if (!pendingRequest) {+ // Maybe abortRequest was called...+ return;}- }- };-})();-// Combines two URLs. The baseUrl shall be absolute URL. If the url is an-// absolute URL, it will be returned as is.-function combineUrl(baseUrl, url) {- if (!url) {- return baseUrl;- }- if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {- return url;- }- var i;- if (url.charAt(0) == '/') {- // absolute path- i = baseUrl.indexOf('://');- if (url.charAt(1) === '/') {- ++i;- } else {- i = baseUrl.indexOf('/', i + 3);- }- return baseUrl.substring(0, i) + url;- } else {- // relative path- var pathLength = baseUrl.length;- i = baseUrl.lastIndexOf('#');- pathLength = i >= 0 ? i : pathLength;- i = baseUrl.lastIndexOf('?', pathLength);- pathLength = i >= 0 ? i : pathLength;- var prefixLength = baseUrl.lastIndexOf('/', pathLength);- return baseUrl.substring(0, prefixLength + 1) + url;- }-}+ var xhr = pendingRequest.xhr;+ if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {+ pendingRequest.onHeadersReceived();+ delete pendingRequest.onHeadersReceived;+ }-// Validates if URL is safe and allowed, e.g. to avoid XSS.-function isValidUrl(url, allowRelative) {- if (!url) {- return false;- }- // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)- // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )- var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);- if (!protocol) {- return allowRelative;- }- protocol = protocol[0].toLowerCase();- switch (protocol) {- case 'http':- case 'https':- case 'ftp':- case 'mailto':- return true;- default:- return false;- }-}-PDFJS.isValidUrl = isValidUrl;+ if (xhr.readyState !== 4) {+ return;+ }-function shadow(obj, prop, value) {- Object.defineProperty(obj, prop, { value: value,- enumerable: true,- configurable: true,- writable: false });- return value;-}+ if (!(xhrId in this.pendingRequests)) {+ // The XHR request might have been aborted in onHeadersReceived()+ // callback, in which case we should abort request+ return;+ }-var PasswordResponses = PDFJS.PasswordResponses = {- NEED_PASSWORD: 1,- INCORRECT_PASSWORD: 2-};+ delete this.pendingRequests[xhrId];-var PasswordException = (function PasswordExceptionClosure() {- function PasswordException(msg, code) {- this.name = 'PasswordException';- this.message = msg;- this.code = code;- }+ // success status == 0 can be on ftp, file and other protocols+ if (xhr.status === 0 && /^https?:/i.test(this.url)) {+ if (pendingRequest.onError) {+ pendingRequest.onError(xhr.status);+ }+ return;+ }+ var xhrStatus = xhr.status || OK_RESPONSE;- PasswordException.prototype = new Error();- PasswordException.constructor = PasswordException;+ // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:+ // "A server MAY ignore the Range header". This means it's possible to+ // get a 200 rather than a 206 response from a range request.+ var ok_response_on_range_request =+ xhrStatus === OK_RESPONSE &&+ pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;- return PasswordException;-})();+ if (!ok_response_on_range_request &&+ xhrStatus !== pendingRequest.expectedStatus) {+ if (pendingRequest.onError) {+ pendingRequest.onError(xhr.status);+ }+ return;+ }-var UnknownErrorException = (function UnknownErrorExceptionClosure() {- function UnknownErrorException(msg, details) {- this.name = 'UnknownErrorException';- this.message = msg;- this.details = details;- }+ this.loadedRequests[xhrId] = true;- UnknownErrorException.prototype = new Error();- UnknownErrorException.constructor = UnknownErrorException;+ var chunk = getArrayBuffer(xhr);+ if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {+ var rangeHeader = xhr.getResponseHeader('Content-Range');+ var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);+ var begin = parseInt(matches[1], 10);+ pendingRequest.onDone({+ begin: begin,+ chunk: chunk+ });+ } else {+ pendingRequest.onDone({+ begin: 0,+ chunk: chunk+ });+ }+ },- return UnknownErrorException;-})();+ hasPendingRequests: function NetworkManager_hasPendingRequests() {+ for (var xhrId in this.pendingRequests) {+ return true;+ }+ return false;+ },-var InvalidPDFException = (function InvalidPDFExceptionClosure() {- function InvalidPDFException(msg) {- this.name = 'InvalidPDFException';- this.message = msg;- }+ getRequestXhr: function NetworkManager_getXhr(xhrId) {+ return this.pendingRequests[xhrId].xhr;+ },- InvalidPDFException.prototype = new Error();- InvalidPDFException.constructor = InvalidPDFException;+ isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {+ return xhrId in this.pendingRequests;+ },- return InvalidPDFException;-})();+ isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {+ return xhrId in this.loadedRequests;+ },-var MissingPDFException = (function MissingPDFExceptionClosure() {- function MissingPDFException(msg) {- this.name = 'MissingPDFException';- this.message = msg;- }+ abortAllRequests: function NetworkManager_abortAllRequests() {+ for (var xhrId in this.pendingRequests) {+ this.abortRequest(xhrId | 0);+ }+ },- MissingPDFException.prototype = new Error();- MissingPDFException.constructor = MissingPDFException;+ abortRequest: function NetworkManager_abortRequest(xhrId) {+ var xhr = this.pendingRequests[xhrId].xhr;+ delete this.pendingRequests[xhrId];+ xhr.abort();+ }+ };- return MissingPDFException;+ return NetworkManager;})();-var NotImplementedException = (function NotImplementedExceptionClosure() {- function NotImplementedException(msg) {- this.message = msg;- }-- NotImplementedException.prototype = new Error();- NotImplementedException.prototype.name = 'NotImplementedException';- NotImplementedException.constructor = NotImplementedException;- return NotImplementedException;-})();-var MissingDataException = (function MissingDataExceptionClosure() {- function MissingDataException(begin, end) {- this.begin = begin;- this.end = end;- this.message = 'Missing data [' + begin + ', ' + end + ')';+var ChunkedStream = (function ChunkedStreamClosure() {+ function ChunkedStream(length, chunkSize, manager) {+ this.bytes = new Uint8Array(length);+ this.start = 0;+ this.pos = 0;+ this.end = length;+ this.chunkSize = chunkSize;+ this.loadedChunks = [];+ this.numChunksLoaded = 0;+ this.numChunks = Math.ceil(length / chunkSize);+ this.manager = manager;}- MissingDataException.prototype = new Error();- MissingDataException.prototype.name = 'MissingDataException';- MissingDataException.constructor = MissingDataException;-- return MissingDataException;-})();--var XRefParseException = (function XRefParseExceptionClosure() {- function XRefParseException(msg) {- this.message = msg;- }+ // required methods for a stream. if a particular stream does not+ // implement these, an error should be thrown+ ChunkedStream.prototype = {- XRefParseException.prototype = new Error();- XRefParseException.prototype.name = 'XRefParseException';- XRefParseException.constructor = XRefParseException;+ getMissingChunks: function ChunkedStream_getMissingChunks() {+ var chunks = [];+ for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ chunks.push(chunk);+ }+ }+ return chunks;+ },- return XRefParseException;-})();+ allChunksLoaded: function ChunkedStream_allChunksLoaded() {+ return this.numChunksLoaded === this.numChunks;+ },+ onReceiveData: function(begin, chunk) {+ var end = begin + chunk.byteLength;-function bytesToString(bytes) {- var length = bytes.length;- var MAX_ARGUMENT_COUNT = 8192;- if (length < MAX_ARGUMENT_COUNT) {- return String.fromCharCode.apply(null, bytes);- }- var strBuf = [];- for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {- var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);- var chunk = bytes.subarray(i, chunkEnd);- strBuf.push(String.fromCharCode.apply(null, chunk));- }- return strBuf.join('');-}+ assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);+ // Using this.length is inaccurate here since this.start can be moved+ // See ChunkedStream.moveStart()+ var length = this.bytes.length;+ assert(end % this.chunkSize === 0 || end === length,+ 'Bad end offset: ' + end);-function stringToArray(str) {- var length = str.length;- var array = [];- for (var i = 0; i < length; ++i) {- array[i] = str.charCodeAt(i);- }- return array;-}+ this.bytes.set(new Uint8Array(chunk), begin);+ var chunkSize = this.chunkSize;+ var beginChunk = Math.floor(begin / chunkSize);+ var endChunk = Math.floor((end - 1) / chunkSize) + 1;-function stringToBytes(str) {- var length = str.length;- var bytes = new Uint8Array(length);- for (var i = 0; i < length; ++i) {- bytes[i] = str.charCodeAt(i) & 0xFF;- }- return bytes;-}+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ this.loadedChunks[chunk] = true;+ ++this.numChunksLoaded;+ }+ }+ },-function string32(value) {- return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,- (value >> 8) & 0xff, value & 0xff);-}+ ensureRange: function ChunkedStream_ensureRange(begin, end) {+ if (begin >= end) {+ return;+ }-// Lazy test the endianness of the platform-// NOTE: This will be 'true' for simulated TypedArrays-function isLittleEndian() {- var buffer8 = new Uint8Array(2);- buffer8[0] = 1;- var buffer16 = new Uint16Array(buffer8.buffer);- return (buffer16[0] === 1);-}+ var chunkSize = this.chunkSize;+ var beginChunk = Math.floor(begin / chunkSize);+ var endChunk = Math.floor((end - 1) / chunkSize) + 1;+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ throw new MissingDataException(begin, end);+ }+ }+ },-Object.defineProperty(PDFJS, 'isLittleEndian', {- configurable: true,- get: function PDFJS_isLittleEndian() {- return shadow(PDFJS, 'isLittleEndian', isLittleEndian());- }-});+ nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {+ for (var chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ return chunk;+ }+ }+ // Wrap around to beginning+ for (var chunk = 0; chunk < beginChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ return chunk;+ }+ }+ return null;+ },- // Lazy test if the userAgant support CanvasTypedArrays-function hasCanvasTypedArrays() {- var canvas = document.createElement('canvas');- canvas.width = canvas.height = 1;- var ctx = canvas.getContext('2d');- var imageData = ctx.createImageData(1, 1);- return (typeof imageData.data.buffer !== 'undefined');-}+ hasChunk: function ChunkedStream_hasChunk(chunk) {+ return chunk in this.loadedChunks;+ },-Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {- configurable: true,- get: function PDFJS_hasCanvasTypedArrays() {- return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());- }-});+ get length() {+ return this.end - this.start;+ },-var Uint32ArrayView = (function Uint32ArrayViewClosure() {+ getByte: function ChunkedStream_getByte() {+ var pos = this.pos;+ if (pos >= this.end) {+ return null;+ }+ this.ensureRange(pos, pos + 1);+ return this.bytes[this.pos++];+ },- function Uint32ArrayView(buffer, length) {- this.buffer = buffer;- this.byteLength = buffer.length;- this.length = length === undefined ? (this.byteLength >> 2) : length;- ensureUint32ArrayViewProps(this.length);- }- Uint32ArrayView.prototype = Object.create(null);+ // returns subarray of original buffer+ // should only be read+ getBytes: function ChunkedStream_getBytes(length) {+ var bytes = this.bytes;+ var pos = this.pos;+ var strEnd = this.end;- var uint32ArrayViewSetters = 0;- function createUint32ArrayProp(index) {- return {- get: function () {- var buffer = this.buffer, offset = index << 2;- return (buffer[offset] | (buffer[offset + 1] << 8) |- (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;- },- set: function (value) {- var buffer = this.buffer, offset = index << 2;- buffer[offset] = value & 255;- buffer[offset + 1] = (value >> 8) & 255;- buffer[offset + 2] = (value >> 16) & 255;- buffer[offset + 3] = (value >>> 24) & 255;+ if (!length) {+ this.ensureRange(pos, strEnd);+ return bytes.subarray(pos, strEnd);}- };- }-- function ensureUint32ArrayViewProps(length) {- while (uint32ArrayViewSetters < length) {- Object.defineProperty(Uint32ArrayView.prototype,- uint32ArrayViewSetters,- createUint32ArrayProp(uint32ArrayViewSetters));- uint32ArrayViewSetters++;- }- }- return Uint32ArrayView;-})();+ var end = pos + length;+ if (end > strEnd)+ end = strEnd;+ this.ensureRange(pos, end);-var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];+ this.pos = end;+ return bytes.subarray(pos, end);+ },-var Util = PDFJS.Util = (function UtilClosure() {- function Util() {}+ peekBytes: function ChunkedStream_peekBytes(length) {+ var bytes = this.getBytes(length);+ this.pos -= bytes.length;+ return bytes;+ },- Util.makeCssRgb = function Util_makeCssRgb(rgb) {- return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';- };+ getByteRange: function ChunkedStream_getBytes(begin, end) {+ this.ensureRange(begin, end);+ return this.bytes.subarray(begin, end);+ },- Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) {- var rgb = ColorSpace.singletons.cmyk.getRgb(cmyk, 0);- return Util.makeCssRgb(rgb);- };+ lookChar: function ChunkedStream_lookChar() {+ var pos = this.pos;+ if (pos >= this.end)+ return null;+ this.ensureRange(pos, pos + 1);+ return String.fromCharCode(this.bytes[pos]);+ },- // Concatenates two transformation matrices together and returns the result.- Util.transform = function Util_transform(m1, m2) {- return [- m1[0] * m2[0] + m1[2] * m2[1],- m1[1] * m2[0] + m1[3] * m2[1],- m1[0] * m2[2] + m1[2] * m2[3],- m1[1] * m2[2] + m1[3] * m2[3],- m1[0] * m2[4] + m1[2] * m2[5] + m1[4],- m1[1] * m2[4] + m1[3] * m2[5] + m1[5]- ];- };+ getChar: function ChunkedStream_getChar() {+ var pos = this.pos;+ if (pos >= this.end)+ return null;+ this.ensureRange(pos, pos + 1);+ return String.fromCharCode(this.bytes[this.pos++]);+ },- // For 2d affine transforms- Util.applyTransform = function Util_applyTransform(p, m) {- var xt = p[0] * m[0] + p[1] * m[2] + m[4];- var yt = p[0] * m[1] + p[1] * m[3] + m[5];- return [xt, yt];- };+ skip: function ChunkedStream_skip(n) {+ if (!n)+ n = 1;+ this.pos += n;+ },- Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {- var d = m[0] * m[3] - m[1] * m[2];- var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;- var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;- return [xt, yt];- };+ reset: function ChunkedStream_reset() {+ this.pos = this.start;+ },- // Applies the transform to the rectangle and finds the minimum axially- // aligned bounding box.- Util.getAxialAlignedBoundingBox =- function Util_getAxialAlignedBoundingBox(r, m) {-- var p1 = Util.applyTransform(r, m);- var p2 = Util.applyTransform(r.slice(2, 4), m);- var p3 = Util.applyTransform([r[0], r[3]], m);- var p4 = Util.applyTransform([r[2], r[1]], m);- return [- Math.min(p1[0], p2[0], p3[0], p4[0]),- Math.min(p1[1], p2[1], p3[1], p4[1]),- Math.max(p1[0], p2[0], p3[0], p4[0]),- Math.max(p1[1], p2[1], p3[1], p4[1])- ];- };-- Util.inverseTransform = function Util_inverseTransform(m) {- var d = m[0] * m[3] - m[1] * m[2];- return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,- (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];- };-- // Apply a generic 3d matrix M on a 3-vector v:- // | a b c | | X |- // | d e f | x | Y |- // | g h i | | Z |- // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],- // with v as [X,Y,Z]- Util.apply3dTransform = function Util_apply3dTransform(m, v) {- return [- m[0] * v[0] + m[1] * v[1] + m[2] * v[2],- m[3] * v[0] + m[4] * v[1] + m[5] * v[2],- m[6] * v[0] + m[7] * v[1] + m[8] * v[2]- ];- };-- // This calculation uses Singular Value Decomposition.- // The SVD can be represented with formula A = USV. We are interested in the- // matrix S here because it represents the scale values.- Util.singularValueDecompose2dScale =- function Util_singularValueDecompose2dScale(m) {-- var transpose = [m[0], m[2], m[1], m[3]];-- // Multiply matrix m with its transpose.- var a = m[0] * transpose[0] + m[1] * transpose[2];- var b = m[0] * transpose[1] + m[1] * transpose[3];- var c = m[2] * transpose[0] + m[3] * transpose[2];- var d = m[2] * transpose[1] + m[3] * transpose[3];-- // Solve the second degree polynomial to get roots.- var first = (a + d) / 2;- var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;- var sx = first + second || 1;- var sy = first - second || 1;+ moveStart: function ChunkedStream_moveStart() {+ this.start = this.pos;+ },- // Scale values are the square roots of the eigenvalues.- return [Math.sqrt(sx), Math.sqrt(sy)];- };+ makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {+ function ChunkedStreamSubstream() {}+ ChunkedStreamSubstream.prototype = Object.create(this);+ ChunkedStreamSubstream.prototype.getMissingChunks = function() {+ var chunkSize = this.chunkSize;+ var beginChunk = Math.floor(this.start / chunkSize);+ var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;+ var missingChunks = [];+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ if (!(chunk in this.loadedChunks)) {+ missingChunks.push(chunk);+ }+ }+ return missingChunks;+ };+ var subStream = new ChunkedStreamSubstream();+ subStream.pos = subStream.start = start;+ subStream.end = start + length || this.end;+ subStream.dict = dict;+ return subStream;+ },- // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)- // For coordinate systems whose origin lies in the bottom-left, this- // means normalization to (BL,TR) ordering. For systems with origin in the- // top-left, this means (TL,BR) ordering.- Util.normalizeRect = function Util_normalizeRect(rect) {- var r = rect.slice(0); // clone rect- if (rect[0] > rect[2]) {- r[0] = rect[2];- r[2] = rect[0];- }- if (rect[1] > rect[3]) {- r[1] = rect[3];- r[3] = rect[1];- }- return r;+ isStream: true};- // Returns a rectangle [x1, y1, x2, y2] corresponding to the- // intersection of rect1 and rect2. If no intersection, returns 'false'- // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]- Util.intersect = function Util_intersect(rect1, rect2) {- function compare(a, b) {- return a - b;- }+ return ChunkedStream;+})();- // Order points along the axes- var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),- orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),- result = [];+var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {- rect1 = Util.normalizeRect(rect1);- rect2 = Util.normalizeRect(rect2);+ function ChunkedStreamManager(length, chunkSize, url, args) {+ var self = this;+ this.stream = new ChunkedStream(length, chunkSize, this);+ this.length = length;+ this.chunkSize = chunkSize;+ this.url = url;+ this.disableAutoFetch = args.disableAutoFetch;+ var msgHandler = this.msgHandler = args.msgHandler;- // X: first and second points belong to different rectangles?- if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||- (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {- // Intersection must be between second and third points- result[0] = orderedX[1];- result[2] = orderedX[2];+ if (args.chunkedViewerLoading) {+ msgHandler.on('OnDataRange', this.onReceiveData.bind(this));+ msgHandler.on('OnDataProgress', this.onProgress.bind(this));+ this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {+ msgHandler.send('RequestDataRange', { begin: begin, end: end });+ };} else {- return false;- }- // Y: first and second points belong to different rectangles?- if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||- (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {- // Intersection must be between second and third points- result[1] = orderedY[1];- result[3] = orderedY[2];- } else {- return false;+ var getXhr = function getXhr() {+ return new XMLHttpRequest();+ };+ this.networkManager = new NetworkManager(this.url, {+ getXhr: getXhr,+ httpHeaders: args.httpHeaders+ });+ this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {+ this.networkManager.requestRange(begin, end, {+ onDone: this.onReceiveData.bind(this),+ onProgress: this.onProgress.bind(this)+ });+ };}- return result;- };+ this.currRequestId = 0;- Util.sign = function Util_sign(num) {- return num < 0 ? -1 : 1;- };+ this.chunksNeededByRequest = {};+ this.requestsByChunk = {};+ this.callbacksByRequest = {};- // TODO(mack): Rename appendToArray- Util.concatenateToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.push.apply(arr1, arr2);- };+ this.loadedStream = new Promise();+ }- Util.prependToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.unshift.apply(arr1, arr2);- };+ ChunkedStreamManager.prototype = {- Util.extendObj = function extendObj(obj1, obj2) {- for (var key in obj2) {- obj1[key] = obj2[key];- }- };+ onLoadedStream: function ChunkedStreamManager_getLoadedStream() {+ return this.loadedStream;+ },- Util.getInheritableProperty = function Util_getInheritableProperty(dict,- name) {- while (dict && !dict.has(name)) {- dict = dict.get('Parent');- }- if (!dict) {- return null;- }- return dict.get(name);- };+ // Get all the chunks that are not yet loaded and groups them into+ // contiguous ranges to load in as few requests as possible+ requestAllChunks: function ChunkedStreamManager_requestAllChunks() {+ var missingChunks = this.stream.getMissingChunks();+ this.requestChunks(missingChunks);+ return this.loadedStream;+ },- Util.inherit = function Util_inherit(sub, base, prototype) {- sub.prototype = Object.create(base.prototype);- sub.prototype.constructor = sub;- for (var prop in prototype) {- sub.prototype[prop] = prototype[prop];- }- };+ requestChunks: function ChunkedStreamManager_requestChunks(chunks,+ callback) {+ var requestId = this.currRequestId++;- Util.loadScript = function Util_loadScript(src, callback) {- var script = document.createElement('script');- var loaded = false;- script.setAttribute('src', src);- if (callback) {- script.onload = function() {- if (!loaded) {- callback();+ var chunksNeeded;+ this.chunksNeededByRequest[requestId] = chunksNeeded = {};+ for (var i = 0, ii = chunks.length; i < ii; i++) {+ if (!this.stream.hasChunk(chunks[i])) {+ chunksNeeded[chunks[i]] = true;}- loaded = true;- };- }- document.getElementsByTagName('head')[0].appendChild(script);- };+ }- return Util;-})();+ if (isEmptyObj(chunksNeeded)) {+ if (callback) {+ callback();+ }+ return;+ }-var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {- function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {- this.viewBox = viewBox;- this.scale = scale;- this.rotation = rotation;- this.offsetX = offsetX;- this.offsetY = offsetY;+ this.callbacksByRequest[requestId] = callback;- // creating transform to convert pdf coordinate system to the normal- // canvas like coordinates taking in account scale and rotation- var centerX = (viewBox[2] + viewBox[0]) / 2;- var centerY = (viewBox[3] + viewBox[1]) / 2;- var rotateA, rotateB, rotateC, rotateD;- rotation = rotation % 360;- rotation = rotation < 0 ? rotation + 360 : rotation;- switch (rotation) {- case 180:- rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;- break;- case 90:- rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;- break;- case 270:- rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;- break;- //case 0:- default:- rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;- break;- }+ var chunksToRequest = [];+ for (var chunk in chunksNeeded) {+ chunk = chunk | 0;+ if (!(chunk in this.requestsByChunk)) {+ this.requestsByChunk[chunk] = [];+ chunksToRequest.push(chunk);+ }+ this.requestsByChunk[chunk].push(requestId);+ }- if (dontFlip) {- rotateC = -rotateC; rotateD = -rotateD;- }+ if (!chunksToRequest.length) {+ return;+ }- var offsetCanvasX, offsetCanvasY;- var width, height;- if (rotateA === 0) {- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;- width = Math.abs(viewBox[3] - viewBox[1]) * scale;- height = Math.abs(viewBox[2] - viewBox[0]) * scale;- } else {- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;- width = Math.abs(viewBox[2] - viewBox[0]) * scale;- height = Math.abs(viewBox[3] - viewBox[1]) * scale;- }- // creating transform for the following operations:- // translate(-centerX, -centerY), rotate and flip vertically,- // scale, and translate(offsetCanvasX, offsetCanvasY)- this.transform = [- rotateA * scale,- rotateB * scale,- rotateC * scale,- rotateD * scale,- offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,- offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY- ];+ var groupedChunksToRequest = this.groupChunks(chunksToRequest);- this.width = width;- this.height = height;- this.fontScale = scale;- }- PageViewport.prototype = {- clone: function PageViewPort_clone(args) {- args = args || {};- var scale = 'scale' in args ? args.scale : this.scale;- var rotation = 'rotation' in args ? args.rotation : this.rotation;- return new PageViewport(this.viewBox.slice(), scale, rotation,- this.offsetX, this.offsetY, args.dontFlip);- },- convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {- return Util.applyTransform([x, y], this.transform);+ for (var i = 0; i < groupedChunksToRequest.length; ++i) {+ var groupedChunk = groupedChunksToRequest[i];+ var begin = groupedChunk.beginChunk * this.chunkSize;+ var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);+ this.sendRequest(begin, end);+ }},- convertToViewportRectangle:- function PageViewport_convertToViewportRectangle(rect) {- var tl = Util.applyTransform([rect[0], rect[1]], this.transform);- var br = Util.applyTransform([rect[2], rect[3]], this.transform);- return [tl[0], tl[1], br[0], br[1]];++ getStream: function ChunkedStreamManager_getStream() {+ return this.stream;},- convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {- return Util.applyInverseTransform([x, y], this.transform);- }- };- return PageViewport;-})();-var PDFStringTranslateTable = [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,- 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,- 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,- 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC-];+ // Loads any chunks in the requested range that are not yet loaded+ requestRange: function ChunkedStreamManager_requestRange(+ begin, end, callback) {-function stringToPDFString(str) {- var i, n = str.length, strBuf = [];- if (str[0] === '\xFE' && str[1] === '\xFF') {- // UTF16BE BOM- for (i = 2; i < n; i += 2) {- strBuf.push(String.fromCharCode(- (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));- }- } else {- for (i = 0; i < n; ++i) {- var code = PDFStringTranslateTable[str.charCodeAt(i)];- strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));- }- }- return strBuf.join('');-}+ end = Math.min(end, this.length);-function stringToUTF8String(str) {- return decodeURIComponent(escape(str));-}+ var beginChunk = this.getBeginChunk(begin);+ var endChunk = this.getEndChunk(end);-function isEmptyObj(obj) {- for (var key in obj) {- return false;- }- return true;-}+ var chunks = [];+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ chunks.push(chunk);+ }-function isBool(v) {- return typeof v == 'boolean';-}+ this.requestChunks(chunks, callback);+ },-function isInt(v) {- return typeof v == 'number' && ((v | 0) == v);-}+ requestRanges: function ChunkedStreamManager_requestRanges(ranges,+ callback) {+ ranges = ranges || [];+ var chunksToRequest = [];-function isNum(v) {- return typeof v == 'number';-}+ for (var i = 0; i < ranges.length; i++) {+ var beginChunk = this.getBeginChunk(ranges[i].begin);+ var endChunk = this.getEndChunk(ranges[i].end);+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {+ if (chunksToRequest.indexOf(chunk) < 0) {+ chunksToRequest.push(chunk);+ }+ }+ }-function isString(v) {- return typeof v == 'string';-}+ chunksToRequest.sort(function(a, b) { return a - b; });+ this.requestChunks(chunksToRequest, callback);+ },-function isNull(v) {- return v === null;-}+ // Groups a sorted array of chunks into as few continguous larger+ // chunks as possible+ groupChunks: function ChunkedStreamManager_groupChunks(chunks) {+ var groupedChunks = [];+ var beginChunk;+ var prevChunk;+ for (var i = 0; i < chunks.length; ++i) {+ var chunk = chunks[i];-function isName(v) {- return v instanceof Name;-}+ if (!beginChunk) {+ beginChunk = chunk;+ }-function isCmd(v, cmd) {- return v instanceof Cmd && (!cmd || v.cmd == cmd);-}+ if (prevChunk && prevChunk + 1 !== chunk) {+ groupedChunks.push({+ beginChunk: beginChunk, endChunk: prevChunk + 1});+ beginChunk = chunk;+ }+ if (i + 1 === chunks.length) {+ groupedChunks.push({+ beginChunk: beginChunk, endChunk: chunk + 1});+ }-function isDict(v, type) {- if (!(v instanceof Dict)) {- return false;- }- if (!type) {- return true;- }- var dictType = v.get('Type');- return isName(dictType) && dictType.name == type;-}+ prevChunk = chunk;+ }+ return groupedChunks;+ },-function isArray(v) {- return v instanceof Array;-}+ onProgress: function ChunkedStreamManager_onProgress(args) {+ var bytesLoaded = this.stream.numChunksLoaded * this.chunkSize ++ args.loaded;+ this.msgHandler.send('DocProgress', {+ loaded: bytesLoaded,+ total: this.length+ });+ },-function isStream(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('getBytes' in v);-}+ onReceiveData: function ChunkedStreamManager_onReceiveData(args) {+ var chunk = args.chunk;+ var begin = args.begin;+ var end = begin + chunk.byteLength;-function isArrayBuffer(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('byteLength' in v);-}+ var beginChunk = this.getBeginChunk(begin);+ var endChunk = this.getEndChunk(end);-function isRef(v) {- return v instanceof Ref;-}+ this.stream.onReceiveData(begin, chunk);+ if (this.stream.allChunksLoaded()) {+ this.loadedStream.resolve(this.stream);+ }-function isPDFFunction(v) {- var fnDict;- if (typeof v != 'object') {- return false;- } else if (isDict(v)) {- fnDict = v;- } else if (isStream(v)) {- fnDict = v.dict;- } else {- return false;- }- return fnDict.has('FunctionType');-}+ var loadedRequests = [];+ for (var chunk = beginChunk; chunk < endChunk; ++chunk) {-/**- * Legacy support for PDFJS Promise implementation.- * TODO remove eventually- * @ignore- */-var LegacyPromise = PDFJS.LegacyPromise = (function LegacyPromiseClosure() {- return function LegacyPromise() {- var resolve, reject;- var promise = new Promise(function (resolve_, reject_) {- resolve = resolve_;- reject = reject_;- });- promise.resolve = resolve;- promise.reject = reject;- return promise;- };-})();+ // The server might return more chunks than requested+ var requestIds = this.requestsByChunk[chunk] || [];+ delete this.requestsByChunk[chunk];-/**- * Polyfill for Promises:- * The following promise implementation tries to generally implment the- * Promise/A+ spec. Some notable differences from other promise libaries are:- * - There currently isn't a seperate deferred and promise object.- * - Unhandled rejections eventually show an error if they aren't handled.- *- * Based off of the work in:- * https://bugzilla.mozilla.org/show_bug.cgi?id=810490- */-(function PromiseClosure() {- if (globalScope.Promise) {- // Promises existing in the DOM/Worker, checking presence of all/resolve- if (typeof globalScope.Promise.all !== 'function') {- globalScope.Promise.all = function (iterable) {- var count = 0, results = [], resolve, reject;- var promise = new globalScope.Promise(function (resolve_, reject_) {- resolve = resolve_;- reject = reject_;- });- iterable.forEach(function (p, i) {- count++;- p.then(function (result) {- results[i] = result;- count--;- if (count === 0) {- resolve(results);- }- }, reject);- });- if (count === 0) {- resolve(results);+ for (var i = 0; i < requestIds.length; ++i) {+ var requestId = requestIds[i];+ var chunksNeeded = this.chunksNeededByRequest[requestId];+ if (chunk in chunksNeeded) {+ delete chunksNeeded[chunk];+ }++ if (!isEmptyObj(chunksNeeded)) {+ continue;+ }++ loadedRequests.push(requestId);}- return promise;- };- }- if (typeof globalScope.Promise.resolve !== 'function') {- globalScope.Promise.resolve = function (x) {- return new globalScope.Promise(function (resolve) { resolve(x); });- };- }- return;- }- var STATUS_PENDING = 0;- var STATUS_RESOLVED = 1;- var STATUS_REJECTED = 2;-- // In an attempt to avoid silent exceptions, unhandled rejections are- // tracked and if they aren't handled in a certain amount of time an- // error is logged.- var REJECTION_TIMEOUT = 500;+ }- var HandlerManager = {- handlers: [],- running: false,- unhandledRejections: [],- pendingRejectionCheck: false,+ // If there are no pending requests, automatically fetch the next+ // unfetched chunk of the PDF+ if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {+ var nextEmptyChunk;+ if (this.stream.numChunksLoaded === 1) {+ // This is a special optimization so that after fetching the first+ // chunk, rather than fetching the second chunk, we fetch the last+ // chunk.+ var lastChunk = this.stream.numChunks - 1;+ if (!this.stream.hasChunk(lastChunk)) {+ nextEmptyChunk = lastChunk;+ }+ } else {+ nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);+ }+ if (isInt(nextEmptyChunk)) {+ this.requestChunks([nextEmptyChunk]);+ }+ }- scheduleHandlers: function scheduleHandlers(promise) {- if (promise._status == STATUS_PENDING) {- return;+ for (var i = 0; i < loadedRequests.length; ++i) {+ var requestId = loadedRequests[i];+ var callback = this.callbacksByRequest[requestId];+ delete this.callbacksByRequest[requestId];+ if (callback) {+ callback();+ }}- this.handlers = this.handlers.concat(promise._handlers);- promise._handlers = [];+ this.msgHandler.send('DocProgress', {+ loaded: this.stream.numChunksLoaded * this.chunkSize,+ total: this.length+ });+ },- if (this.running) {- return;+ getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {+ var chunk = Math.floor(begin / this.chunkSize);+ return chunk;+ },++ getEndChunk: function ChunkedStreamManager_getEndChunk(end) {+ if (end % this.chunkSize === 0) {+ return end / this.chunkSize;}- this.running = true;- setTimeout(this.runHandlers.bind(this), 0);- },+ // 0 -> 0+ // 1 -> 1+ // 99 -> 1+ // 100 -> 1+ // 101 -> 2+ var chunk = Math.floor((end - 1) / this.chunkSize) + 1;+ return chunk;+ }+ };- runHandlers: function runHandlers() {- var RUN_TIMEOUT = 1; // ms- var timeoutAt = Date.now() + RUN_TIMEOUT;- while (this.handlers.length > 0) {- var handler = this.handlers.shift();+ return ChunkedStreamManager;+})();- var nextStatus = handler.thisPromise._status;- var nextValue = handler.thisPromise._value;- try {- if (nextStatus === STATUS_RESOLVED) {- if (typeof(handler.onResolve) == 'function') {- nextValue = handler.onResolve(nextValue);- }- } else if (typeof(handler.onReject) === 'function') {- nextValue = handler.onReject(nextValue);- nextStatus = STATUS_RESOLVED;- if (handler.thisPromise._unhandledRejection) {- this.removeUnhandeledRejection(handler.thisPromise);- }- }- } catch (ex) {- nextStatus = STATUS_REJECTED;- nextValue = ex;- }+// TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available+var BasePdfManager = (function BasePdfManagerClosure() {+ function BasePdfManager() {+ throw new Error('Cannot initialize BaseManagerManager');+ }- handler.nextPromise._updateStatus(nextStatus, nextValue);- if (Date.now() >= timeoutAt) {- break;- }- }+ BasePdfManager.prototype = {+ onLoadedStream: function BasePdfManager_onLoadedStream() {+ throw new NotImplementedException();+ },- if (this.handlers.length > 0) {- setTimeout(this.runHandlers.bind(this), 0);- return;- }+ ensureModel: function BasePdfManager_ensureModel(prop, args) {+ return this.ensure(this.pdfModel, prop, args);+ },- this.running = false;+ ensureXRef: function BasePdfManager_ensureXRef(prop, args) {+ return this.ensure(this.pdfModel.xref, prop, args);},- addUnhandledRejection: function addUnhandledRejection(promise) {- this.unhandledRejections.push({- promise: promise,- time: Date.now()- });- this.scheduleRejectionCheck();+ ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {+ return this.ensure(this.pdfModel.catalog, prop, args);},- removeUnhandeledRejection: function removeUnhandeledRejection(promise) {- promise._unhandledRejection = false;- for (var i = 0; i < this.unhandledRejections.length; i++) {- if (this.unhandledRejections[i].promise === promise) {- this.unhandledRejections.splice(i);- i--;- }- }+ getPage: function BasePdfManager_pagePage(pageIndex) {+ return this.pdfModel.getPage(pageIndex);},- scheduleRejectionCheck: function scheduleRejectionCheck() {- if (this.pendingRejectionCheck) {- return;+ ensure: function BasePdfManager_ensure(obj, prop, args) {+ return new NotImplementedException();+ },++ requestRange: function BasePdfManager_ensure(begin, end) {+ return new NotImplementedException();+ },++ requestLoadedStream: function BasePdfManager_requestLoadedStream() {+ return new NotImplementedException();+ },++ updatePassword: function BasePdfManager_updatePassword(password) {+ this.pdfModel.xref.password = this.password = password;+ if (this.passwordChangedPromise) {+ this.passwordChangedPromise.resolve();}- this.pendingRejectionCheck = true;- setTimeout(function rejectionCheck() {- this.pendingRejectionCheck = false;- var now = Date.now();- for (var i = 0; i < this.unhandledRejections.length; i++) {- if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {- var unhandled = this.unhandledRejections[i].promise._value;- var msg = 'Unhandled rejection: ' + unhandled;- if (unhandled.stack) {- msg += '\n' + unhandled.stack;- }- warn(msg);- this.unhandledRejections.splice(i);- i--;- }- }- if (this.unhandledRejections.length) {- this.scheduleRejectionCheck();- }- }.bind(this), REJECTION_TIMEOUT);}};- function Promise(resolver) {- this._status = STATUS_PENDING;- this._handlers = [];- resolver.call(this, this._resolve.bind(this), this._reject.bind(this));+ return BasePdfManager;+})();++var LocalPdfManager = (function LocalPdfManagerClosure() {+ function LocalPdfManager(data, password) {+ var stream = new Stream(data);+ this.pdfModel = new PDFDocument(this, stream, password);+ this.loadedStream = new Promise();+ this.loadedStream.resolve(stream);}- /**- * Builds a promise that is resolved when all the passed in promises are- * resolved.- * @param {array} array of data and/or promises to wait for.- * @return {Promise} New dependant promise.- */- Promise.all = function Promise_all(promises) {- var resolveAll, rejectAll;- var deferred = new Promise(function (resolve, reject) {- resolveAll = resolve;- rejectAll = reject;- });- var unresolved = promises.length;- var results = [];- if (unresolved === 0) {- resolveAll(results);- return deferred;- }- function reject(reason) {- if (deferred._status === STATUS_REJECTED) {- return;- }- results = [];- rejectAll(reason);- }- for (var i = 0, ii = promises.length; i < ii; ++i) {- var promise = promises[i];- var resolve = (function(i) {- return function(value) {- if (deferred._status === STATUS_REJECTED) {- return;- }- results[i] = value;- unresolved--;- if (unresolved === 0) {- resolveAll(results);- }- };- })(i);- if (Promise.isPromise(promise)) {- promise.then(resolve, reject);++ LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);+ LocalPdfManager.prototype.constructor = LocalPdfManager;++ LocalPdfManager.prototype.ensure =+ function LocalPdfManager_ensure(obj, prop, args) {+ var promise = new Promise();+ try {+ var value = obj[prop];+ var result;+ if (typeof(value) === 'function') {+ result = value.apply(obj, args);} else {- resolve(promise);+ result = value;}+ promise.resolve(result);+ } catch (e) {+ console.log(e.stack);+ promise.reject(e);}- return deferred;+ return promise;};- /**- * Checks if the value is likely a promise (has a 'then' function).- * @return {boolean} true if x is thenable- */- Promise.isPromise = function Promise_isPromise(value) {- return value && typeof value.then === 'function';+ LocalPdfManager.prototype.requestRange =+ function LocalPdfManager_requestRange(begin, end) {+ var promise = new Promise();+ promise.resolve();+ return promise;};- /**- * Creates resolved promise- * @param x resolve value- * @returns {Promise}- */- Promise.resolve = function Promise_resolve(x) {- return new Promise(function (resolve) { resolve(x); });++ LocalPdfManager.prototype.requestLoadedStream =+ function LocalPdfManager_requestLoadedStream() {};- Promise.prototype = {- _status: null,- _value: null,- _handlers: null,- _unhandledRejection: null,+ LocalPdfManager.prototype.onLoadedStream =+ function LocalPdfManager_getLoadedStream() {+ return this.loadedStream;+ };- _updateStatus: function Promise__updateStatus(status, value) {- if (this._status === STATUS_RESOLVED ||- this._status === STATUS_REJECTED) {- return;- }+ return LocalPdfManager;+})();- if (status == STATUS_RESOLVED &&- Promise.isPromise(value)) {- value.then(this._updateStatus.bind(this, STATUS_RESOLVED),- this._updateStatus.bind(this, STATUS_REJECTED));- return;- }+var NetworkPdfManager = (function NetworkPdfManagerClosure() {- this._status = status;- this._value = value;+ var CHUNK_SIZE = 65536;- if (status === STATUS_REJECTED && this._handlers.length === 0) {- this._unhandledRejection = true;- HandlerManager.addUnhandledRejection(this);- }+ function NetworkPdfManager(args, msgHandler) {- HandlerManager.scheduleHandlers(this);- },+ this.msgHandler = msgHandler;- _resolve: function Promise_resolve(value) {- this._updateStatus(STATUS_RESOLVED, value);- },+ var params = {+ msgHandler: msgHandler,+ httpHeaders: args.httpHeaders,+ chunkedViewerLoading: args.chunkedViewerLoading,+ disableAutoFetch: args.disableAutoFetch+ };+ this.streamManager = new ChunkedStreamManager(args.length, CHUNK_SIZE,+ args.url, params);- _reject: function Promise_reject(reason) {- this._updateStatus(STATUS_REJECTED, reason);- },+ this.pdfModel = new PDFDocument(this, this.streamManager.getStream(),+ args.password);+ }- then: function Promise_then(onResolve, onReject) {- var nextPromise = new Promise(function (resolve, reject) {- this.resolve = reject;- this.reject = reject;- });- this._handlers.push({- thisPromise: this,- onResolve: onResolve,- onReject: onReject,- nextPromise: nextPromise- });- HandlerManager.scheduleHandlers(this);- return nextPromise;- }- };+ NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);+ NetworkPdfManager.prototype.constructor = NetworkPdfManager;- globalScope.Promise = Promise;-})();+ NetworkPdfManager.prototype.ensure =+ function NetworkPdfManager_ensure(obj, prop, args) {+ var promise = new Promise();+ this.ensureHelper(promise, obj, prop, args);+ return promise;+ };-var StatTimer = (function StatTimerClosure() {- function rpad(str, pad, length) {- while (str.length < length) {- str += pad;- }- return str;- }- function StatTimer() {- this.started = {};- this.times = [];- this.enabled = true;- }- StatTimer.prototype = {- time: function StatTimer_time(name) {- if (!this.enabled) {- return;- }- if (name in this.started) {- warn('Timer is already running for ' + name);+ NetworkPdfManager.prototype.ensureHelper =+ function NetworkPdfManager_ensureHelper(promise, obj, prop, args) {+ try {+ var result;+ var value = obj[prop];+ if (typeof(value) === 'function') {+ result = value.apply(obj, args);+ } else {+ result = value;}- this.started[name] = Date.now();- },- timeEnd: function StatTimer_timeEnd(name) {- if (!this.enabled) {+ promise.resolve(result);+ } catch(e) {+ if (!(e instanceof MissingDataException)) {+ console.log(e.stack);+ promise.reject(e);return;}- if (!(name in this.started)) {- warn('Timer has not been started for ' + name);- }- this.times.push({- 'name': name,- 'start': this.started[name],- 'end': Date.now()- });- // Remove timer from started so it can be called again.- delete this.started[name];- },- toString: function StatTimer_toString() {- var i, ii;- var times = this.times;- var out = '';- // Find the longest name for padding purposes.- var longest = 0;- for (i = 0, ii = times.length; i < ii; ++i) {- var name = times[i]['name'];- if (name.length > longest) {- longest = name.length;- }- }- for (i = 0, ii = times.length; i < ii; ++i) {- var span = times[i];- var duration = span.end - span.start;- out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';- }- return out;++ this.streamManager.requestRange(e.begin, e.end, function() {+ this.ensureHelper(promise, obj, prop, args);+ }.bind(this));}};- return StatTimer;-})();--PDFJS.createBlob = function createBlob(data, contentType) {- if (typeof Blob !== 'undefined') {- return new Blob([data], { type: contentType });- }- // Blob builder is deprecated in FF14 and removed in FF18.- var bb = new MozBlobBuilder();- bb.append(data);- return bb.getBlob(contentType);-};-PDFJS.createObjectURL = (function createObjectURLClosure() {- // Blob/createObjectURL is not available, falling back to data schema.- var digits =- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';+ NetworkPdfManager.prototype.requestRange =+ function NetworkPdfManager_requestRange(begin, end) {+ var promise = new Promise();+ this.streamManager.requestRange(begin, end, function() {+ promise.resolve();+ });+ return promise;+ };- return function createObjectURL(data, contentType) {- if (!PDFJS.disableCreateObjectURL &&- typeof URL !== 'undefined' && URL.createObjectURL) {- var blob = PDFJS.createBlob(data, contentType);- return URL.createObjectURL(blob);- }+ NetworkPdfManager.prototype.requestLoadedStream =+ function NetworkPdfManager_requestLoadedStream() {+ this.streamManager.requestAllChunks();+ };- var buffer = 'data:' + contentType + ';base64,';- for (var i = 0, ii = data.length; i < ii; i += 3) {- var b1 = data[i] & 0xFF;- var b2 = data[i + 1] & 0xFF;- var b3 = data[i + 2] & 0xFF;- var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);- var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;- var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;- buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];- }- return buffer;+ NetworkPdfManager.prototype.onLoadedStream =+ function NetworkPdfManager_getLoadedStream() {+ return this.streamManager.onLoadedStream();};++ return NetworkPdfManager;})();-function MessageHandler(name, comObj) {- this.name = name;- this.comObj = comObj;- this.callbackIndex = 1;- this.postMessageTransfers = true;- var callbacks = this.callbacks = {};- var ah = this.actionHandler = {};- ah['console_log'] = [function ahConsoleLog(data) {- console.log.apply(console, data);- }];- ah['console_error'] = [function ahConsoleError(data) {- console.error.apply(console, data);- }];- ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {- UnsupportedManager.notify(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 {- error('Cannot resolve callback ' + callbackId);- }- } else if (data.action in ah) {- var action = ah[data.action];- if (data.callbackId) {- var deferred = {};- var promise = new Promise(function (resolve, reject) {- deferred.resolve = resolve;- deferred.reject = reject;- });- deferred.promise = promise;- promise.then(function(resolvedData) {- comObj.postMessage({- isReply: true,- callbackId: data.callbackId,- data: resolvedData- });- });- action[0].call(action[1], data.data, deferred);- } else {- action[0].call(action[1], data.data);- }- } else {- error('Unkown action from worker: ' + data.action);- }- };-}+var globalScope = (typeof window === 'undefined') ? this : window;-MessageHandler.prototype = {- on: function messageHandlerOn(actionName, handler, scope) {- var ah = this.actionHandler;- if (ah[actionName]) {- 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.- * @param {Array} [transfers] Optional list of transfers/ArrayBuffers- */- send: function messageHandlerSend(actionName, data, callback, transfers) {- var message = {- action: actionName,- data: data- };- if (callback) {- var callbackId = this.callbackIndex++;- this.callbacks[callbackId] = callback;- message.callbackId = callbackId;- }- if (transfers && this.postMessageTransfers) {- this.comObj.postMessage(message, transfers);- } else {- this.comObj.postMessage(message);- }- }-};+var isWorker = (typeof window == 'undefined');-function loadJpegStream(id, imageUrl, objs) {- var img = new Image();- img.onload = (function loadJpegStream_onloadClosure() {- objs.resolve(id, img);- });- img.src = imageUrl;+var ERRORS = 0, WARNINGS = 1, INFOS = 5;+var verbosity = WARNINGS;++// The global PDFJS object exposes the API+// In production, it will be declared outside a global wrapper+// In development, it will be declared here+if (!globalScope.PDFJS) {+ globalScope.PDFJS = {};}+globalScope.PDFJS.pdfBug = false;-var ColorSpace = (function ColorSpaceClosure() {- // Constructor should define this.numComps, this.defaultColor, this.name- function ColorSpace() {- error('should not call ColorSpace constructor');++var Page = (function PageClosure() {++ function Page(pdfManager, xref, pageIndex, pageDict, ref) {+ this.pdfManager = pdfManager;+ this.pageIndex = pageIndex;+ this.pageDict = pageDict;+ this.xref = xref;+ this.ref = ref;+ this.idCounters = {+ obj: 0+ };+ this.resourcesPromise = null;}- ColorSpace.prototype = {- /**- * Converts the color value to the RGB color. The color components are- * located in the src array starting from the srcOffset. Returns the array- * of the rgb components, each value ranging from [0,255].- */- getRgb: function ColorSpace_getRgb(src, srcOffset) {- var rgb = new Uint8Array(3);- this.getRgbItem(src, srcOffset, rgb, 0);- return rgb;+ Page.prototype = {+ getPageProp: function Page_getPageProp(key) {+ return this.pageDict.get(key);},- /**- * Converts the color value to the RGB color, similar to the getRgb method.- * The result placed into the dest array starting from the destOffset.- */- getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,- dest, destOffset) {- error('Should not call ColorSpace.getRgbItem');+ inheritPageProp: function Page_inheritPageProp(key) {+ var dict = this.pageDict;+ var obj = dict.get(key);+ while (obj === undefined) {+ dict = dict.get('Parent');+ if (!dict)+ break;+ obj = dict.get(key);+ }+ return obj;},- /**- * Converts the specified number of the color values to the RGB colors.- * The colors are located in the src array starting from the srcOffset.- * The result is placed into the dest array starting from the destOffset.- * The src array items shall be in [0,2^bits) range, the dest array items- * will be in [0,255] range. alpha01 indicates how many alpha components- * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA- * array).- */- getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- error('Should not call ColorSpace.getRgbBuffer');+ get content() {+ return this.getPageProp('Contents');},- /**- * Determines the number of bytes required to store the result of the- * conversion done by the getRgbBuffer method. As in getRgbBuffer,- * |alpha01| is either 0 (RGB output) or 1 (RGBA output).- */- getOutputLength: function ColorSpace_getOutputLength(inputLength,- alpha01) {- error('Should not call ColorSpace.getOutputLength');+ get resources() {+ return shadow(this, 'resources', this.inheritPageProp('Resources'));},- /**- * Returns true if source data will be equal the result/output data.- */- isPassthrough: function ColorSpace_isPassthrough(bits) {- return false;+ get mediaBox() {+ var obj = this.inheritPageProp('MediaBox');+ // Reset invalid media box to letter size.+ if (!isArray(obj) || obj.length !== 4)+ obj = [0, 0, 612, 792];+ return shadow(this, 'mediaBox', obj);},- /**- * Fills in the RGB colors in the destination buffer. alpha01 indicates- * how many alpha components there are in the dest array; it will be either- * 0 (RGB array) or 1 (RGBA array).- */- fillRgb: function ColorSpace_fillRgb(dest, originalWidth,- originalHeight, width, height,- actualHeight, bpc, comps, alpha01) {- var count = originalWidth * originalHeight;- var rgbBuf = null;- var numComponentColors = 1 << bpc;- var needsResizing = originalHeight != height || originalWidth != width;- var i, ii;-- if (this.isPassthrough(bpc)) {- rgbBuf = comps;- } else if (this.numComps === 1 && count > numComponentColors &&- this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {- // Optimization: create a color map when there is just one component and- // we are converting more colors than the size of the color map. We- // don't build the map if the colorspace is gray or rgb since those- // methods are faster than building a map. This mainly offers big speed- // ups for indexed and alternate colorspaces.- //- // TODO it may be worth while to cache the color map. While running- // testing I never hit a cache so I will leave that out for now (perhaps- // we are reparsing colorspaces too much?).- var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :- new Uint16Array(numComponentColors);- var key;- for (i = 0; i < numComponentColors; i++) {- allColors[i] = i;- }- var colorMap = new Uint8Array(numComponentColors * 3);- this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,- /* alpha01 = */ 0);-- var destPos, rgbPos;- if (!needsResizing) {- // Fill in the RGB values directly into |dest|.- destPos = 0;- for (i = 0; i < count; ++i) {- key = comps[i] * 3;- dest[destPos++] = colorMap[key];- dest[destPos++] = colorMap[key + 1];- dest[destPos++] = colorMap[key + 2];- destPos += alpha01;- }- } else {- rgbBuf = new Uint8Array(count * 3);- rgbPos = 0;- for (i = 0; i < count; ++i) {- key = comps[i] * 3;- rgbBuf[rgbPos++] = colorMap[key];- rgbBuf[rgbPos++] = colorMap[key + 1];- rgbBuf[rgbPos++] = colorMap[key + 2];- }- }+ get view() {+ var mediaBox = this.mediaBox;+ var cropBox = this.inheritPageProp('CropBox');+ if (!isArray(cropBox) || cropBox.length !== 4)+ return shadow(this, 'view', mediaBox);++ // From the spec, 6th ed., p.963:+ // "The crop, bleed, trim, and art boxes should not ordinarily+ // extend beyond the boundaries of the media box. If they do, they are+ // effectively reduced to their intersection with the media box."+ cropBox = Util.intersect(cropBox, mediaBox);+ if (!cropBox)+ return shadow(this, 'view', mediaBox);++ return shadow(this, 'view', cropBox);+ },+ get annotationRefs() {+ return shadow(this, 'annotationRefs', this.inheritPageProp('Annots'));+ },+ get rotate() {+ var rotate = this.inheritPageProp('Rotate') || 0;+ // Normalize rotation so it's a multiple of 90 and between 0 and 270+ if (rotate % 90 !== 0) {+ rotate = 0;+ } else if (rotate >= 360) {+ rotate = rotate % 360;+ } else if (rotate < 0) {+ // The spec doesn't cover negatives, assume its counterclockwise+ // rotation. The following is the other implementation of modulo.+ rotate = ((rotate % 360) + 360) % 360;+ }+ return shadow(this, 'rotate', rotate);+ },+ getContentStream: function Page_getContentStream() {+ var content = this.content;+ var stream;+ if (isArray(content)) {+ // fetching items+ var xref = this.xref;+ var i, n = content.length;+ var streams = [];+ for (i = 0; i < n; ++i)+ streams.push(xref.fetchIfRef(content[i]));+ stream = new StreamsSequenceStream(streams);+ } else if (isStream(content)) {+ stream = content;} else {- if (!needsResizing) {- // Fill in the RGB values directly into |dest|.- this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,- alpha01);- } else {- rgbBuf = new Uint8Array(count * 3);- this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,- /* alpha01 = */ 0);- }+ // replacing non-existent page content with empty one+ stream = new NullStream();}-- if (rgbBuf) {- if (needsResizing) {- rgbBuf = PDFImage.resize(rgbBuf, bpc, 3, originalWidth,- originalHeight, width, height);- }- rgbPos = 0;- destPos = 0;- for (i = 0, ii = width * actualHeight; i < ii; i++) {- dest[destPos++] = rgbBuf[rgbPos++];- dest[destPos++] = rgbBuf[rgbPos++];- dest[destPos++] = rgbBuf[rgbPos++];- destPos += alpha01;- }+ return stream;+ },+ loadResources: function(keys) {+ if (!this.resourcesPromise) {+ // TODO: add async inheritPageProp and remove this.+ this.resourcesPromise = this.pdfManager.ensure(this, 'resources');}+ var promise = new Promise();+ this.resourcesPromise.then(function resourceSuccess() {+ var objectLoader = new ObjectLoader(this.resources.map,+ keys,+ this.xref);+ objectLoader.load().then(function objectLoaderSuccess() {+ promise.resolve();+ });+ }.bind(this));+ return promise;},- /**- * True if the colorspace has components in the default range of [0, 1].- * This should be true for all colorspaces except for lab color spaces- * which are [0,100], [-128, 127], [-128, 127].- */- usesZeroToOneRange: true- };+ getOperatorList: function Page_getOperatorList(handler) {+ var self = this;+ var promise = new Promise();- ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {- var IR = ColorSpace.parseToIR(cs, xref, res);- if (IR instanceof AlternateCS) {- return IR;- }- return ColorSpace.fromIR(IR);- };+ function reject(e) {+ promise.reject(e);+ }- ColorSpace.fromIR = function ColorSpace_fromIR(IR) {- var name = isArray(IR) ? IR[0] : IR;- var whitePoint, blackPoint;+ var pageListPromise = new Promise();- switch (name) {- case 'DeviceGrayCS':- return this.singletons.gray;- case 'DeviceRgbCS':- return this.singletons.rgb;- case 'DeviceCmykCS':- return this.singletons.cmyk;- case 'CalGrayCS':- whitePoint = IR[1].WhitePoint;- blackPoint = IR[1].BlackPoint;- var gamma = IR[1].Gamma;- return new CalGrayCS(whitePoint, blackPoint, gamma);- case 'PatternCS':- var basePatternCS = IR[1];- if (basePatternCS) {- basePatternCS = ColorSpace.fromIR(basePatternCS);- }- return new PatternCS(basePatternCS);- case 'IndexedCS':- var baseIndexedCS = IR[1];- var hiVal = IR[2];- var lookup = IR[3];- return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);- case 'AlternateCS':- var numComps = IR[1];- var alt = IR[2];- var tintFnIR = IR[3];+ var pdfManager = this.pdfManager;+ var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',+ []);+ var resourcesPromise = this.loadResources([+ 'ExtGState',+ 'ColorSpace',+ 'Pattern',+ 'Shading',+ 'XObject',+ 'Font',+ // ProcSet+ // Properties+ ]);- return new AlternateCS(numComps, ColorSpace.fromIR(alt),- PDFFunction.fromIR(tintFnIR));- case 'LabCS':- whitePoint = IR[1].WhitePoint;- blackPoint = IR[1].BlackPoint;- var range = IR[1].Range;- return new LabCS(whitePoint, blackPoint, range);- default:- error('Unkown name ' + name);- }- return null;- };+ var partialEvaluator = new PartialEvaluator(+ pdfManager, this.xref, handler,+ this.pageIndex, 'p' + this.pageIndex + '_',+ this.idCounters);- ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {- if (isName(cs)) {- var colorSpaces = res.get('ColorSpace');- if (isDict(colorSpaces)) {- var refcs = colorSpaces.get(cs.name);- if (refcs) {- cs = refcs;+ var dataPromises = Promise.all(+ [contentStreamPromise, resourcesPromise], reject);+ dataPromises.then(function(data) {+ var contentStream = data[0];++ partialEvaluator.getOperatorList(contentStream, self.resources).then(+ function(data) {+ pageListPromise.resolve(data);+ },+ reject+ );+ });++ var annotationsPromise = pdfManager.ensure(this, 'annotations');+ Promise.all([pageListPromise, annotationsPromise]).then(function(datas) {+ var pageData = datas[0];+ var pageQueue = pageData.queue;+ var annotations = datas[1];++ if (annotations.length === 0) {+ PartialEvaluator.optimizeQueue(pageQueue);+ promise.resolve(pageData);+ return;}- }- }- cs = xref.fetchIfRef(cs);- var mode;+ var dependencies = pageData.dependencies;+ var annotationsReadyPromise = Annotation.appendToOperatorList(+ annotations, pageQueue, pdfManager, dependencies, partialEvaluator);+ annotationsReadyPromise.then(function () {+ PartialEvaluator.optimizeQueue(pageQueue);- if (isName(cs)) {- mode = cs.name;- this.mode = mode;+ promise.resolve(pageData);+ }, reject);+ }, reject);- switch (mode) {- case 'DeviceGray':- case 'G':- return 'DeviceGrayCS';- case 'DeviceRGB':- case 'RGB':- return 'DeviceRgbCS';- case 'DeviceCMYK':- case 'CMYK':- return 'DeviceCmykCS';- case 'Pattern':- return ['PatternCS', null];- default:- error('unrecognized colorspace ' + mode);- }- } else if (isArray(cs)) {- mode = cs[0].name;- this.mode = mode;- var numComps, params;+ return promise;+ },+ extractTextContent: function Page_extractTextContent() {+ var handler = {+ on: function nullHandlerOn() {},+ send: function nullHandlerSend() {}+ };- switch (mode) {- case 'DeviceGray':- case 'G':- return 'DeviceGrayCS';- case 'DeviceRGB':- case 'RGB':- return 'DeviceRgbCS';- case 'DeviceCMYK':- case 'CMYK':- return 'DeviceCmykCS';- case 'CalGray':- params = cs[1].getAll();- return ['CalGrayCS', params];- case 'CalRGB':- return 'DeviceRgbCS';- case 'ICCBased':- var stream = xref.fetchIfRef(cs[1]);- var dict = stream.dict;- numComps = dict.get('N');- if (numComps == 1) {- return 'DeviceGrayCS';- } else if (numComps == 3) {- return 'DeviceRgbCS';- } else if (numComps == 4) {- return 'DeviceCmykCS';- }- break;- case 'Pattern':- var basePatternCS = cs[1];- if (basePatternCS) {- basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);- }- return ['PatternCS', basePatternCS];- case 'Indexed':- case 'I':- var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);- var hiVal = cs[2] + 1;- var lookup = xref.fetchIfRef(cs[3]);- if (isStream(lookup)) {- lookup = lookup.getBytes();- }- return ['IndexedCS', baseIndexedCS, hiVal, lookup];- case 'Separation':- case 'DeviceN':- var name = cs[1];- numComps = 1;- if (isName(name)) {- numComps = 1;- } else if (isArray(name)) {- numComps = name.length;- }- var alt = ColorSpace.parseToIR(cs[2], xref, res);- var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));- return ['AlternateCS', numComps, alt, tintFnIR];- case 'Lab':- params = cs[1].getAll();- return ['LabCS', params];- default:- error('unimplemented color space object "' + mode + '"');- }- } else {- error('unrecognized color space object: "' + cs + '"');- }- return null;- };- /**- * Checks if a decode map matches the default decode map for a color space.- * This handles the general decode maps where there are two values per- * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.- * This does not handle Lab, Indexed, or Pattern decode maps since they are- * slightly different.- * @param {Array} decode Decode map (usually from an image).- * @param {Number} n Number of components the color space has.- */- ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {- if (!decode) {- return true;- }+ var self = this;- if (n * 2 !== decode.length) {- warn('The decode map is not the correct length');- return true;- }- for (var i = 0, ii = decode.length; i < ii; i += 2) {- if (decode[i] !== 0 || decode[i + 1] != 1) {- return false;- }- }- return true;- };+ var textContentPromise = new Promise();++ var pdfManager = this.pdfManager;+ var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',+ []);++ var resourcesPromise = this.loadResources([+ 'ExtGState',+ 'XObject',+ 'Font'+ ]);++ var dataPromises = Promise.all([contentStreamPromise,+ resourcesPromise]);+ dataPromises.then(function(data) {+ var contentStream = data[0];+ var partialEvaluator = new PartialEvaluator(+ pdfManager, self.xref, handler,+ self.pageIndex, 'p' + self.pageIndex + '_',+ self.idCounters);++ partialEvaluator.getTextContent(+ contentStream, self.resources).then(function(bidiTexts) {+ textContentPromise.resolve({+ bidiTexts: bidiTexts+ });+ });+ });- ColorSpace.singletons = {- get gray() {- return shadow(this, 'gray', new DeviceGrayCS());+ return textContentPromise;},- get rgb() {- return shadow(this, 'rgb', new DeviceRgbCS());++ getAnnotationsData: function Page_getAnnotationsData() {+ var annotations = this.annotations;+ var annotationsData = [];+ for (var i = 0, n = annotations.length; i < n; ++i) {+ annotationsData.push(annotations[i].getData());+ }+ return annotationsData;},- get cmyk() {- return shadow(this, 'cmyk', new DeviceCmykCS());++ get annotations() {+ var annotations = [];+ var annotationRefs = this.annotationRefs || [];+ for (var i = 0, n = annotationRefs.length; i < n; ++i) {+ var annotationRef = annotationRefs[i];+ var annotation = Annotation.fromRef(this.xref, annotationRef);+ if (annotation) {+ annotations.push(annotation);+ }+ }+ return shadow(this, 'annotations', annotations);}};- return ColorSpace;+ return Page;})();/**- * Alternate color space handles both Separation and DeviceN color spaces. A- * Separation color space is actually just a DeviceN with one color component.- * Both color spaces use a tinting function to convert colors to a base color- * space.+ * The `PDFDocument` holds all the data of the PDF file. Compared to the+ * `PDFDoc`, this one doesn't have any job management code.+ * Right now there exists one PDFDocument on the main thread + one object+ * for each worker. If there is no worker support enabled, there are two+ * `PDFDocument` objects on the main thread created.*/-var AlternateCS = (function AlternateCSClosure() {- function AlternateCS(numComps, base, tintFn) {- this.name = 'Alternate';- this.numComps = numComps;- this.defaultColor = new Float32Array(numComps);- for (var i = 0; i < numComps; ++i) {- this.defaultColor[i] = 1;- }- this.base = base;- this.tintFn = tintFn;+var PDFDocument = (function PDFDocumentClosure() {+ function PDFDocument(pdfManager, arg, password) {+ if (isStream(arg))+ init.call(this, pdfManager, arg, password);+ else if (isArrayBuffer(arg))+ init.call(this, pdfManager, new Stream(arg), password);+ else+ error('PDFDocument: Unknown argument type');}- AlternateCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var baseNumComps = this.base.numComps;- var input = 'subarray' in src ?- src.subarray(srcOffset, srcOffset + this.numComps) :- Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps);- var tinted = this.tintFn(input);- this.base.getRgbItem(tinted, 0, dest, destOffset);+ function init(pdfManager, stream, password) {+ assertWellFormed(stream.length > 0, 'stream must have data');+ this.pdfManager = pdfManager;+ this.stream = stream;+ var xref = new XRef(this.stream, password, pdfManager);+ this.xref = xref;+ }++ function find(stream, needle, limit, backwards) {+ var pos = stream.pos;+ var end = stream.end;+ var str = '';+ if (pos + limit > end)+ limit = end - pos;+ for (var n = 0; n < limit; ++n)+ str += stream.getChar();+ stream.pos = pos;+ var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);+ if (index == -1)+ return false; /* not found */+ stream.pos += index;+ return true; /* found */+ }++ var DocumentInfoValidators = {+ get entries() {+ // Lazily build this since all the validation functions below are not+ // defined until after this file loads.+ return shadow(this, 'entries', {+ Title: isString,+ Author: isString,+ Subject: isString,+ Keywords: isString,+ Creator: isString,+ Producer: isString,+ CreationDate: isString,+ ModDate: isString,+ Trapped: isName+ });+ }+ };++ PDFDocument.prototype = {+ parse: function PDFDocument_parse(recoveryMode) {+ this.setup(recoveryMode);+ this.acroForm = this.catalog.catDict.get('AcroForm');},- getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var tintFn = this.tintFn;- var base = this.base;- var scale = 1 / ((1 << bits) - 1);- var baseNumComps = base.numComps;- var usesZeroToOneRange = base.usesZeroToOneRange;- var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&- alpha01 === 0;- var pos = isPassthrough ? destOffset : 0;- var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);- var numComps = this.numComps;- var scaled = new Float32Array(numComps);- var i, j;- for (i = 0; i < count; i++) {- for (j = 0; j < numComps; j++) {- scaled[j] = src[srcOffset++] * scale;+ get linearization() {+ var length = this.stream.length;+ var linearization = false;+ if (length) {+ try {+ linearization = new Linearization(this.stream);+ if (linearization.length != length) {+ linearization = false;+ }+ } catch (err) {+ if (err instanceof MissingDataException) {+ throw err;+ }++ info('The linearization data is not available ' ++ 'or unreadable PDF data is found');+ linearization = false;}- var tinted = tintFn(scaled);- if (usesZeroToOneRange) {- for (j = 0; j < baseNumComps; j++) {- baseBuf[pos++] = tinted[j] * 255;+ }+ // shadow the prototype getter with a data property+ return shadow(this, 'linearization', linearization);+ },+ get startXRef() {+ var stream = this.stream;+ var startXRef = 0;+ var linearization = this.linearization;+ if (linearization) {+ // Find end of first obj.+ stream.reset();+ if (find(stream, 'endobj', 1024))+ startXRef = stream.pos + 6;+ } else {+ // Find startxref by jumping backward from the end of the file.+ var step = 1024;+ var found = false, pos = stream.end;+ while (!found && pos > 0) {+ pos -= step - 'startxref'.length;+ if (pos < 0)+ pos = 0;+ stream.pos = pos;+ found = find(stream, 'startxref', step, true);+ }+ if (found) {+ stream.skip(9);+ var ch;+ do {+ ch = stream.getChar();+ } while (Lexer.isSpace(ch));+ var str = '';+ while ((ch - '0') <= 9) {+ str += ch;+ ch = stream.getChar();}- } else {- base.getRgbItem(tinted, 0, baseBuf, pos);- pos += baseNumComps;+ startXRef = parseInt(str, 10);+ if (isNaN(startXRef))+ startXRef = 0;}}- if (!isPassthrough) {- base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);+ // shadow the prototype getter with a data property+ return shadow(this, 'startXRef', startXRef);+ },+ get mainXRefEntriesOffset() {+ var mainXRefEntriesOffset = 0;+ var linearization = this.linearization;+ if (linearization)+ mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;+ // shadow the prototype getter with a data property+ return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);+ },+ // Find the header, remove leading garbage and setup the stream+ // starting from the header.+ checkHeader: function PDFDocument_checkHeader() {+ var stream = this.stream;+ stream.reset();+ if (find(stream, '%PDF-', 1024)) {+ // Found the header, trim off any garbage before it.+ stream.moveStart();+ // Reading file format version+ var MAX_VERSION_LENGTH = 12;+ var version = '', ch;+ while ((ch = stream.getChar()) > ' ') {+ if (version.length >= MAX_VERSION_LENGTH) {+ break;+ }+ version += ch;+ }+ // removing "%PDF-"-prefix+ this.pdfFormatVersion = version.substring(5);+ return;}+ // May not be a PDF file, continue anyway.},- getOutputLength: function AlternateCS_getOutputLength(inputLength,- alpha01) {- return this.base.getOutputLength(inputLength *- this.base.numComps / this.numComps,- alpha01);+ parseStartXRef: function PDFDocument_parseStartXRef() {+ var startXRef = this.startXRef;+ this.xref.setStartXRef(startXRef);},- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);+ setup: function PDFDocument_setup(recoveryMode) {+ this.xref.parse(recoveryMode);+ this.catalog = new Catalog(this.pdfManager, this.xref);},- usesZeroToOneRange: true- };-- return AlternateCS;-})();+ get numPages() {+ var linearization = this.linearization;+ var num = linearization ? linearization.numPages : this.catalog.numPages;+ // shadow the prototype getter+ return shadow(this, 'numPages', num);+ },+ get documentInfo() {+ var docInfo = {+ PDFFormatVersion: this.pdfFormatVersion,+ IsAcroFormPresent: !!this.acroForm+ };+ if (this.xref.trailer.has('Info')) {+ var infoDict = this.xref.trailer.get('Info');-var PatternCS = (function PatternCSClosure() {- function PatternCS(baseCS) {- this.name = 'Pattern';- this.base = baseCS;- }- PatternCS.prototype = {};-- return PatternCS;-})();--var IndexedCS = (function IndexedCSClosure() {- function IndexedCS(base, highVal, lookup) {- this.name = 'Indexed';- this.numComps = 1;- this.defaultColor = new Uint8Array([0]);- this.base = base;- this.highVal = highVal;-- var baseNumComps = base.numComps;- var length = baseNumComps * highVal;- var lookupArray;-- if (isStream(lookup)) {- lookupArray = new Uint8Array(length);- var bytes = lookup.getBytes(length);- lookupArray.set(bytes);- } else if (isString(lookup)) {- lookupArray = new Uint8Array(length);- for (var i = 0; i < length; ++i) {- lookupArray[i] = lookup.charCodeAt(i);+ var validEntries = DocumentInfoValidators.entries;+ // Only fill the document info with valid entries from the spec.+ for (var key in validEntries) {+ if (infoDict.has(key)) {+ var value = infoDict.get(key);+ // Make sure the value conforms to the spec.+ if (validEntries[key](value)) {+ docInfo[key] = typeof value !== 'string' ? value :+ stringToPDFString(value);+ } else {+ info('Bad value in document info for "' + key + '"');+ }+ }+ }}- } else if (lookup instanceof Uint8Array || lookup instanceof Array) {- lookupArray = lookup;- } else {- error('Unrecognized lookup table: ' + lookup);- }- this.lookup = lookupArray;- }-- IndexedCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var numComps = this.base.numComps;- var start = src[srcOffset] * numComps;- this.base.getRgbItem(this.lookup, start, dest, destOffset);+ return shadow(this, 'documentInfo', docInfo);},- getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var base = this.base;- var numComps = base.numComps;- var outputDelta = base.getOutputLength(numComps, alpha01);- var lookup = this.lookup;-- for (var i = 0; i < count; ++i) {- var lookupPos = src[srcOffset++] * numComps;- base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);- destOffset += outputDelta;+ get fingerprint() {+ var xref = this.xref, fileID;+ if (xref.trailer.has('ID')) {+ fileID = '';+ var id = xref.trailer.get('ID')[0];+ id.split('').forEach(function(el) {+ fileID += Number(el.charCodeAt(0)).toString(16);+ });+ } else {+ // If we got no fileID, then we generate one,+ // from the first 100 bytes of PDF+ var data = this.stream.bytes.subarray(0, 100);+ var hash = calculateMD5(data, 0, data.length);+ fileID = '';+ for (var i = 0, length = hash.length; i < length; i++) {+ fileID += Number(hash[i]).toString(16);+ }}++ return shadow(this, 'fingerprint', fileID);},- getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {- return this.base.getOutputLength(inputLength * this.base.numComps,- alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {- // indexed color maps shouldn't be changed- return true;++ traversePages: function PDFDocument_traversePages() {+ this.catalog.traversePages();},- usesZeroToOneRange: true++ getPage: function PDFDocument_getPage(pageIndex) {+ return this.catalog.getPage(pageIndex);+ }};- return IndexedCS;++ return PDFDocument;})();-var DeviceGrayCS = (function DeviceGrayCSClosure() {- function DeviceGrayCS() {- this.name = 'DeviceGray';- this.numComps = 1;- this.defaultColor = new Float32Array([0]);- }- DeviceGrayCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var c = (src[srcOffset] * 255) | 0;- c = c < 0 ? 0 : c > 255 ? 255 : c;- dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;- },- getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 255 / ((1 << bits) - 1);- var j = srcOffset, q = destOffset;- for (var i = 0; i < count; ++i) {- var c = (scale * src[j++]) | 0;- dest[q++] = c;- dest[q++] = c;- dest[q++] = c;- q += alpha01;- }- },- getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,- alpha01) {- return inputLength * (3 + alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return DeviceGrayCS;-})();-var DeviceRgbCS = (function DeviceRgbCSClosure() {- function DeviceRgbCS() {- this.name = 'DeviceRGB';- this.numComps = 3;- this.defaultColor = new Float32Array([0, 0, 0]);+// Use only for debugging purposes. This should not be used in any code that is+// in mozilla master.+var log = (function() {+ if ('console' in globalScope && 'log' in globalScope['console']) {+ return globalScope['console']['log'].bind(globalScope['console']);+ } else {+ return function nop() {+ };}- DeviceRgbCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var r = (src[srcOffset] * 255) | 0;- var g = (src[srcOffset + 1] * 255) | 0;- var b = (src[srcOffset + 2] * 255) | 0;- dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;- dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;- dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;- },- getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- if (bits === 8 && alpha01 === 0) {- dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);- return;- }- var scale = 255 / ((1 << bits) - 1);- var j = srcOffset, q = destOffset;- for (var i = 0; i < count; ++i) {- dest[q++] = (scale * src[j++]) | 0;- dest[q++] = (scale * src[j++]) | 0;- dest[q++] = (scale * src[j++]) | 0;- q += alpha01;- }- },- getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,- alpha01) {- return (inputLength * (3 + alpha01) / 3) | 0;- },- isPassthrough: function DeviceRgbCS_isPassthrough(bits) {- return bits == 8;- },- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return DeviceRgbCS;})();-var DeviceCmykCS = (function DeviceCmykCSClosure() {- // The coefficients below was found using numerical analysis: the method of- // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,- // where color_value is the tabular value from the table of sampled RGB colors- // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding- // CMYK color conversion using the estimation below:- // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255- function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {- var c = src[srcOffset + 0] * srcScale;- var m = src[srcOffset + 1] * srcScale;- var y = src[srcOffset + 2] * srcScale;- var k = src[srcOffset + 3] * srcScale;+// A notice for devs that will not trigger the fallback UI. These are good+// for things that are helpful to devs, such as warning that Workers were+// disabled, which is important to devs but not end users.+function info(msg) {+ if (verbosity >= INFOS) {+ log('Info: ' + msg);+ PDFJS.LogManager.notify('info', msg);+ }+}- var r =- c * (-4.387332384609988 * c + 54.48615194189176 * m +- 18.82290502165302 * y + 212.25662451639585 * k +- -285.2331026137004) +- m * (1.7149763477362134 * m - 5.6096736904047315 * y +- -17.873870861415444 * k - 5.497006427196366) +- y * (-2.5217340131683033 * y - 21.248923337353073 * k +- 17.5119270841813) +- k * (-21.86122147463605 * k - 189.48180835922747) + 255;- var g =- c * (8.841041422036149 * c + 60.118027045597366 * m +- 6.871425592049007 * y + 31.159100130055922 * k +- -79.2970844816548) +- m * (-15.310361306967817 * m + 17.575251261109482 * y +- 131.35250912493976 * k - 190.9453302588951) +- y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +- k * (-20.737325471181034 * k - 187.80453709719578) + 255;- var b =- c * (0.8842522430003296 * c + 8.078677503112928 * m +- 30.89978309703729 * y - 0.23883238689178934 * k +- -14.183576799673286) +- m * (10.49593273432072 * m + 63.02378494754052 * y +- 50.606957656360734 * k - 112.23884253719248) +- y * (0.03296041114873217 * y + 115.60384449646641 * k +- -193.58209356861505) +- k * (-22.33816807309886 * k - 180.12613974708367) + 255;+// Non-fatal warnings that should trigger the fallback UI.+function warn(msg) {+ if (verbosity >= WARNINGS) {+ log('Warning: ' + msg);+ PDFJS.LogManager.notify('warn', msg);+ }+}- dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;- dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;- dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;+// Fatal errors that should trigger the fallback UI and halt execution by+// throwing an exception.+function error(msg) {+ // If multiple arguments were passed, pass them all to the log function.+ if (arguments.length > 1) {+ var logArguments = ['Error:'];+ logArguments.push.apply(logArguments, arguments);+ log.apply(null, logArguments);+ // Join the arguments into a single string for the lines below.+ msg = [].join.call(arguments, ' ');+ } else {+ log('Error: ' + msg);}+ log(backtrace());+ PDFJS.LogManager.notify('error', msg);+ throw new Error(msg);+}- function DeviceCmykCS() {- this.name = 'DeviceCMYK';- this.numComps = 4;- this.defaultColor = new Float32Array([0, 0, 0, 1]);+// Missing features that should trigger the fallback UI.+function TODO(what) {+ warn('TODO: ' + what);+}++function backtrace() {+ try {+ throw new Error();+ } catch (e) {+ return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';}- DeviceCmykCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,- dest, destOffset) {- convertToRgb(src, srcOffset, 1, dest, destOffset);+}++function assert(cond, msg) {+ if (!cond)+ error(msg);+}++// Combines two URLs. The baseUrl shall be absolute URL. If the url is an+// absolute URL, it will be returned as is.+function combineUrl(baseUrl, url) {+ if (!url)+ return baseUrl;+ if (url.indexOf(':') >= 0)+ return url;+ if (url.charAt(0) == '/') {+ // absolute path+ var i = baseUrl.indexOf('://');+ i = baseUrl.indexOf('/', i + 3);+ return baseUrl.substring(0, i) + url;+ } else {+ // relative path+ var pathLength = baseUrl.length, i;+ i = baseUrl.lastIndexOf('#');+ pathLength = i >= 0 ? i : pathLength;+ i = baseUrl.lastIndexOf('?', pathLength);+ pathLength = i >= 0 ? i : pathLength;+ var prefixLength = baseUrl.lastIndexOf('/', pathLength);+ return baseUrl.substring(0, prefixLength + 1) + url;+ }+}++// In a well-formed PDF, |cond| holds. If it doesn't, subsequent+// behavior is undefined.+function assertWellFormed(cond, msg) {+ if (!cond)+ error(msg);+}++var LogManager = PDFJS.LogManager = (function LogManagerClosure() {+ var loggers = [];+ return {+ addLogger: function logManager_addLogger(logger) {+ loggers.push(logger);},- getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 1 / ((1 << bits) - 1);- for (var i = 0; i < count; i++) {- convertToRgb(src, srcOffset, scale, dest, destOffset);- srcOffset += 4;- destOffset += 3 + alpha01;+ notify: function(type, message) {+ for (var i = 0, ii = loggers.length; i < ii; i++) {+ var logger = loggers[i];+ if (logger[type])+ logger[type](message);}- },- getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,- alpha01) {- return (inputLength / 4 * (3 + alpha01)) | 0;- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true+ }};-- return DeviceCmykCS;})();-//-// CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245-//-var CalGrayCS = (function CalGrayCSClosure() {- function CalGrayCS(whitePoint, blackPoint, gamma) {- this.name = 'CalGray';- this.numComps = 1;- this.defaultColor = new Float32Array([0]);+function shadow(obj, prop, value) {+ Object.defineProperty(obj, prop, { value: value,+ enumerable: true,+ configurable: true,+ writable: false });+ return value;+}- if (!whitePoint) {- error('WhitePoint missing - required for color space CalGray');- }- blackPoint = blackPoint || [0, 0, 0];- gamma = gamma || 1;+var PasswordResponses = PDFJS.PasswordResponses = {+ NEED_PASSWORD: 1,+ INCORRECT_PASSWORD: 2+};- // Translate arguments to spec variables.- this.XW = whitePoint[0];- this.YW = whitePoint[1];- this.ZW = whitePoint[2];+var PasswordException = (function PasswordExceptionClosure() {+ function PasswordException(msg, code) {+ this.name = 'PasswordException';+ this.message = msg;+ this.code = code;+ }- this.XB = blackPoint[0];- this.YB = blackPoint[1];- this.ZB = blackPoint[2];+ PasswordException.prototype = new Error();+ PasswordException.constructor = PasswordException;- this.G = gamma;+ return PasswordException;+})();- // Validate variables as per spec.- if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {- error('Invalid WhitePoint components for ' + this.name +- ', no fallback available');- }+var UnknownErrorException = (function UnknownErrorExceptionClosure() {+ function UnknownErrorException(msg, details) {+ this.name = 'UnknownErrorException';+ this.message = msg;+ this.details = details;+ }- if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {- info('Invalid BlackPoint for ' + this.name + ', falling back to default');- this.XB = this.YB = this.ZB = 0;- }+ UnknownErrorException.prototype = new Error();+ UnknownErrorException.constructor = UnknownErrorException;- if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {- warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +- ', ZB: ' + this.ZB + ', only default values are supported.');- }+ return UnknownErrorException;+})();- if (this.G < 1) {- info('Invalid Gamma: ' + this.G + ' for ' + this.name +- ', falling back to default');- this.G = 1;- }+var InvalidPDFException = (function InvalidPDFExceptionClosure() {+ function InvalidPDFException(msg) {+ this.name = 'InvalidPDFException';+ this.message = msg;}- function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {- // A represents a gray component of a calibrated gray space.- // A <---> AG in the spec- var A = src[srcOffset] * scale;- var AG = Math.pow(A, cs.G);-- // Computes intermediate variables M, L, N as per spec.- // Except if other than default BlackPoint values are used.- var M = cs.XW * AG;- var L = cs.YW * AG;- var N = cs.ZW * AG;-- // Decode XYZ, as per spec.- var X = M;- var Y = L;- var Z = N;-- // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.- // This yields values in range [0, 100].- var Lstar = Math.max(116 * Math.pow(Y, 1 / 3) - 16, 0);-- // Convert values to rgb range [0, 255].- dest[destOffset] = Lstar * 255 / 100;- dest[destOffset + 1] = Lstar * 255 / 100;- dest[destOffset + 2] = Lstar * 255 / 100;+ InvalidPDFException.prototype = new Error();+ InvalidPDFException.constructor = InvalidPDFException;++ return InvalidPDFException;+})();++var MissingPDFException = (function MissingPDFExceptionClosure() {+ function MissingPDFException(msg) {+ this.name = 'MissingPDFException';+ this.message = msg;}- CalGrayCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,- dest, destOffset) {- convertToRgb(this, src, srcOffset, dest, destOffset, 1);- },- getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 1 / ((1 << bits) - 1);+ MissingPDFException.prototype = new Error();+ MissingPDFException.constructor = MissingPDFException;- for (var i = 0; i < count; ++i) {- convertToRgb(this, src, srcOffset, dest, destOffset, scale);- srcOffset += 1;- destOffset += 3 + alpha01;- }- },- getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {- return inputLength * (3 + alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return CalGrayCS;+ return MissingPDFException;})();-//-// LabCS: Based on "PDF Reference, Sixth Ed", p.250-//-var LabCS = (function LabCSClosure() {- function LabCS(whitePoint, blackPoint, range) {- this.name = 'Lab';- this.numComps = 3;- this.defaultColor = new Float32Array([0, 0, 0]);+var NotImplementedException = (function NotImplementedExceptionClosure() {+ function NotImplementedException(msg) {+ this.message = msg;+ }- if (!whitePoint) {- error('WhitePoint missing - required for color space Lab');- }- blackPoint = blackPoint || [0, 0, 0];- range = range || [-100, 100, -100, 100];+ NotImplementedException.prototype = new Error();+ NotImplementedException.prototype.name = 'NotImplementedException';+ NotImplementedException.constructor = NotImplementedException;- // Translate args to spec variables- this.XW = whitePoint[0];- this.YW = whitePoint[1];- this.ZW = whitePoint[2];- this.amin = range[0];- this.amax = range[1];- this.bmin = range[2];- this.bmax = range[3];+ return NotImplementedException;+})();- // These are here just for completeness - the spec doesn't offer any- // formulas that use BlackPoint in Lab- this.XB = blackPoint[0];- this.YB = blackPoint[1];- this.ZB = blackPoint[2];+var MissingDataException = (function MissingDataExceptionClosure() {+ function MissingDataException(begin, end) {+ this.begin = begin;+ this.end = end;+ this.message = 'Missing data [begin, end)';+ }- // Validate vars as per spec- if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {- error('Invalid WhitePoint components, no fallback available');- }+ MissingDataException.prototype = new Error();+ MissingDataException.prototype.name = 'MissingDataException';+ MissingDataException.constructor = MissingDataException;- if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {- info('Invalid BlackPoint, falling back to default');- this.XB = this.YB = this.ZB = 0;- }+ return MissingDataException;+})();- if (this.amin > this.amax || this.bmin > this.bmax) {- info('Invalid Range, falling back to defaults');- this.amin = -100;- this.amax = 100;- this.bmin = -100;- this.bmax = 100;- }+var XRefParseException = (function XRefParseExceptionClosure() {+ function XRefParseException(msg) {+ this.message = msg;}- // Function g(x) from spec- function fn_g(x) {- if (x >= 6 / 29) {- return x * x * x;- } else {- return (108 / 841) * (x - 4 / 29);- }- }+ XRefParseException.prototype = new Error();+ XRefParseException.prototype.name = 'XRefParseException';+ XRefParseException.constructor = XRefParseException;- function decode(value, high1, low2, high2) {- return low2 + (value) * (high2 - low2) / (high1);- }+ return XRefParseException;+})();- // If decoding is needed maxVal should be 2^bits per component - 1.- function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {- // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]- // not the usual [0, 1]. If a command like setFillColor is used the src- // values will already be within the correct range. However, if we are- // converting an image we have to map the values to the correct range given- // above.- // Ls,as,bs <---> L*,a*,b* in the spec- var Ls = src[srcOffset];- var as = src[srcOffset + 1];- var bs = src[srcOffset + 2];- if (maxVal !== false) {- Ls = decode(Ls, maxVal, 0, 100);- as = decode(as, maxVal, cs.amin, cs.amax);- bs = decode(bs, maxVal, cs.bmin, cs.bmax);- }- // Adjust limits of 'as' and 'bs'- as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;- bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;+function bytesToString(bytes) {+ var str = '';+ var length = bytes.length;+ for (var n = 0; n < length; ++n)+ str += String.fromCharCode(bytes[n]);+ return str;+}- // Computes intermediate variables X,Y,Z as per spec- var M = (Ls + 16) / 116;- var L = M + (as / 500);- var N = M - (bs / 200);+function stringToBytes(str) {+ var length = str.length;+ var bytes = new Uint8Array(length);+ for (var n = 0; n < length; ++n)+ bytes[n] = str.charCodeAt(n) & 0xFF;+ return bytes;+}- var X = cs.XW * fn_g(L);- var Y = cs.YW * fn_g(M);- var Z = cs.ZW * fn_g(N);+var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];- var r, g, b;- // Using different conversions for D50 and D65 white points,- // per http://www.color.org/srgb.pdf- if (cs.ZW < 1) {- // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)- r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;- g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;- b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;- } else {- // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)- r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;- g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;- b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;- }- // clamp color values to [0,1] range then convert to [0,255] range.- dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;- dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;- dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;- }+var Util = PDFJS.Util = (function UtilClosure() {+ function Util() {}- LabCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {- convertToRgb(this, src, srcOffset, false, dest, destOffset);- },- getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var maxVal = (1 << bits) - 1;- for (var i = 0; i < count; i++) {- convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);- srcOffset += 3;- destOffset += 3 + alpha01;- }- },- getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {- return (inputLength * (3 + alpha01) / 3) | 0;- },- isPassthrough: ColorSpace.prototype.isPassthrough,- isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {- // XXX: Decoding is handled with the lab conversion because of the strange- // ranges that are used.- return true;- },- usesZeroToOneRange: false+ Util.makeCssRgb = function Util_makeCssRgb(rgb) {+ return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';};- return LabCS;-})();+ Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) {+ var cs = new DeviceCmykCS();+ Util.makeCssCmyk = function makeCssCmyk(cmyk) {+ var rgb = cs.getRgb(cmyk, 0);+ return Util.makeCssRgb(rgb);+ };+ return Util.makeCssCmyk(cmyk);+ };+ // Concatenates two transformation matrices together and returns the result.+ Util.transform = function Util_transform(m1, m2) {+ return [+ m1[0] * m2[0] + m1[2] * m2[1],+ m1[1] * m2[0] + m1[3] * m2[1],+ m1[0] * m2[2] + m1[2] * m2[3],+ m1[1] * m2[2] + m1[3] * m2[3],+ m1[0] * m2[4] + m1[2] * m2[5] + m1[4],+ m1[1] * m2[4] + m1[3] * m2[5] + m1[5]+ ];+ };-var PDFFunction = (function PDFFunctionClosure() {- var CONSTRUCT_SAMPLED = 0;- var CONSTRUCT_INTERPOLATED = 2;- var CONSTRUCT_STICHED = 3;- var CONSTRUCT_POSTSCRIPT = 4;-- return {- getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,- str) {- var i, ii;- var length = 1;- for (i = 0, ii = size.length; i < ii; i++) {- length *= size[i];- }- length *= outputSize;-- var array = [];- var codeSize = 0;- var codeBuf = 0;- // 32 is a valid bps so shifting won't work- var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);-- var strBytes = str.getBytes((length * bps + 7) / 8);- var strIdx = 0;- for (i = 0; i < length; i++) {- while (codeSize < bps) {- codeBuf <<= 8;- codeBuf |= strBytes[strIdx++];- codeSize += 8;- }- codeSize -= bps;- array.push((codeBuf >> codeSize) * sampleMul);- codeBuf &= (1 << codeSize) - 1;- }- return array;- },+ // For 2d affine transforms+ Util.applyTransform = function Util_applyTransform(p, m) {+ var xt = p[0] * m[0] + p[1] * m[2] + m[4];+ var yt = p[0] * m[1] + p[1] * m[3] + m[5];+ return [xt, yt];+ };- getIR: function PDFFunction_getIR(xref, fn) {- var dict = fn.dict;- if (!dict) {- dict = fn;- }+ Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {+ var d = m[0] * m[3] - m[1] * m[2];+ var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;+ var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;+ return [xt, yt];+ };- var types = [this.constructSampled,- null,- this.constructInterpolated,- this.constructStiched,- this.constructPostScript];+ // Applies the transform to the rectangle and finds the minimum axially+ // aligned bounding box.+ Util.getAxialAlignedBoundingBox =+ function Util_getAxialAlignedBoundingBox(r, m) {- var typeNum = dict.get('FunctionType');- var typeFn = types[typeNum];- if (!typeFn) {- error('Unknown type of function');- }+ var p1 = Util.applyTransform(r, m);+ var p2 = Util.applyTransform(r.slice(2, 4), m);+ var p3 = Util.applyTransform([r[0], r[3]], m);+ var p4 = Util.applyTransform([r[2], r[1]], m);+ return [+ Math.min(p1[0], p2[0], p3[0], p4[0]),+ Math.min(p1[1], p2[1], p3[1], p4[1]),+ Math.max(p1[0], p2[0], p3[0], p4[0]),+ Math.max(p1[1], p2[1], p3[1], p4[1])+ ];+ };- return typeFn.call(this, fn, dict, xref);- },+ Util.inverseTransform = function Util_inverseTransform(m) {+ var d = m[0] * m[3] - m[1] * m[2];+ return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,+ (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];+ };- fromIR: function PDFFunction_fromIR(IR) {- var type = IR[0];- switch (type) {- case CONSTRUCT_SAMPLED:- return this.constructSampledFromIR(IR);- case CONSTRUCT_INTERPOLATED:- return this.constructInterpolatedFromIR(IR);- case CONSTRUCT_STICHED:- return this.constructStichedFromIR(IR);- //case CONSTRUCT_POSTSCRIPT:- default:- return this.constructPostScriptFromIR(IR);- }- },+ // Apply a generic 3d matrix M on a 3-vector v:+ // | a b c | | X |+ // | d e f | x | Y |+ // | g h i | | Z |+ // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],+ // with v as [X,Y,Z]+ Util.apply3dTransform = function Util_apply3dTransform(m, v) {+ return [+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2]+ ];+ };- parse: function PDFFunction_parse(xref, fn) {- var IR = this.getIR(xref, fn);- return this.fromIR(IR);- },+ // This calculation uses Singular Value Decomposition.+ // The SVD can be represented with formula A = USV. We are interested in the+ // matrix S here because it represents the scale values.+ Util.singularValueDecompose2dScale =+ function Util_singularValueDecompose2dScale(m) {- constructSampled: function PDFFunction_constructSampled(str, dict) {- function toMultiArray(arr) {- var inputLength = arr.length;- var outputLength = arr.length / 2;- var out = [];- var index = 0;- for (var i = 0; i < inputLength; i += 2) {- out[index] = [arr[i], arr[i + 1]];- ++index;- }- return out;- }- var domain = dict.get('Domain');- var range = dict.get('Range');+ var transpose = [m[0], m[2], m[1], m[3]];- if (!domain || !range) {- error('No domain or range');- }+ // Multiply matrix m with its transpose.+ var a = m[0] * transpose[0] + m[1] * transpose[2];+ var b = m[0] * transpose[1] + m[1] * transpose[3];+ var c = m[2] * transpose[0] + m[3] * transpose[2];+ var d = m[2] * transpose[1] + m[3] * transpose[3];- var inputSize = domain.length / 2;- var outputSize = range.length / 2;+ // Solve the second degree polynomial to get roots.+ var first = (a + d) / 2;+ var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;+ var sx = first + second || 1;+ var sy = first - second || 1;- domain = toMultiArray(domain);- range = toMultiArray(range);+ // Scale values are the square roots of the eigenvalues.+ return [Math.sqrt(sx), Math.sqrt(sy)];+ };- var size = dict.get('Size');- var bps = dict.get('BitsPerSample');- var order = dict.get('Order') || 1;- if (order !== 1) {- // No description how cubic spline interpolation works in PDF32000:2008- // As in poppler, ignoring order, linear interpolation may work as good- info('No support for cubic spline interpolation: ' + order);- }+ // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)+ // For coordinate systems whose origin lies in the bottom-left, this+ // means normalization to (BL,TR) ordering. For systems with origin in the+ // top-left, this means (TL,BR) ordering.+ Util.normalizeRect = function Util_normalizeRect(rect) {+ var r = rect.slice(0); // clone rect+ if (rect[0] > rect[2]) {+ r[0] = rect[2];+ r[2] = rect[0];+ }+ if (rect[1] > rect[3]) {+ r[1] = rect[3];+ r[3] = rect[1];+ }+ return r;+ };- var encode = dict.get('Encode');- if (!encode) {- encode = [];- for (var i = 0; i < inputSize; ++i) {- encode.push(0);- encode.push(size[i] - 1);- }- }- encode = toMultiArray(encode);+ // Returns a rectangle [x1, y1, x2, y2] corresponding to the+ // intersection of rect1 and rect2. If no intersection, returns 'false'+ // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]+ Util.intersect = function Util_intersect(rect1, rect2) {+ function compare(a, b) {+ return a - b;+ }- var decode = dict.get('Decode');- if (!decode) {- decode = range;- } else {- decode = toMultiArray(decode);- }+ // Order points along the axes+ var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),+ orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),+ result = [];- var samples = this.getSampleArray(size, outputSize, bps, str);+ rect1 = Util.normalizeRect(rect1);+ rect2 = Util.normalizeRect(rect2);- return [- CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,- outputSize, Math.pow(2, bps) - 1, range- ];- },+ // X: first and second points belong to different rectangles?+ if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||+ (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {+ // Intersection must be between second and third points+ result[0] = orderedX[1];+ result[2] = orderedX[2];+ } else {+ return false;+ }- constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {- // See chapter 3, page 109 of the PDF reference- function interpolate(x, xmin, xmax, ymin, ymax) {- return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));- }+ // Y: first and second points belong to different rectangles?+ if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||+ (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {+ // Intersection must be between second and third points+ result[1] = orderedY[1];+ result[3] = orderedY[2];+ } else {+ return false;+ }- return function constructSampledFromIRResult(args) {- // See chapter 3, page 110 of the PDF reference.- var m = IR[1];- var domain = IR[2];- var encode = IR[3];- var decode = IR[4];- var samples = IR[5];- var size = IR[6];- var n = IR[7];- var mask = IR[8];- var range = IR[9];+ return result;+ };- if (m != args.length) {- error('Incorrect number of arguments: ' + m + ' != ' +- args.length);- }+ Util.sign = function Util_sign(num) {+ return num < 0 ? -1 : 1;+ };- var x = args;+ // TODO(mack): Rename appendToArray+ Util.concatenateToArray = function concatenateToArray(arr1, arr2) {+ Array.prototype.push.apply(arr1, arr2);+ };- // Building the cube vertices: its part and sample index- // http://rjwagner49.com/Mathematics/Interpolation.pdf- var cubeVertices = 1 << m;- var cubeN = new Float64Array(cubeVertices);- var cubeVertex = new Uint32Array(cubeVertices);- var i, j;- for (j = 0; j < cubeVertices; j++) {- cubeN[j] = 1;- }+ Util.prependToArray = function concatenateToArray(arr1, arr2) {+ Array.prototype.unshift.apply(arr1, arr2);+ };- var k = n, pos = 1;- // Map x_i to y_j for 0 <= i < m using the sampled function.- for (i = 0; i < m; ++i) {- // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)- var domain_2i = domain[i][0];- var domain_2i_1 = domain[i][1];- var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);+ Util.extendObj = function extendObj(obj1, obj2) {+ for (var key in obj2) {+ obj1[key] = obj2[key];+ }+ };- // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,- // Encode_2i, Encode_2i+1)- var e = interpolate(xi, domain_2i, domain_2i_1,- encode[i][0], encode[i][1]);+ Util.getInheritableProperty = function Util_getInheritableProperty(dict,+ name) {+ while (dict && !dict.has(name)) {+ dict = dict.get('Parent');+ }+ if (!dict) {+ return null;+ }+ return dict.get(name);+ };- // e_i' = min(max(e_i, 0), Size_i - 1)- var size_i = size[i];- e = Math.min(Math.max(e, 0), size_i - 1);+ Util.inherit = function Util_inherit(sub, base, prototype) {+ sub.prototype = Object.create(base.prototype);+ sub.prototype.constructor = sub;+ for (var prop in prototype) {+ sub.prototype[prop] = prototype[prop];+ }+ };- // Adjusting the cube: N and vertex sample index- var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;- var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);- var n1 = e - e0; // (e - e0) / (e1 - e0);- var offset0 = e0 * k;- var offset1 = offset0 + k; // e1 * k- for (j = 0; j < cubeVertices; j++) {- if (j & pos) {- cubeN[j] *= n1;- cubeVertex[j] += offset1;- } else {- cubeN[j] *= n0;- cubeVertex[j] += offset0;- }- }+ return Util;+})();- k *= size_i;- pos <<= 1;- }+var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {+ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {+ this.viewBox = viewBox;+ this.scale = scale;+ this.rotation = rotation;+ this.offsetX = offsetX;+ this.offsetY = offsetY;- var y = new Float64Array(n);- for (j = 0; j < n; ++j) {- // Sum all cube vertices' samples portions- var rj = 0;- for (i = 0; i < cubeVertices; i++) {- rj += samples[cubeVertex[i] + j] * cubeN[i];- }+ // creating transform to convert pdf coordinate system to the normal+ // canvas like coordinates taking in account scale and rotation+ var centerX = (viewBox[2] + viewBox[0]) / 2;+ var centerY = (viewBox[3] + viewBox[1]) / 2;+ var rotateA, rotateB, rotateC, rotateD;+ rotation = rotation % 360;+ rotation = rotation < 0 ? rotation + 360 : rotation;+ switch (rotation) {+ case 180:+ rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;+ break;+ case 90:+ rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;+ break;+ case 270:+ rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;+ break;+ //case 0:+ default:+ rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;+ break;+ }- // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,- // Decode_2j, Decode_2j+1)- rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);+ if (dontFlip) {+ rotateC = -rotateC; rotateD = -rotateD;+ }- // y_j = min(max(r_j, range_2j), range_2j+1)- y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);- }+ var offsetCanvasX, offsetCanvasY;+ var width, height;+ if (rotateA === 0) {+ offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;+ offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;+ width = Math.abs(viewBox[3] - viewBox[1]) * scale;+ height = Math.abs(viewBox[2] - viewBox[0]) * scale;+ } else {+ offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;+ offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;+ width = Math.abs(viewBox[2] - viewBox[0]) * scale;+ height = Math.abs(viewBox[3] - viewBox[1]) * scale;+ }+ // creating transform for the following operations:+ // translate(-centerX, -centerY), rotate and flip vertically,+ // scale, and translate(offsetCanvasX, offsetCanvasY)+ this.transform = [+ rotateA * scale,+ rotateB * scale,+ rotateC * scale,+ rotateD * scale,+ offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,+ offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY+ ];- return y;- };+ this.width = width;+ this.height = height;+ this.fontScale = scale;+ }+ PageViewport.prototype = {+ clone: function PageViewPort_clone(args) {+ args = args || {};+ var scale = 'scale' in args ? args.scale : this.scale;+ var rotation = 'rotation' in args ? args.rotation : this.rotation;+ return new PageViewport(this.viewBox.slice(), scale, rotation,+ this.offsetX, this.offsetY, args.dontFlip);+ },+ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {+ return Util.applyTransform([x, y], this.transform);},+ convertToViewportRectangle:+ function PageViewport_convertToViewportRectangle(rect) {+ var tl = Util.applyTransform([rect[0], rect[1]], this.transform);+ var br = Util.applyTransform([rect[2], rect[3]], this.transform);+ return [tl[0], tl[1], br[0], br[1]];+ },+ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {+ return Util.applyInverseTransform([x, y], this.transform);+ }+ };+ return PageViewport;+})();- constructInterpolated: function PDFFunction_constructInterpolated(str,- dict) {- var c0 = dict.get('C0') || [0];- var c1 = dict.get('C1') || [1];- var n = dict.get('N');+var PDFStringTranslateTable = [+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,+ 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,+ 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,+ 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC+];- if (!isArray(c0) || !isArray(c1)) {- error('Illegal dictionary for interpolated function');- }+function stringToPDFString(str) {+ var i, n = str.length, str2 = '';+ if (str[0] === '\xFE' && str[1] === '\xFF') {+ // UTF16BE BOM+ for (i = 2; i < n; i += 2)+ str2 += String.fromCharCode(+ (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1));+ } else {+ for (i = 0; i < n; ++i) {+ var code = PDFStringTranslateTable[str.charCodeAt(i)];+ str2 += code ? String.fromCharCode(code) : str.charAt(i);+ }+ }+ return str2;+}- var length = c0.length;- var diff = [];- for (var i = 0; i < length; ++i) {- diff.push(c1[i] - c0[i]);- }+function stringToUTF8String(str) {+ return decodeURIComponent(escape(str));+}- return [CONSTRUCT_INTERPOLATED, c0, diff, n];- },+function isEmptyObj(obj) {+ for (var key in obj) {+ return false;+ }+ return true;+}- constructInterpolatedFromIR:- function PDFFunction_constructInterpolatedFromIR(IR) {- var c0 = IR[1];- var diff = IR[2];- var n = IR[3];+function isBool(v) {+ return typeof v == 'boolean';+}- var length = diff.length;+function isInt(v) {+ return typeof v == 'number' && ((v | 0) == v);+}- return function constructInterpolatedFromIRResult(args) {- var x = n == 1 ? args[0] : Math.pow(args[0], n);+function isNum(v) {+ return typeof v == 'number';+}- var out = [];- for (var j = 0; j < length; ++j) {- out.push(c0[j] + (x * diff[j]));- }+function isString(v) {+ return typeof v == 'string';+}- return out;+function isNull(v) {+ return v === null;+}- };- },+function isName(v) {+ return v instanceof Name;+}- constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {- var domain = dict.get('Domain');+function isCmd(v, cmd) {+ return v instanceof Cmd && (!cmd || v.cmd == cmd);+}- if (!domain) {- error('No domain');- }+function isDict(v, type) {+ if (!(v instanceof Dict)) {+ return false;+ }+ if (!type) {+ return true;+ }+ var dictType = v.get('Type');+ return isName(dictType) && dictType.name == type;+}- var inputSize = domain.length / 2;- if (inputSize != 1) {- error('Bad domain for stiched function');- }+function isArray(v) {+ return v instanceof Array;+}- var fnRefs = dict.get('Functions');- var fns = [];- for (var i = 0, ii = fnRefs.length; i < ii; ++i) {- fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));+function isStream(v) {+ return typeof v == 'object' && v !== null && v !== undefined &&+ ('getChar' in v);+}++function isArrayBuffer(v) {+ return typeof v == 'object' && v !== null && v !== undefined &&+ ('byteLength' in v);+}++function isRef(v) {+ return v instanceof Ref;+}++function isPDFFunction(v) {+ var fnDict;+ if (typeof v != 'object')+ return false;+ else if (isDict(v))+ fnDict = v;+ else if (isStream(v))+ fnDict = v.dict;+ else+ return false;+ return fnDict.has('FunctionType');+}++/**+ * The following promise implementation tries to generally implment the+ * Promise/A+ spec. Some notable differences from other promise libaries are:+ * - There currently isn't a seperate deferred and promise object.+ * - Unhandled rejections eventually show an error if they aren't handled.+ *+ * Based off of the work in:+ * https://bugzilla.mozilla.org/show_bug.cgi?id=810490+ */+var Promise = PDFJS.Promise = (function PromiseClosure() {+ var STATUS_PENDING = 0;+ var STATUS_RESOLVED = 1;+ var STATUS_REJECTED = 2;++ // In an attempt to avoid silent exceptions, unhandled rejections are+ // tracked and if they aren't handled in a certain amount of time an+ // error is logged.+ var REJECTION_TIMEOUT = 500;++ var HandlerManager = {+ handlers: [],+ running: false,+ unhandledRejections: [],+ pendingRejectionCheck: false,++ scheduleHandlers: function scheduleHandlers(promise) {+ if (promise._status == STATUS_PENDING) {+ return;}- var bounds = dict.get('Bounds');- var encode = dict.get('Encode');+ this.handlers = this.handlers.concat(promise._handlers);+ promise._handlers = [];- return [CONSTRUCT_STICHED, domain, bounds, encode, fns];+ if (this.running) {+ return;+ }+ this.running = true;++ setTimeout(this.runHandlers.bind(this), 0);},- constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {- var domain = IR[1];- var bounds = IR[2];- var encode = IR[3];- var fnsIR = IR[4];- var fns = [];+ runHandlers: function runHandlers() {+ while (this.handlers.length > 0) {+ var handler = this.handlers.shift();- for (var i = 0, ii = fnsIR.length; i < ii; i++) {- fns.push(PDFFunction.fromIR(fnsIR[i]));- }+ var nextStatus = handler.thisPromise._status;+ var nextValue = handler.thisPromise._value;- return function constructStichedFromIRResult(args) {- var clip = function constructStichedFromIRClip(v, min, max) {- if (v > max) {- v = max;- } else if (v < min) {- v = min;- }- return v;- };+ try {+ if (nextStatus === STATUS_RESOLVED) {+ if (typeof(handler.onResolve) == 'function') {+ nextValue = handler.onResolve(nextValue);+ }+ } else if (typeof(handler.onReject) === 'function') {+ nextValue = handler.onReject(nextValue);+ nextStatus = STATUS_RESOLVED;- // clip to domain- var v = clip(args[0], domain[0], domain[1]);- // calulate which bound the value is in- for (var i = 0, ii = bounds.length; i < ii; ++i) {- if (v < bounds[i]) {- break;+ if (handler.thisPromise._unhandledRejection) {+ this.removeUnhandeledRejection(handler.thisPromise);+ }}+ } catch (ex) {+ nextStatus = STATUS_REJECTED;+ nextValue = ex;}- // encode value into domain of function- var dmin = domain[0];- if (i > 0) {- dmin = bounds[i - 1];- }- var dmax = domain[1];- if (i < bounds.length) {- dmax = bounds[i];- }+ handler.nextPromise._updateStatus(nextStatus, nextValue);+ }- var rmin = encode[2 * i];- var rmax = encode[2 * i + 1];+ this.running = false;+ },- var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);+ addUnhandledRejection: function addUnhandledRejection(promise) {+ this.unhandledRejections.push({+ promise: promise,+ time: Date.now()+ });+ this.scheduleRejectionCheck();+ },- // call the appropriate function- return fns[i]([v2]);- };+ removeUnhandeledRejection: function removeUnhandeledRejection(promise) {+ promise._unhandledRejection = false;+ for (var i = 0; i < this.unhandledRejections.length; i++) {+ if (this.unhandledRejections[i].promise === promise) {+ this.unhandledRejections.splice(i);+ i--;+ }+ }},- constructPostScript: function PDFFunction_constructPostScript(fn, dict,- xref) {- var domain = dict.get('Domain');- var range = dict.get('Range');+ scheduleRejectionCheck: function scheduleRejectionCheck() {+ if (this.pendingRejectionCheck) {+ return;+ }+ this.pendingRejectionCheck = true;+ setTimeout(function rejectionCheck() {+ this.pendingRejectionCheck = false;+ var now = Date.now();+ for (var i = 0; i < this.unhandledRejections.length; i++) {+ if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {+ warn('Unhandled rejection: ' ++ this.unhandledRejections[i].promise._value);+ this.unhandledRejections.splice(i);+ i--;+ }+ }+ if (this.unhandledRejections.length) {+ this.scheduleRejectionCheck();+ }+ }.bind(this), REJECTION_TIMEOUT);+ }+ };- if (!domain) {- error('No domain.');+ function Promise() {+ this._status = STATUS_PENDING;+ this._handlers = [];+ }+ /**+ * Builds a promise that is resolved when all the passed in promises are+ * resolved.+ * @param {Promise[]} promises Array of promises to wait for.+ * @return {Promise} New dependant promise.+ */+ Promise.all = function Promise_all(promises) {+ var deferred = new Promise();+ var unresolved = promises.length;+ var results = [];+ if (unresolved === 0) {+ deferred.resolve(results);+ return deferred;+ }+ function reject(reason) {+ if (deferred._status === STATUS_REJECTED) {+ return;}+ results = [];+ deferred.reject(reason);+ }+ for (var i = 0, ii = promises.length; i < ii; ++i) {+ var promise = promises[i];+ promise.then((function(i) {+ return function(value) {+ if (deferred._status === STATUS_REJECTED) {+ return;+ }+ results[i] = value;+ unresolved--;+ if (unresolved === 0)+ deferred.resolve(results);+ };+ })(i), reject);+ }+ return deferred;+ };- if (!range) {- error('No range.');+ Promise.prototype = {+ _status: null,+ _value: null,+ _handlers: null,+ _unhandledRejection: null,++ _updateStatus: function Promise__updateStatus(status, value) {+ if (this._status === STATUS_RESOLVED ||+ this._status === STATUS_REJECTED) {+ return;}- var lexer = new PostScriptLexer(fn);- var parser = new PostScriptParser(lexer);- var code = parser.parse();+ if (status == STATUS_RESOLVED &&+ value && typeof(value.then) === 'function') {+ value.then(this._updateStatus.bind(this, STATUS_RESOLVED),+ this._updateStatus.bind(this, STATUS_REJECTED));+ return;+ }- return [CONSTRUCT_POSTSCRIPT, domain, range, code];+ this._status = status;+ this._value = value;++ if (status === STATUS_REJECTED && this._handlers.length === 0) {+ this._unhandledRejection = true;+ HandlerManager.addUnhandledRejection(this);+ }++ HandlerManager.scheduleHandlers(this);},- constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(- IR) {- var domain = IR[1];- var range = IR[2];- var code = IR[3];- var numOutputs = range.length / 2;- var evaluator = new PostScriptEvaluator(code);- // Cache the values for a big speed up, the cache size is limited though- // since the number of possible values can be huge from a PS function.- var cache = new FunctionCache();- return function constructPostScriptFromIRResult(args) {- var initialStack = [];- for (var i = 0, ii = (domain.length / 2); i < ii; ++i) {- initialStack.push(args[i]);- }+ get isResolved() {+ return this._status === STATUS_RESOLVED;+ },- var key = initialStack.join('_');- if (cache.has(key)) {- return cache.get(key);- }+ get isRejected() {+ return this._status === STATUS_REJECTED;+ },- var stack = evaluator.execute(initialStack);- var transformed = [];- for (i = numOutputs - 1; i >= 0; --i) {- var out = stack.pop();- var rangeIndex = 2 * i;- if (out < range[rangeIndex]) {- out = range[rangeIndex];- } else if (out > range[rangeIndex + 1]) {- out = range[rangeIndex + 1];- }- transformed[i] = out;- }- cache.set(key, transformed);- return transformed;- };+ resolve: function Promise_resolve(value) {+ this._updateStatus(STATUS_RESOLVED, value);+ },++ reject: function Promise_reject(reason) {+ this._updateStatus(STATUS_REJECTED, reason);+ },++ then: function Promise_then(onResolve, onReject) {+ var nextPromise = new Promise();+ this._handlers.push({+ thisPromise: this,+ onResolve: onResolve,+ onReject: onReject,+ nextPromise: nextPromise+ });+ HandlerManager.scheduleHandlers(this);+ return nextPromise;}};++ return Promise;})();-var FunctionCache = (function FunctionCacheClosure() {- // Of 10 PDF's with type4 functions the maxium number of distinct values seen- // was 256. This still may need some tweaking in the future though.- var MAX_CACHE_SIZE = 1024;- function FunctionCache() {- this.cache = {};- this.total = 0;+var StatTimer = (function StatTimerClosure() {+ function rpad(str, pad, length) {+ while (str.length < length)+ str += pad;+ return str;}- FunctionCache.prototype = {- has: function FunctionCache_has(key) {- return key in this.cache;+ function StatTimer() {+ this.started = {};+ this.times = [];+ this.enabled = true;+ }+ StatTimer.prototype = {+ time: function StatTimer_time(name) {+ if (!this.enabled)+ return;+ if (name in this.started)+ throw 'Timer is already running for ' + name;+ this.started[name] = Date.now();},- get: function FunctionCache_get(key) {- return this.cache[key];+ timeEnd: function StatTimer_timeEnd(name) {+ if (!this.enabled)+ return;+ if (!(name in this.started))+ throw 'Timer has not been started for ' + name;+ this.times.push({+ 'name': name,+ 'start': this.started[name],+ 'end': Date.now()+ });+ // Remove timer from started so it can be called again.+ delete this.started[name];},- set: function FunctionCache_set(key, value) {- if (this.total < MAX_CACHE_SIZE) {- this.cache[key] = value;- this.total++;+ toString: function StatTimer_toString() {+ var times = this.times;+ var out = '';+ // Find the longest name for padding purposes.+ var longest = 0;+ for (var i = 0, ii = times.length; i < ii; ++i) {+ var name = times[i]['name'];+ if (name.length > longest)+ longest = name.length;}+ for (var i = 0, ii = times.length; i < ii; ++i) {+ var span = times[i];+ var duration = span.end - span.start;+ out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';+ }+ return out;}};- return FunctionCache;+ return StatTimer;})();-var PostScriptStack = (function PostScriptStackClosure() {- var MAX_STACK_SIZE = 100;- function PostScriptStack(initialStack) {- this.stack = initialStack || [];+PDFJS.createBlob = function createBlob(data, contentType) {+ if (typeof Blob === 'function')+ return new Blob([data], { type: contentType });+ // Blob builder is deprecated in FF14 and removed in FF18.+ var bb = new MozBlobBuilder();+ bb.append(data);+ return bb.getBlob(contentType);+};+++/**+ * This is the main entry point for loading a PDF and interacting with it.+ * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)+ * is used, which means it must follow the same origin rules that any XHR does+ * e.g. No cross domain requests without CORS.+ *+ * @param {string|TypedAray|object} source Can be an url to where a PDF is+ * located, a typed array (Uint8Array) already populated with data or+ * and parameter object with the following possible fields:+ * - url - The URL of the PDF.+ * - data - A typed array with PDF data.+ * - httpHeaders - Basic authentication headers.+ * - password - For decrypting password-protected PDFs.+ *+ * @param {object} pdfDataRangeTransport is optional. It is used if you want+ * to manually serve range requests for data in the PDF. See viewer.js for+ * an example of pdfDataRangeTransport's interface.+ *+ * @param {function} passwordCallback is optional. It is used to request a+ * password if wrong or no password was provided. The callback receives two+ * parameters: function that needs to be called with new password and reason+ * (see {PasswordResponses}).+ *+ * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.+ */+PDFJS.getDocument = function getDocument(source,+ pdfDataRangeTransport,+ passwordCallback,+ progressCallback) {+ var workerInitializedPromise, workerReadyPromise, transport;++ if (typeof source === 'string') {+ source = { url: source };+ } else if (isArrayBuffer(source)) {+ source = { data: source };+ } else if (typeof source !== 'object') {+ error('Invalid parameter in getDocument, need either Uint8Array, ' ++ 'string or a parameter object');+ }++ if (!source.url && !source.data)+ error('Invalid parameter array, need either .data or .url');++ // copy/use all keys as is except 'url' -- full path is required+ var params = {};+ for (var key in source) {+ if (key === 'url' && typeof window !== 'undefined') {+ params[key] = combineUrl(window.location.href, source[key]);+ continue;+ }+ params[key] = source[key];+ }++ workerInitializedPromise = new PDFJS.Promise();+ workerReadyPromise = new PDFJS.Promise();+ transport = new WorkerTransport(workerInitializedPromise,+ workerReadyPromise, pdfDataRangeTransport, progressCallback);+ workerInitializedPromise.then(function transportInitialized() {+ transport.passwordCallback = passwordCallback;+ transport.fetchDocument(params);+ });+ return workerReadyPromise;+};++/**+ * Proxy to a PDFDocument in the worker thread. Also, contains commonly used+ * properties that can be read synchronously.+ */+var PDFDocumentProxy = (function PDFDocumentProxyClosure() {+ function PDFDocumentProxy(pdfInfo, transport) {+ this.pdfInfo = pdfInfo;+ this.transport = transport;}+ PDFDocumentProxy.prototype = {+ /**+ * @return {number} Total number of pages the PDF contains.+ */+ get numPages() {+ return this.pdfInfo.numPages;+ },+ /**+ * @return {string} A unique ID to identify a PDF. Not guaranteed to be+ * unique.+ */+ get fingerprint() {+ return this.pdfInfo.fingerprint;+ },+ /**+ * @return {boolean} true if embedded document fonts are in use. Will be+ * set during rendering of the pages.+ */+ get embeddedFontsUsed() {+ return this.transport.embeddedFontsUsed;+ },+ /**+ * @param {number} The page number to get. The first page is 1.+ * @return {Promise} A promise that is resolved with a {PDFPageProxy}+ * object.+ */+ getPage: function PDFDocumentProxy_getPage(number) {+ return this.transport.getPage(number);+ },+ /**+ * @return {Promise} A promise that is resolved with a lookup table for+ * mapping named destinations to reference numbers.+ */+ getDestinations: function PDFDocumentProxy_getDestinations() {+ return this.transport.getDestinations();+ },+ /**+ * @return {Promise} A promise that is resolved with an array of all the+ * JavaScript strings in the name tree.+ */+ getJavaScript: function PDFDocumentProxy_getDestinations() {+ var promise = new PDFJS.Promise();+ var js = this.pdfInfo.javaScript;+ promise.resolve(js);+ return promise;+ },+ /**+ * @return {Promise} A promise that is resolved with an {array} that is a+ * tree outline (if it has one) of the PDF. The tree is in the format of:+ * [+ * {+ * title: string,+ * bold: boolean,+ * italic: boolean,+ * color: rgb array,+ * dest: dest obj,+ * items: array of more items like this+ * },+ * ...+ * ].+ */+ getOutline: function PDFDocumentProxy_getOutline() {+ var promise = new PDFJS.Promise();+ var outline = this.pdfInfo.outline;+ promise.resolve(outline);+ return promise;+ },+ /**+ * @return {Promise} A promise that is resolved with an {object} that has+ * info and metadata properties. Info is an {object} filled with anything+ * available in the information dictionary and similarly metadata is a+ * {Metadata} object with information from the metadata section of the PDF.+ */+ getMetadata: function PDFDocumentProxy_getMetadata() {+ var promise = new PDFJS.Promise();+ var info = this.pdfInfo.info;+ var metadata = this.pdfInfo.metadata;+ promise.resolve({+ info: info,+ metadata: metadata ? new PDFJS.Metadata(metadata) : null+ });+ return promise;+ },+ isEncrypted: function PDFDocumentProxy_isEncrypted() {+ var promise = new PDFJS.Promise();+ promise.resolve(this.pdfInfo.encrypted);+ return promise;+ },+ /**+ * @return {Promise} A promise that is resolved with a TypedArray that has+ * the raw data from the PDF.+ */+ getData: function PDFDocumentProxy_getData() {+ var promise = new PDFJS.Promise();+ this.transport.getData(promise);+ return promise;+ },+ /**+ * @return {Promise} A promise that is resolved when the document's data+ * is loaded+ */+ dataLoaded: function PDFDocumentProxy_dataLoaded() {+ return this.transport.dataLoaded();+ },+ destroy: function PDFDocumentProxy_destroy() {+ this.transport.destroy();+ }+ };+ return PDFDocumentProxy;+})();- PostScriptStack.prototype = {- push: function PostScriptStack_push(value) {- if (this.stack.length >= MAX_STACK_SIZE) {- error('PostScript function stack overflow.');- }- this.stack.push(value);+var PDFPageProxy = (function PDFPageProxyClosure() {+ function PDFPageProxy(pageInfo, transport) {+ this.pageInfo = pageInfo;+ this.transport = transport;+ this.stats = new StatTimer();+ this.stats.enabled = !!globalScope.PDFJS.enableStats;+ this.commonObjs = transport.commonObjs;+ this.objs = new PDFObjects();+ this.renderInProgress = false;+ this.cleanupAfterRender = false;+ }+ PDFPageProxy.prototype = {+ /**+ * @return {number} Page number of the page. First page is 1.+ */+ get pageNumber() {+ return this.pageInfo.pageIndex + 1;},- pop: function PostScriptStack_pop() {- if (this.stack.length <= 0) {- error('PostScript function stack underflow.');- }- return this.stack.pop();+ /**+ * @return {number} The number of degrees the page is rotated clockwise.+ */+ get rotate() {+ return this.pageInfo.rotate;},- copy: function PostScriptStack_copy(n) {- if (this.stack.length + n >= MAX_STACK_SIZE) {- error('PostScript function stack overflow.');+ /**+ * @return {object} The reference that points to this page. It has 'num' and+ * 'gen' properties.+ */+ get ref() {+ return this.pageInfo.ref;+ },+ /**+ * @return {array} An array of the visible portion of the PDF page in the+ * user space units - [x1, y1, x2, y2].+ */+ get view() {+ return this.pageInfo.view;+ },+ /**+ * @param {number} scale The desired scale of the viewport.+ * @param {number} rotate Degrees to rotate the viewport. If omitted this+ * defaults to the page rotation.+ * @return {PageViewport} Contains 'width' and 'height' properties along+ * with transforms required for rendering.+ */+ getViewport: function PDFPageProxy_getViewport(scale, rotate) {+ if (arguments.length < 2)+ rotate = this.rotate;+ return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);+ },+ /**+ * @return {Promise} A promise that is resolved with an {array} of the+ * annotation objects.+ */+ getAnnotations: function PDFPageProxy_getAnnotations() {+ if (this.annotationsPromise)+ return this.annotationsPromise;++ var promise = new PDFJS.Promise();+ this.annotationsPromise = promise;+ this.transport.getAnnotations(this.pageInfo.pageIndex);+ return promise;+ },+ /**+ * Begins the process of rendering a page to the desired context.+ * @param {object} params A parameter object that supports:+ * {+ * canvasContext(required): A 2D context of a DOM Canvas object.,+ * textLayer(optional): An object that has beginLayout, endLayout, and+ * appendText functions.,+ * imageLayer(optional): An object that has beginLayout, endLayout and+ * appendImage functions.,+ * continueCallback(optional): A function that will be called each time+ * the rendering is paused. To continue+ * rendering call the function that is the+ * first argument to the callback.+ * }.+ * @return {Promise} A promise that is resolved when the page finishes+ * rendering.+ */+ render: function PDFPageProxy_render(params) {+ this.renderInProgress = true;++ var promise = new Promise();+ var stats = this.stats;+ stats.time('Overall');+ // If there is no displayReadyPromise yet, then the operatorList was never+ // requested before. Make the request and create the promise.+ if (!this.displayReadyPromise) {+ this.displayReadyPromise = new Promise();+ this.destroyed = false;++ this.stats.time('Page Request');+ this.transport.messageHandler.send('RenderPageRequest', {+ pageIndex: this.pageNumber - 1+ });}- var stack = this.stack;- for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {- stack.push(stack[i]);++ var self = this;+ function complete(error) {+ self.renderInProgress = false;+ if (self.destroyed || self.cleanupAfterRender) {+ delete self.displayReadyPromise;+ delete self.operatorList;+ self.objs.clear();+ }++ if (error)+ promise.reject(error);+ else+ promise.resolve();}+ var continueCallback = params.continueCallback;++ // Once the operatorList and fonts are loaded, do the actual rendering.+ this.displayReadyPromise.then(+ function pageDisplayReadyPromise() {+ if (self.destroyed) {+ complete();+ return;+ }++ var gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,+ this.objs, params.textLayer, params.imageLayer);+ try {+ this.display(gfx, params.viewport, complete, continueCallback);+ } catch (e) {+ complete(e);+ }+ }.bind(this),+ function pageDisplayReadPromiseError(reason) {+ complete(reason);+ }+ );++ return promise;},- index: function PostScriptStack_index(n) {- this.push(this.stack[this.stack.length - n - 1]);+ /**+ * For internal use only.+ */+ startRenderingFromOperatorList:+ function PDFPageProxy_startRenderingFromOperatorList(operatorList,+ fonts) {+ var self = this;+ this.operatorList = operatorList;++ this.ensureFonts(fonts,+ function pageStartRenderingFromOperatorListEnsureFonts() {+ self.displayReadyPromise.resolve();+ }+ );},- // rotate the last n stack elements p times- roll: function PostScriptStack_roll(n, p) {- var stack = this.stack;- var l = stack.length - n;- var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;- for (i = l, j = r; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;+ /**+ * For internal use only.+ */+ ensureFonts: function PDFPageProxy_ensureFonts(fonts, callback) {+ this.stats.time('Font Loading');+ // Convert the font names to the corresponding font obj.+ var fontObjs = [];+ for (var i = 0, ii = fonts.length; i < ii; i++) {+ var obj = this.commonObjs.getData(fonts[i]);+ if (obj.error) {+ warn('Error during font loading: ' + obj.error);+ continue;+ }+ if (!obj.coded) {+ this.transport.embeddedFontsUsed = true;+ }+ fontObjs.push(obj);}- for (i = l, j = c - 1; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;++ // Load all the fonts+ FontLoader.bind(+ fontObjs,+ function pageEnsureFontsFontObjs(fontObjs) {+ this.stats.timeEnd('Font Loading');++ callback.call(this);+ }.bind(this)+ );+ },+ /**+ * For internal use only.+ */+ display: function PDFPageProxy_display(gfx, viewport, callback,+ continueCallback) {+ var stats = this.stats;+ stats.time('Rendering');++ var operatorList = this.operatorList;+ gfx.beginDrawing(viewport, operatorList.transparency);++ var startIdx = 0;+ var length = operatorList.fnArray.length;+ var stepper = null;+ if (PDFJS.pdfBug && 'StepperManager' in globalScope &&+ globalScope['StepperManager'].enabled) {+ stepper = globalScope['StepperManager'].create(this.pageNumber - 1);+ stepper.init(operatorList);+ stepper.nextBreakPoint = stepper.getNextBreakPoint();+ }++ var continueWrapper;+ if (continueCallback)+ continueWrapper = function() { continueCallback(next); };+ else+ continueWrapper = next;++ var self = this;+ function next() {+ startIdx = gfx.executeOperatorList(operatorList, startIdx,+ continueWrapper, stepper);+ if (startIdx == length) {+ gfx.endDrawing();+ stats.timeEnd('Rendering');+ stats.timeEnd('Overall');+ if (callback) callback();+ }}- for (i = c, j = r; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;+ continueWrapper();+ },+ /**+ * @return {Promise} That is resolved with the a {string} that is the text+ * content from the page.+ */+ getTextContent: function PDFPageProxy_getTextContent() {+ var promise = new PDFJS.Promise();+ this.transport.messageHandler.send('GetTextContent', {+ pageIndex: this.pageNumber - 1+ },+ function textContentCallback(textContent) {+ promise.resolve(textContent);+ }+ );+ return promise;+ },+ /**+ * Stub for future feature.+ */+ getOperationList: function PDFPageProxy_getOperationList() {+ var promise = new PDFJS.Promise();+ var operationList = { // not implemented+ dependencyFontsID: null,+ operatorList: null+ };+ promise.resolve(operationList);+ return promise;+ },+ /**+ * Destroys resources allocated by the page.+ */+ destroy: function PDFPageProxy_destroy() {+ this.destroyed = true;++ if (!this.renderInProgress) {+ delete this.operatorList;+ delete this.displayReadyPromise;+ this.objs.clear();}}};- return PostScriptStack;+ return PDFPageProxy;})();-var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {- function PostScriptEvaluator(operators) {- this.operators = operators;+/**+ * For internal use only.+ */+var WorkerTransport = (function WorkerTransportClosure() {+ function WorkerTransport(workerInitializedPromise, workerReadyPromise,+ pdfDataRangeTransport, progressCallback) {+ this.pdfDataRangeTransport = pdfDataRangeTransport;++ this.workerReadyPromise = workerReadyPromise;+ this.progressCallback = progressCallback;+ this.commonObjs = new PDFObjects();++ this.pageCache = [];+ this.pagePromises = [];+ this.embeddedFontsUsed = false;++ this.passwordCallback = null;++ // If worker support isn't disabled explicit and the browser has worker+ // support, create a new web worker and test if it/the browser fullfills+ // all requirements to run parts of pdf.js in a web worker.+ // Right now, the requirement is, that an Uint8Array is still an Uint8Array+ // as it arrives on the worker. Chrome added this with version 15.+ if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {+ var workerSrc = PDFJS.workerSrc;+ if (typeof workerSrc === 'undefined') {+ error('No PDFJS.workerSrc specified');+ }++ try {+ // Some versions of FF can't create a worker on localhost, see:+ // https://bugzilla.mozilla.org/show_bug.cgi?id=683280+ var worker = new Worker(workerSrc);+ var messageHandler = new MessageHandler('main', worker);+ this.messageHandler = messageHandler;++ messageHandler.on('test', function transportTest(supportTypedArray) {+ if (supportTypedArray) {+ this.worker = worker;+ this.setupMessageHandler(messageHandler);+ } else {+ globalScope.PDFJS.disableWorker = true;+ this.setupFakeWorker();+ }+ workerInitializedPromise.resolve();+ }.bind(this));++ var testObj = new Uint8Array(1);+ // Some versions of Opera throw a DATA_CLONE_ERR on+ // serializing the typed array.+ messageHandler.send('test', testObj);+ return;+ } catch (e) {+ info('The worker has been disabled.');+ }+ }+ // Either workers are disabled, not supported or have thrown an exception.+ // Thus, we fallback to a faked worker.+ globalScope.PDFJS.disableWorker = true;+ this.setupFakeWorker();+ workerInitializedPromise.resolve();}- PostScriptEvaluator.prototype = {- execute: function PostScriptEvaluator_execute(initialStack) {- var stack = new PostScriptStack(initialStack);- var counter = 0;- var operators = this.operators;- var length = operators.length;- var operator, a, b;- while (counter < length) {- operator = operators[counter++];- if (typeof operator == 'number') {- // Operator is really an operand and should be pushed to the stack.- stack.push(operator);- continue;- }- switch (operator) {- // non standard ps operators- case 'jz': // jump if false- b = stack.pop();- a = stack.pop();- if (!a) {- counter = b;- }- break;- case 'j': // jump- a = stack.pop();- counter = a;- break;-- // all ps operators in alphabetical order (excluding if/ifelse)- case 'abs':- a = stack.pop();- stack.push(Math.abs(a));- break;- case 'add':- b = stack.pop();- a = stack.pop();- stack.push(a + b);- break;- case 'and':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a && b);- } else {- stack.push(a & b);- }- break;- case 'atan':- a = stack.pop();- stack.push(Math.atan(a));- break;- case 'bitshift':- b = stack.pop();- a = stack.pop();- if (a > 0) {- stack.push(a << b);- } else {- stack.push(a >> b);- }- break;- case 'ceiling':- a = stack.pop();- stack.push(Math.ceil(a));- break;- case 'copy':- a = stack.pop();- stack.copy(a);- break;- case 'cos':- a = stack.pop();- stack.push(Math.cos(a));- break;- case 'cvi':- a = stack.pop() | 0;- stack.push(a);- break;- case 'cvr':- // noop- break;- case 'div':- b = stack.pop();- a = stack.pop();- stack.push(a / b);- break;- case 'dup':- stack.copy(1);- break;- case 'eq':- b = stack.pop();- a = stack.pop();- stack.push(a == b);- break;- case 'exch':- stack.roll(2, 1);- break;- case 'exp':- b = stack.pop();- a = stack.pop();- stack.push(Math.pow(a, b));- break;- case 'false':- stack.push(false);- break;- case 'floor':- a = stack.pop();- stack.push(Math.floor(a));- break;- case 'ge':- b = stack.pop();- a = stack.pop();- stack.push(a >= b);- break;- case 'gt':- b = stack.pop();- a = stack.pop();- stack.push(a > b);- break;- case 'idiv':- b = stack.pop();- a = stack.pop();- stack.push((a / b) | 0);- break;- case 'index':- a = stack.pop();- stack.index(a);- break;- case 'le':- b = stack.pop();- a = stack.pop();- stack.push(a <= b);- break;- case 'ln':- a = stack.pop();- stack.push(Math.log(a));- break;- case 'log':- a = stack.pop();- stack.push(Math.log(a) / Math.LN10);- break;- case 'lt':- b = stack.pop();- a = stack.pop();- stack.push(a < b);- break;- case 'mod':- b = stack.pop();- a = stack.pop();- stack.push(a % b);- break;- case 'mul':- b = stack.pop();- a = stack.pop();- stack.push(a * b);- break;- case 'ne':- b = stack.pop();- a = stack.pop();- stack.push(a != b);- break;- case 'neg':- a = stack.pop();- stack.push(-b);- break;- case 'not':- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a && b);- } else {- stack.push(a & b);- }- break;- case 'or':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a || b);- } else {- stack.push(a | b);- }- break;- case 'pop':- stack.pop();- break;- case 'roll':- b = stack.pop();- a = stack.pop();- stack.roll(a, b);- break;- case 'round':- a = stack.pop();- stack.push(Math.round(a));- break;- case 'sin':- a = stack.pop();- stack.push(Math.sin(a));- break;- case 'sqrt':- a = stack.pop();- stack.push(Math.sqrt(a));- break;- case 'sub':- b = stack.pop();- a = stack.pop();- stack.push(a - b);- break;- case 'true':- stack.push(true);- break;- case 'truncate':- a = stack.pop();- a = a < 0 ? Math.ceil(a) : Math.floor(a);- stack.push(a);- break;- case 'xor':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a != b);- } else {- stack.push(a ^ b);- }- break;- default:- error('Unknown operator ' + operator);- break;+ WorkerTransport.prototype = {+ destroy: function WorkerTransport_destroy() {+ this.pageCache = [];+ this.pagePromises = [];+ var self = this;+ this.messageHandler.send('Terminate', null, function () {+ if (self.worker) {+ self.worker.terminate();}- }- return stack.stack;- }- };- return PostScriptEvaluator;-})();---var HIGHLIGHT_OFFSET = 4; // px-var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];--var Annotation = (function AnnotationClosure() {- // 12.5.5: Algorithm: Appearance streams- function getTransformMatrix(rect, bbox, matrix) {- var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);- var minX = bounds[0];- var minY = bounds[1];- var maxX = bounds[2];- var maxY = bounds[3];+ });+ },+ setupFakeWorker: function WorkerTransport_setupFakeWorker() {+ warn('Setting up fake worker.');+ // If we don't use a worker, just post/sendMessage to the main thread.+ var fakeWorker = {+ postMessage: function WorkerTransport_postMessage(obj) {+ fakeWorker.onmessage({data: obj});+ },+ terminate: function WorkerTransport_terminate() {}+ };- if (minX === maxX || minY === maxY) {- // From real-life file, bbox was [0, 0, 0, 0]. In this case,- // just apply the transform for rect- return [1, 0, 0, 1, rect[0], rect[1]];- }+ var messageHandler = new MessageHandler('main', fakeWorker);+ this.setupMessageHandler(messageHandler);- var xRatio = (rect[2] - rect[0]) / (maxX - minX);- var yRatio = (rect[3] - rect[1]) / (maxY - minY);- return [- xRatio,- 0,- 0,- yRatio,- rect[0] - minX * xRatio,- rect[1] - minY * yRatio- ];- }+ // If the main thread is our worker, setup the handling for the messages+ // the main thread sends to it self.+ WorkerMessageHandler.setup(messageHandler);+ },- function getDefaultAppearance(dict) {- var appearanceState = dict.get('AP');- if (!isDict(appearanceState)) {- return;- }+ setupMessageHandler:+ function WorkerTransport_setupMessageHandler(messageHandler) {+ this.messageHandler = messageHandler;- var appearance;- var appearances = appearanceState.get('N');- if (isDict(appearances)) {- var as = dict.get('AS');- if (as && appearances.has(as.name)) {- appearance = appearances.get(as.name);+ function updatePassword(password) {+ messageHandler.send('UpdatePassword', password);}- } else {- appearance = appearances;- }- return appearance;- }-- function Annotation(params) {- if (params.data) {- this.data = params.data;- return;- }- var dict = params.dict;- var data = this.data = {};+ var pdfDataRangeTransport = this.pdfDataRangeTransport;+ if (pdfDataRangeTransport) {+ pdfDataRangeTransport.addRangeListener(function(begin, chunk) {+ messageHandler.send('OnDataRange', {+ begin: begin,+ chunk: chunk+ });+ });- data.subtype = dict.get('Subtype').name;- var rect = dict.get('Rect') || [0, 0, 0, 0];- data.rect = Util.normalizeRect(rect);- data.annotationFlags = dict.get('F');+ pdfDataRangeTransport.addProgressListener(function(loaded) {+ messageHandler.send('OnDataProgress', {+ loaded: loaded+ });+ });- var color = dict.get('C');- if (isArray(color) && color.length === 3) {- // TODO(mack): currently only supporting rgb; need support different- // colorspaces- data.color = color;- } else {- data.color = [0, 0, 0];- }+ messageHandler.on('RequestDataRange',+ function transportDataRange(data) {+ pdfDataRangeTransport.requestDataRange(data.begin, data.end);+ }, this);+ }++ messageHandler.on('GetDoc', function transportDoc(data) {+ var pdfInfo = data.pdfInfo;+ var pdfDocument = new PDFDocumentProxy(pdfInfo, this);+ this.pdfDocument = pdfDocument;+ this.workerReadyPromise.resolve(pdfDocument);+ }, this);++ messageHandler.on('NeedPassword', function transportPassword(data) {+ if (this.passwordCallback) {+ return this.passwordCallback(updatePassword,+ PasswordResponses.NEED_PASSWORD);+ }+ this.workerReadyPromise.reject(data.exception.message, data.exception);+ }, this);++ messageHandler.on('IncorrectPassword', function transportBadPass(data) {+ if (this.passwordCallback) {+ return this.passwordCallback(updatePassword,+ PasswordResponses.INCORRECT_PASSWORD);+ }+ this.workerReadyPromise.reject(data.exception.message, data.exception);+ }, this);++ messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {+ this.workerReadyPromise.reject(data.exception.name, data.exception);+ }, this);++ messageHandler.on('MissingPDF', function transportMissingPDF(data) {+ this.workerReadyPromise.reject(data.exception.message, data.exception);+ }, this);++ messageHandler.on('UnknownError', function transportUnknownError(data) {+ this.workerReadyPromise.reject(data.exception.message, data.exception);+ }, this);++ messageHandler.on('GetPage', function transportPage(data) {+ var pageInfo = data.pageInfo;+ var page = new PDFPageProxy(pageInfo, this);+ this.pageCache[pageInfo.pageIndex] = page;+ var promise = this.pagePromises[pageInfo.pageIndex];+ promise.resolve(page);+ }, this);++ messageHandler.on('GetAnnotations', function transportAnnotations(data) {+ var annotations = data.annotations;+ var promise = this.pageCache[data.pageIndex].annotationsPromise;+ promise.resolve(annotations);+ }, this);++ messageHandler.on('RenderPage', function transportRender(data) {+ var page = this.pageCache[data.pageIndex];+ var depFonts = data.depFonts;++ page.stats.timeEnd('Page Request');+ page.startRenderingFromOperatorList(data.operatorList, depFonts);+ }, this);++ messageHandler.on('commonobj', function transportObj(data) {+ var id = data[0];+ var type = data[1];+ if (this.commonObjs.hasData(id))+ return;- // Some types of annotations have border style dict which has more- // info than the border array- if (dict.has('BS')) {- var borderStyle = dict.get('BS');- data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;- } else {- var borderArray = dict.get('Border') || [0, 0, 1];- data.borderWidth = borderArray[2] || 0;-- // TODO: implement proper support for annotations with line dash patterns.- var dashArray = borderArray[3];- if (data.borderWidth > 0 && dashArray && isArray(dashArray)) {- var dashArrayLength = dashArray.length;- if (dashArrayLength > 0) {- // According to the PDF specification: the elements in a dashArray- // shall be numbers that are nonnegative and not all equal to zero.- var isInvalid = false;- var numPositive = 0;- for (var i = 0; i < dashArrayLength; i++) {- var validNumber = (+dashArray[i] >= 0);- if (!validNumber) {- isInvalid = true;- break;- } else if (dashArray[i] > 0) {- numPositive++;- }- }- if (isInvalid || numPositive === 0) {- data.borderWidth = 0;- }+ switch (type) {+ case 'Font':+ var exportedData = data[2];++ // At this point, only the font object is created but the font is+ // not yet attached to the DOM. This is done in `FontLoader.bind`.+ var font;+ if ('error' in exportedData)+ font = new ErrorFont(exportedData.error);+ else+ font = new Font(exportedData);+ this.commonObjs.resolve(id, font);+ break;+ default:+ error('Got unknown common object type ' + type);}- }- }-- this.appearance = getDefaultAppearance(dict);- data.hasAppearance = !!this.appearance;- }+ }, this);- Annotation.prototype = {+ messageHandler.on('obj', function transportObj(data) {+ var id = data[0];+ var pageIndex = data[1];+ var type = data[2];+ var pageProxy = this.pageCache[pageIndex];+ if (pageProxy.objs.hasData(id))+ return;- getData: function Annotation_getData() {- return this.data;- },+ switch (type) {+ case 'JpegStream':+ var imageData = data[3];+ loadJpegStream(id, imageData, pageProxy.objs);+ break;+ case 'Image':+ var imageData = data[3];+ pageProxy.objs.resolve(id, imageData);++ // heuristics that will allow not to store large data+ var MAX_IMAGE_SIZE_TO_STORE = 8000000;+ if ('data' in imageData &&+ imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {+ pageProxy.cleanupAfterRender = true;+ }+ break;+ default:+ error('Got unknown object type ' + type);+ }+ }, this);- hasHtml: function Annotation_hasHtml() {- return false;+ messageHandler.on('DocProgress', function transportDocProgress(data) {+ if (this.progressCallback) {+ this.progressCallback({+ loaded: data.loaded,+ total: data.total+ });+ }+ }, this);++ messageHandler.on('DocError', function transportDocError(data) {+ this.workerReadyPromise.reject(data);+ }, this);++ messageHandler.on('PageError', function transportError(data) {+ var page = this.pageCache[data.pageNum - 1];+ if (page.displayReadyPromise)+ page.displayReadyPromise.reject(data.error);+ else+ error(data.error);+ }, this);++ messageHandler.on('JpegDecode', function(data, promise) {+ var imageData = data[0];+ var components = data[1];+ if (components != 3 && components != 1)+ error('Only 3 component or 1 component can be returned');++ var img = new Image();+ img.onload = (function messageHandler_onloadClosure() {+ var width = img.width;+ var height = img.height;+ var size = width * height;+ var rgbaLength = size * 4;+ var buf = new Uint8Array(size * components);+ var tmpCanvas = createScratchCanvas(width, height);+ var tmpCtx = tmpCanvas.getContext('2d');+ tmpCtx.drawImage(img, 0, 0);+ var data = tmpCtx.getImageData(0, 0, width, height).data;++ if (components == 3) {+ for (var i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {+ buf[j] = data[i];+ buf[j + 1] = data[i + 1];+ buf[j + 2] = data[i + 2];+ }+ } else if (components == 1) {+ for (var i = 0, j = 0; i < rgbaLength; i += 4, j++) {+ buf[j] = data[i];+ }+ }+ promise.resolve({ data: buf, width: width, height: height});+ }).bind(this);+ var src = 'data:image/jpeg;base64,' + window.btoa(imageData);+ img.src = src;+ });},- getHtmlElement: function Annotation_getHtmlElement(commonObjs) {- throw new NotImplementedException(- 'getHtmlElement() should be implemented in subclass');+ fetchDocument: function WorkerTransport_fetchDocument(source) {+ source.disableAutoFetch = PDFJS.disableAutoFetch;+ source.chunkedViewerLoading = !!this.pdfDataRangeTransport;+ this.messageHandler.send('GetDocRequest', {+ source: source,+ disableRange: PDFJS.disableRange+ });},- // TODO(mack): Remove this, it's not really that helpful.- getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect,- borderWidth) {- assert(!isWorker,- 'getEmptyContainer() should be called from main thread');-- var bWidth = borderWidth || 0;-- rect = rect || this.data.rect;- var element = document.createElement(tagName);- element.style.borderWidth = bWidth + 'px';- var width = rect[2] - rect[0] - 2 * bWidth;- var height = rect[3] - rect[1] - 2 * bWidth;- element.style.width = width + 'px';- element.style.height = height + 'px';- return element;+ getData: function WorkerTransport_getData(promise) {+ this.messageHandler.send('GetData', null, function(data) {+ promise.resolve(data);+ });},- isInvisible: function Annotation_isInvisible() {- var data = this.data;- if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {- return false;- } else {- return !!(data &&- data.annotationFlags && // Default: not invisible- data.annotationFlags & 0x1); // Invisible- }+ dataLoaded: function WorkerTransport_dataLoaded() {+ var promise = new PDFJS.Promise();+ this.messageHandler.send('DataLoaded', null, function(args) {+ promise.resolve(args);+ });+ return promise;},- isViewable: function Annotation_isViewable() {- var data = this.data;- return !!(!this.isInvisible() &&- data &&- (!data.annotationFlags ||- !(data.annotationFlags & 0x22)) && // Hidden or NoView- data.rect); // rectangle is nessessary+ getPage: function WorkerTransport_getPage(pageNumber, promise) {+ var pageIndex = pageNumber - 1;+ if (pageIndex in this.pagePromises)+ return this.pagePromises[pageIndex];+ var promise = new PDFJS.Promise('Page ' + pageNumber);+ this.pagePromises[pageIndex] = promise;+ this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex });+ return promise;},- isPrintable: function Annotation_isPrintable() {- var data = this.data;- return !!(!this.isInvisible() &&- data &&- data.annotationFlags && // Default: not printable- data.annotationFlags & 0x4 && // Print- data.rect); // rectangle is nessessary+ getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {+ this.messageHandler.send('GetAnnotationsRequest',+ { pageIndex: pageIndex });},- loadResources: function(keys) {- var promise = new LegacyPromise();- this.appearance.dict.getAsync('Resources').then(function(resources) {- if (!resources) {- promise.resolve();- return;+ getDestinations: function WorkerTransport_getDestinations() {+ var promise = new PDFJS.Promise();+ this.messageHandler.send('GetDestinations', null,+ function transportDestinations(destinations) {+ promise.resolve(destinations);}- var objectLoader = new ObjectLoader(resources.map,- keys,- resources.xref);- objectLoader.load().then(function() {- promise.resolve(resources);- });- }.bind(this));-+ );return promise;- },+ }+ };+ return WorkerTransport;- getOperatorList: function Annotation_getOperatorList(evaluator) {+})();- var promise = new LegacyPromise();- if (!this.appearance) {- promise.resolve(new OperatorList());- return promise;- }+// <canvas> contexts store most of the state we need natively.+// However, PDF needs a bit more state, which we store here.- var data = this.data;+var TextRenderingMode = {+ FILL: 0,+ STROKE: 1,+ FILL_STROKE: 2,+ INVISIBLE: 3,+ FILL_ADD_TO_PATH: 4,+ STROKE_ADD_TO_PATH: 5,+ FILL_STROKE_ADD_TO_PATH: 6,+ ADD_TO_PATH: 7,+ FILL_STROKE_MASK: 3,+ ADD_TO_PATH_FLAG: 4+};- var appearanceDict = this.appearance.dict;- var resourcesPromise = this.loadResources([- 'ExtGState',- 'ColorSpace',- 'Pattern',- 'Shading',- 'XObject',- 'Font'- // ProcSet- // Properties- ]);- var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];- var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];- var transform = getTransformMatrix(data.rect, bbox, matrix);+// Minimal font size that would be used during canvas fillText operations.+var MIN_FONT_SIZE = 16;- var border = data.border;+var COMPILE_TYPE3_GLYPHS = true;- resourcesPromise.then(function(resources) {- var opList = new OperatorList();- opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);- evaluator.getOperatorList(this.appearance, resources, opList);- opList.addOp(OPS.endAnnotation, []);- promise.resolve(opList);+function createScratchCanvas(width, height) {+ var canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;+ return canvas;+}- this.appearance.reset();- }.bind(this));+function addContextCurrentTransform(ctx) {+ // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.+ if (!ctx.mozCurrentTransform) {+ // Store the original context+ ctx._scaleX = ctx._scaleX || 1.0;+ ctx._scaleY = ctx._scaleY || 1.0;+ ctx._originalSave = ctx.save;+ ctx._originalRestore = ctx.restore;+ ctx._originalRotate = ctx.rotate;+ ctx._originalScale = ctx.scale;+ ctx._originalTranslate = ctx.translate;+ ctx._originalTransform = ctx.transform;+ ctx._originalSetTransform = ctx.setTransform;++ ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];+ ctx._transformStack = [];++ Object.defineProperty(ctx, 'mozCurrentTransform', {+ get: function getCurrentTransform() {+ return this._transformMatrix;+ }+ });- return promise;- }- };+ Object.defineProperty(ctx, 'mozCurrentTransformInverse', {+ get: function getCurrentTransformInverse() {+ // Calculation done using WolframAlpha:+ // http://www.wolframalpha.com/input/?+ // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}- Annotation.getConstructor =- function Annotation_getConstructor(subtype, fieldType) {+ var m = this._transformMatrix;+ var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];- if (!subtype) {- return;- }+ var ad_bc = a * d - b * c;+ var bc_ad = b * c - a * d;- // TODO(mack): Implement FreeText annotations- if (subtype === 'Link') {- return LinkAnnotation;- } else if (subtype === 'Text') {- return TextAnnotation;- } else if (subtype === 'Widget') {- if (!fieldType) {- return;+ return [+ d / ad_bc,+ b / bc_ad,+ c / bc_ad,+ a / ad_bc,+ (d * e - c * f) / bc_ad,+ (b * e - a * f) / ad_bc+ ];}+ });- if (fieldType === 'Tx') {- return TextWidgetAnnotation;- } else {- return WidgetAnnotation;+ ctx.save = function ctxSave() {+ var old = this._transformMatrix;+ this._transformStack.push(old);+ this._transformMatrix = old.slice(0, 6);++ this._originalSave();+ };++ ctx.restore = function ctxRestore() {+ var prev = this._transformStack.pop();+ if (prev) {+ this._transformMatrix = prev;+ this._originalRestore();}- } else {- return Annotation;- }- };+ };- // TODO(mack): Support loading annotation from data- Annotation.fromData = function Annotation_fromData(data) {- var subtype = data.subtype;- var fieldType = data.fieldType;- var Constructor = Annotation.getConstructor(subtype, fieldType);- if (Constructor) {- return new Constructor({ data: data });- }- };+ ctx.translate = function ctxTranslate(x, y) {+ var m = this._transformMatrix;+ m[4] = m[0] * x + m[2] * y + m[4];+ m[5] = m[1] * x + m[3] * y + m[5];- Annotation.fromRef = function Annotation_fromRef(xref, ref) {+ this._originalTranslate(x, y);+ };- var dict = xref.fetchIfRef(ref);- if (!isDict(dict)) {- return;- }+ ctx.scale = function ctxScale(x, y) {+ var m = this._transformMatrix;+ m[0] = m[0] * x;+ m[1] = m[1] * x;+ m[2] = m[2] * y;+ m[3] = m[3] * y;- var subtype = dict.get('Subtype');- subtype = isName(subtype) ? subtype.name : '';- if (!subtype) {- return;- }+ this._originalScale(x, y);+ };- var fieldType = Util.getInheritableProperty(dict, 'FT');- fieldType = isName(fieldType) ? fieldType.name : '';+ ctx.transform = function ctxTransform(a, b, c, d, e, f) {+ var m = this._transformMatrix;+ this._transformMatrix = [+ m[0] * a + m[2] * b,+ m[1] * a + m[3] * b,+ m[0] * c + m[2] * d,+ m[1] * c + m[3] * d,+ m[0] * e + m[2] * f + m[4],+ m[1] * e + m[3] * f + m[5]+ ];- var Constructor = Annotation.getConstructor(subtype, fieldType);- if (!Constructor) {- return;- }+ ctx._originalTransform(a, b, c, d, e, f);+ };- var params = {- dict: dict,- ref: ref,+ ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {+ this._transformMatrix = [a, b, c, d, e, f];++ ctx._originalSetTransform(a, b, c, d, e, f);};- var annotation = new Constructor(params);+ ctx.rotate = function ctxRotate(angle) {+ var cosValue = Math.cos(angle);+ var sinValue = Math.sin(angle);++ var m = this._transformMatrix;+ this._transformMatrix = [+ m[0] * cosValue + m[2] * sinValue,+ m[1] * cosValue + m[3] * sinValue,+ m[0] * (-sinValue) + m[2] * cosValue,+ m[1] * (-sinValue) + m[3] * cosValue,+ m[4],+ m[5]+ ];- if (annotation.isViewable() || annotation.isPrintable()) {- return annotation;- } else {- warn('unimplemented annotation type: ' + subtype);+ this._originalRotate(angle);+ };+ }+}++var CachedCanvases = (function CachedCanvasesClosure() {+ var cache = {};+ return {+ getCanvas: function CachedCanvases_getCanvas(id, width, height) {+ var canvas;+ if (id in cache) {+ canvas = cache[id];+ canvas.width = width;+ canvas.height = height;+ // reset canvas transform for emulated mozCurrentTransform, if needed+ canvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);+ } else {+ canvas = createScratchCanvas(width, height);+ cache[id] = canvas;+ }+ return canvas;+ },+ clear: function () {+ cache = {};}};+})();- Annotation.appendToOperatorList = function Annotation_appendToOperatorList(- annotations, opList, pdfManager, partialEvaluator, intent) {-- function reject(e) {- annotationsReadyPromise.reject(e);+function compileType3Glyph(imgData) {+ var POINT_TO_PROCESS_LIMIT = 1000;++ var width = imgData.width, height = imgData.height;+ var i, j, j0, width1 = width + 1;+ var points = new Uint8Array(width1 * (height + 1));+ var POINT_TYPES =+ new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);+ // finding iteresting points: every point is located between mask pixels,+ // so there will be points of the (width + 1)x(height + 1) grid. Every point+ // will have flags assigned based on neighboring mask pixels:+ // 4 | 8+ // --P--+ // 2 | 1+ // We are interested only in points with the flags:+ // - outside corners: 1, 2, 4, 8;+ // - inside corners: 7, 11, 13, 14;+ // - and, intersections: 5, 10.+ var pos = 3, data = imgData.data, lineSize = width * 4, count = 0;+ if (data[3] !== 0) {+ points[0] = 1;+ ++count;+ }+ for (j = 1; j < width; j++) {+ if (data[pos] !== data[pos + 4]) {+ points[j] = data[pos] ? 2 : 1;+ ++count;+ }+ pos += 4;+ }+ if (data[pos] !== 0) {+ points[j] = 2;+ ++count;+ }+ pos += 4;+ for (i = 1; i < height; i++) {+ j0 = i * width1;+ if (data[pos - lineSize] !== data[pos]) {+ points[j0] = data[pos] ? 1 : 8;+ ++count;+ }+ // 'sum' is the position of the current pixel configuration in the 'TYPES'+ // array (in order 8-1-2-4, so we can use '>>2' to shift the column).+ var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);+ for (j = 1; j < width; j++) {+ sum = (sum >> 2) + (data[pos + 4] ? 4 : 0) ++ (data[pos - lineSize + 4] ? 8 : 0);+ if (POINT_TYPES[sum]) {+ points[j0 + j] = POINT_TYPES[sum];+ ++count;+ }+ pos += 4;+ }+ if (data[pos - lineSize] !== data[pos]) {+ points[j0 + j] = data[pos] ? 2 : 4;+ ++count;+ }+ pos += 4;++ if (count > POINT_TO_PROCESS_LIMIT) {+ return null;}+ }- var annotationsReadyPromise = new LegacyPromise();-- var annotationPromises = [];- for (var i = 0, n = annotations.length; i < n; ++i) {- if (intent === 'display' && annotations[i].isViewable() ||- intent === 'print' && annotations[i].isPrintable()) {- annotationPromises.push(- annotations[i].getOperatorList(partialEvaluator));- }+ pos -= lineSize;+ j0 = i * width1;+ if (data[pos] !== 0) {+ points[j0] = 8;+ ++count;+ }+ for (j = 1; j < width; j++) {+ if (data[pos] !== data[pos + 4]) {+ points[j0 + j] = data[pos] ? 4 : 8;+ ++count;}- Promise.all(annotationPromises).then(function(datas) {- opList.addOp(OPS.beginAnnotations, []);- for (var i = 0, n = datas.length; i < n; ++i) {- var annotOpList = datas[i];- opList.addOpList(annotOpList);- }- opList.addOp(OPS.endAnnotations, []);- annotationsReadyPromise.resolve();- }, reject);+ pos += 4;+ }+ if (data[pos] !== 0) {+ points[j0 + j] = 4;+ ++count;+ }+ if (count > POINT_TO_PROCESS_LIMIT) {+ return null;+ }- return annotationsReadyPromise;+ // building outlines+ var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);+ var outlines = [];+ for (i = 0; count && i <= height; i++) {+ var p = i * width1;+ var end = p + width;+ while (p < end && !points[p]) {+ p++;+ }+ if (p === end) {+ continue;+ }+ var coords = [p % width1, i];++ var type = points[p], p0 = p, pp;+ do {+ var step = steps[type];+ do { p += step; } while (!points[p]);++ pp = points[p];+ if (pp !== 5 && pp !== 10) {+ // set new direction+ type = pp;+ // delete mark+ points[p] = 0;+ } else { // type is 5 or 10, ie, a crossing+ // set new direction+ type = pp & ((0x33 * type) >> 4);+ // set new type for "future hit"+ points[p] &= (type >> 2 | type << 2);+ }++ coords.push(p % width1);+ coords.push((p / width1) | 0);+ --count;+ } while (p0 !== p);+ outlines.push(coords);+ --i;+ }++ var drawOutline = function(c) {+ c.save();+ // the path shall be painted in [0..1]x[0..1] space+ c.scale(1 / width, -1 / height);+ c.translate(0, -height);+ c.beginPath();+ for (var i = 0, ii = outlines.length; i < ii; i++) {+ var o = outlines[i];+ c.moveTo(o[0], o[1]);+ for (var j = 2, jj = o.length; j < jj; j += 2) {+ c.lineTo(o[j], o[j+1]);+ }+ }+ c.fill();+ c.beginPath();+ c.restore();};- return Annotation;-})();-PDFJS.Annotation = Annotation;-+ return drawOutline;+}-var WidgetAnnotation = (function WidgetAnnotationClosure() {+var CanvasExtraState = (function CanvasExtraStateClosure() {+ function CanvasExtraState(old) {+ // Are soft masks and alpha values shapes or opacities?+ this.alphaIsShape = false;+ this.fontSize = 0;+ this.fontSizeScale = 1;+ this.textMatrix = IDENTITY_MATRIX;+ this.fontMatrix = FONT_IDENTITY_MATRIX;+ this.leading = 0;+ // Current point (in user coordinates)+ this.x = 0;+ this.y = 0;+ // Start of text line (in text coordinates)+ this.lineX = 0;+ this.lineY = 0;+ // Character and word spacing+ this.charSpacing = 0;+ this.wordSpacing = 0;+ this.textHScale = 1;+ this.textRenderingMode = TextRenderingMode.FILL;+ this.textRise = 0;+ // Color spaces+ this.fillColorSpace = new DeviceGrayCS();+ this.fillColorSpaceObj = null;+ this.strokeColorSpace = new DeviceGrayCS();+ this.strokeColorSpaceObj = null;+ this.fillColorObj = null;+ this.strokeColorObj = null;+ // Default fore and background colors+ this.fillColor = '#000000';+ this.strokeColor = '#000000';+ // Note: fill alpha applies to all non-stroking operations+ this.fillAlpha = 1;+ this.strokeAlpha = 1;+ this.lineWidth = 1;+ this.paintFormXObjectDepth = 0;++ this.old = old;+ }++ CanvasExtraState.prototype = {+ clone: function CanvasExtraState_clone() {+ return Object.create(this);+ },+ setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {+ this.x = x;+ this.y = y;+ }+ };+ return CanvasExtraState;+})();- function WidgetAnnotation(params) {- Annotation.call(this, params);+var CanvasGraphics = (function CanvasGraphicsClosure() {+ // Defines the time the executeOperatorList is going to be executing+ // before it stops and shedules a continue of execution.+ var EXECUTION_TIME = 15;- if (params.data) {+ function CanvasGraphics(canvasCtx, commonObjs, objs, textLayer, imageLayer) {+ this.ctx = canvasCtx;+ this.current = new CanvasExtraState();+ this.stateStack = [];+ this.pendingClip = null;+ this.pendingEOFill = false;+ this.res = null;+ this.xobjs = null;+ this.commonObjs = commonObjs;+ this.objs = objs;+ this.textLayer = textLayer;+ this.imageLayer = imageLayer;+ this.groupStack = [];+ this.processingType3 = null;+ if (canvasCtx) {+ addContextCurrentTransform(canvasCtx);+ }+ }++ function putBinaryImageData(ctx, imgData) {+ if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {+ ctx.putImageData(imgData, 0, 0);return;}- var dict = params.dict;- var data = this.data;+ var tmpImgData = ctx.createImageData(imgData.width, imgData.height);++ var data = imgData.data;+ var tmpImgDataPixels = tmpImgData.data;+ if ('set' in tmpImgDataPixels)+ tmpImgDataPixels.set(data);+ else {+ // Copy over the imageData pixel by pixel.+ for (var i = 0, ii = tmpImgDataPixels.length; i < ii; i++)+ tmpImgDataPixels[i] = data[i];+ }++ ctx.putImageData(tmpImgData, 0, 0);+ }++ function copyCtxState(sourceCtx, destCtx) {+ var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',+ 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',+ 'globalCompositeOperation', 'font'];+ for (var i = 0, ii = properties.length; i < ii; i++) {+ var property = properties[i];+ if (property in sourceCtx) {+ destCtx[property] = sourceCtx[property];+ }+ }+ if ('setLineDash' in sourceCtx) {+ destCtx.setLineDash(sourceCtx.getLineDash());+ destCtx.lineDashOffset = sourceCtx.lineDashOffset;+ } else if ('mozDash' in sourceCtx) {+ destCtx.mozDash = sourceCtx.mozDash;+ destCtx.mozDashOffset = sourceCtx.mozDashOffset;+ }+ }++ var LINE_CAP_STYLES = ['butt', 'round', 'square'];+ var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];+ var NORMAL_CLIP = {};+ var EO_CLIP = {};++ CanvasGraphics.prototype = {+ slowCommands: {+ 'stroke': true,+ 'closeStroke': true,+ 'fill': true,+ 'eoFill': true,+ 'fillStroke': true,+ 'eoFillStroke': true,+ 'closeFillStroke': true,+ 'closeEOFillStroke': true,+ 'showText': true,+ 'showSpacedText': true,+ 'setStrokeColorSpace': true,+ 'setFillColorSpace': true,+ 'setStrokeColor': true,+ 'setStrokeColorN': true,+ 'setFillColor': true,+ 'setFillColorN': true,+ 'setStrokeGray': true,+ 'setFillGray': true,+ 'setStrokeRGBColor': true,+ 'setFillRGBColor': true,+ 'setStrokeCMYKColor': true,+ 'setFillCMYKColor': true,+ 'paintJpegXObject': true,+ 'paintImageXObject': true,+ 'paintInlineImageXObject': true,+ 'paintInlineImageXObjectGroup': true,+ 'paintImageMaskXObject': true,+ 'paintImageMaskXObjectGroup': true,+ 'shadingFill': true+ },++ beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {+ // For pdfs that use blend modes we have to clear the canvas else certain+ // blend modes can look wrong since we'd be blending with a white+ // backdrop. The problem with a transparent backdrop though is we then+ // don't get sub pixel anti aliasing on text, so we fill with white if+ // we can.+ var width = this.ctx.canvas.width;+ var height = this.ctx.canvas.height;+ if (transparency) {+ this.ctx.clearRect(0, 0, width, height);+ } else {+ this.ctx.mozOpaque = true;+ this.ctx.save();+ this.ctx.fillStyle = 'rgb(255, 255, 255)';+ this.ctx.fillRect(0, 0, width, height);+ this.ctx.restore();+ }- data.fieldValue = stringToPDFString(- Util.getInheritableProperty(dict, 'V') || '');- data.alternativeText = stringToPDFString(dict.get('TU') || '');- data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';- var fieldType = Util.getInheritableProperty(dict, 'FT');- data.fieldType = isName(fieldType) ? fieldType.name : '';- data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;- this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;+ var transform = viewport.transform;+ this.ctx.save();+ this.ctx.transform.apply(this.ctx, transform);- // Building the full field name by collecting the field and- // its ancestors 'T' data and joining them using '.'.- var fieldName = [];- var namedItem = dict;- var ref = params.ref;- while (namedItem) {- var parent = namedItem.get('Parent');- var parentRef = namedItem.getRaw('Parent');- var name = namedItem.get('T');- if (name) {- fieldName.unshift(stringToPDFString(name));- } else {- // The field name is absent, that means more than one field- // with the same name may exist. Replacing the empty name- // with the '`' plus index in the parent's 'Kids' array.- // This is not in the PDF spec but necessary to id the- // the input controls.- var kids = parent.get('Kids');- var j, jj;- for (j = 0, jj = kids.length; j < jj; j++) {- var kidRef = kids[j];- if (kidRef.num == ref.num && kidRef.gen == ref.gen) {- break;- }- }- fieldName.unshift('`' + j);+ if (this.textLayer) {+ this.textLayer.beginLayout();}- namedItem = parent;- ref = parentRef;- }- data.fullName = fieldName.join('.');- }+ if (this.imageLayer) {+ this.imageLayer.beginLayout();+ }+ },- var parent = Annotation.prototype;- Util.inherit(WidgetAnnotation, Annotation, {- isViewable: function WidgetAnnotation_isViewable() {- if (this.data.fieldType === 'Sig') {- warn('unimplemented annotation type: Widget signature');- return false;+ executeOperatorList: function CanvasGraphics_executeOperatorList(+ operatorList,+ executionStartIdx, continueCallback,+ stepper) {+ var argsArray = operatorList.argsArray;+ var fnArray = operatorList.fnArray;+ var i = executionStartIdx || 0;+ var argsArrayLen = argsArray.length;++ // Sometimes the OperatorList to execute is empty.+ if (argsArrayLen == i) {+ return i;}- return parent.isViewable.call(this);- }- });+ var executionEndIdx;+ var endTime = Date.now() + EXECUTION_TIME;- return WidgetAnnotation;-})();+ var commonObjs = this.commonObjs;+ var objs = this.objs;+ var fnName;+ var slowCommands = this.slowCommands;-var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {- function TextWidgetAnnotation(params) {- WidgetAnnotation.call(this, params);+ while (true) {+ if (stepper && i === stepper.nextBreakPoint) {+ stepper.breakIt(i, continueCallback);+ return i;+ }- if (params.data) {- return;- }+ fnName = fnArray[i];- this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');- }+ if (fnName !== 'dependency') {+ this[fnName].apply(this, argsArray[i]);+ } else {+ var deps = argsArray[i];+ for (var n = 0, nn = deps.length; n < nn; n++) {+ var depObjId = deps[n];+ var common = depObjId.substring(0, 2) == 'g_';++ // If the promise isn't resolved yet, add the continueCallback+ // to the promise and bail out.+ if (!common && !objs.isResolved(depObjId)) {+ objs.get(depObjId, continueCallback);+ return i;+ }+ if (common && !commonObjs.isResolved(depObjId)) {+ commonObjs.get(depObjId, continueCallback);+ return i;+ }+ }+ }- // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()- function setTextStyles(element, item, fontObj) {+ i++;- var style = element.style;- style.fontSize = item.fontSize + 'px';- style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';+ // If the entire operatorList was executed, stop as were done.+ if (i == argsArrayLen) {+ return i;+ }- if (!fontObj) {- return;- }+ // If the execution took longer then a certain amount of time, shedule+ // to continue exeution after a short delay.+ // However, this is only possible if a 'continueCallback' is passed in.+ if (continueCallback && slowCommands[fnName] && Date.now() > endTime) {+ setTimeout(continueCallback, 0);+ return i;+ }- style.fontWeight = fontObj.black ?- (fontObj.bold ? 'bolder' : 'bold') :- (fontObj.bold ? 'bold' : 'normal');- style.fontStyle = fontObj.italic ? 'italic' : 'normal';+ // If the operatorList isn't executed completely yet OR the execution+ // time was short enough, do another execution round.+ }+ },- var fontName = fontObj.loadedName;- var fontFamily = fontName ? '"' + fontName + '", ' : '';- // Use a reasonable default font if the font doesn't specify a fallback- var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';- style.fontFamily = fontFamily + fallbackName;- }+ endDrawing: function CanvasGraphics_endDrawing() {+ this.ctx.restore();+ CachedCanvases.clear();+ if (this.textLayer) {+ this.textLayer.endLayout();+ }+ if (this.imageLayer) {+ this.imageLayer.endLayout();+ }+ },- var parent = WidgetAnnotation.prototype;- Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {- hasHtml: function TextWidgetAnnotation_hasHtml() {- return !this.data.hasAppearance && !!this.data.fieldValue;+ // Graphics state+ setLineWidth: function CanvasGraphics_setLineWidth(width) {+ this.current.lineWidth = width;+ this.ctx.lineWidth = width;+ },+ setLineCap: function CanvasGraphics_setLineCap(style) {+ this.ctx.lineCap = LINE_CAP_STYLES[style];+ },+ setLineJoin: function CanvasGraphics_setLineJoin(style) {+ this.ctx.lineJoin = LINE_JOIN_STYLES[style];+ },+ setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {+ this.ctx.miterLimit = limit;+ },+ setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {+ var ctx = this.ctx;+ if ('setLineDash' in ctx) {+ ctx.setLineDash(dashArray);+ ctx.lineDashOffset = dashPhase;+ } else {+ ctx.mozDash = dashArray;+ ctx.mozDashOffset = dashPhase;+ }+ },+ setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {+ // Maybe if we one day fully support color spaces this will be important+ // for now we can ignore.+ // TODO set rendering intent?},+ setFlatness: function CanvasGraphics_setFlatness(flatness) {+ // There's no way to control this with canvas, but we can safely ignore.+ // TODO set flatness?+ },+ setGState: function CanvasGraphics_setGState(states) {+ for (var i = 0, ii = states.length; i < ii; i++) {+ var state = states[i];+ var key = state[0];+ var value = state[1];- getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');+ switch (key) {+ case 'LW':+ this.setLineWidth(value);+ break;+ case 'LC':+ this.setLineCap(value);+ break;+ case 'LJ':+ this.setLineJoin(value);+ break;+ case 'ML':+ this.setMiterLimit(value);+ break;+ case 'D':+ this.setDash(value[0], value[1]);+ break;+ case 'RI':+ this.setRenderingIntent(value);+ break;+ case 'FL':+ this.setFlatness(value);+ break;+ case 'Font':+ this.setFont(state[1], state[2]);+ break;+ case 'CA':+ this.current.strokeAlpha = state[1];+ break;+ case 'ca':+ this.current.fillAlpha = state[1];+ this.ctx.globalAlpha = state[1];+ break;+ case 'BM':+ if (value && value.name && (value.name !== 'Normal')) {+ var mode = value.name.replace(/([A-Z])/g,+ function(c) {+ return '-' + c.toLowerCase();+ }+ ).substring(1);+ this.ctx.globalCompositeOperation = mode;+ if (this.ctx.globalCompositeOperation !== mode) {+ warn('globalCompositeOperation "' + mode ++ '" is not supported');+ }+ } else {+ this.ctx.globalCompositeOperation = 'source-over';+ }+ break;+ }+ }+ },+ save: function CanvasGraphics_save() {+ this.ctx.save();+ var old = this.current;+ this.stateStack.push(old);+ this.current = old.clone();+ },+ restore: function CanvasGraphics_restore() {+ var prev = this.stateStack.pop();+ if (prev) {+ this.current = prev;+ this.ctx.restore();+ }+ },+ transform: function CanvasGraphics_transform(a, b, c, d, e, f) {+ this.ctx.transform(a, b, c, d, e, f);+ },- var item = this.data;+ // Path+ moveTo: function CanvasGraphics_moveTo(x, y) {+ this.ctx.moveTo(x, y);+ this.current.setCurrentPoint(x, y);+ },+ lineTo: function CanvasGraphics_lineTo(x, y) {+ this.ctx.lineTo(x, y);+ this.current.setCurrentPoint(x, y);+ },+ curveTo: function CanvasGraphics_curveTo(x1, y1, x2, y2, x3, y3) {+ this.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);+ this.current.setCurrentPoint(x3, y3);+ },+ curveTo2: function CanvasGraphics_curveTo2(x2, y2, x3, y3) {+ var current = this.current;+ this.ctx.bezierCurveTo(current.x, current.y, x2, y2, x3, y3);+ current.setCurrentPoint(x3, y3);+ },+ curveTo3: function CanvasGraphics_curveTo3(x1, y1, x3, y3) {+ this.curveTo(x1, y1, x3, y3, x3, y3);+ this.current.setCurrentPoint(x3, y3);+ },+ closePath: function CanvasGraphics_closePath() {+ this.ctx.closePath();+ },+ rectangle: function CanvasGraphics_rectangle(x, y, width, height) {+ this.ctx.rect(x, y, width, height);+ },+ stroke: function CanvasGraphics_stroke(consumePath) {+ consumePath = typeof consumePath !== 'undefined' ? consumePath : true;+ var ctx = this.ctx;+ var strokeColor = this.current.strokeColor;+ if (this.current.lineWidth === 0)+ ctx.lineWidth = this.getSinglePixelWidth();+ // For stroke we want to temporarily change the global alpha to the+ // stroking alpha.+ ctx.globalAlpha = this.current.strokeAlpha;+ if (strokeColor && strokeColor.hasOwnProperty('type') &&+ strokeColor.type === 'Pattern') {+ // for patterns, we transform to pattern space, calculate+ // the pattern, call stroke, and restore to user space+ ctx.save();+ ctx.strokeStyle = strokeColor.getPattern(ctx);+ ctx.stroke();+ ctx.restore();+ } else {+ ctx.stroke();+ }+ if (consumePath)+ this.consumePath();+ // Restore the global alpha to the fill alpha+ ctx.globalAlpha = this.current.fillAlpha;+ },+ closeStroke: function CanvasGraphics_closeStroke() {+ this.closePath();+ this.stroke();+ },+ fill: function CanvasGraphics_fill(consumePath) {+ consumePath = typeof consumePath !== 'undefined' ? consumePath : true;+ var ctx = this.ctx;+ var fillColor = this.current.fillColor;+ var needRestore = false;++ if (fillColor && fillColor.hasOwnProperty('type') &&+ fillColor.type === 'Pattern') {+ ctx.save();+ ctx.fillStyle = fillColor.getPattern(ctx);+ needRestore = true;+ }++ if (this.pendingEOFill) {+ if ('mozFillRule' in this.ctx) {+ this.ctx.mozFillRule = 'evenodd';+ this.ctx.fill();+ this.ctx.mozFillRule = 'nonzero';+ } else {+ try {+ this.ctx.fill('evenodd');+ } catch (ex) {+ // shouldn't really happen, but browsers might think differently+ this.ctx.fill();+ }+ }+ this.pendingEOFill = false;+ } else {+ this.ctx.fill();+ }- var element = this.getEmptyContainer('div');- element.style.display = 'table';+ if (needRestore) {+ ctx.restore();+ }+ if (consumePath) {+ this.consumePath();+ }+ },+ eoFill: function CanvasGraphics_eoFill() {+ this.pendingEOFill = true;+ this.fill();+ },+ fillStroke: function CanvasGraphics_fillStroke() {+ this.fill(false);+ this.stroke(false);- var content = document.createElement('div');- content.textContent = item.fieldValue;- var textAlignment = item.textAlignment;- content.style.textAlign = ['left', 'center', 'right'][textAlignment];- content.style.verticalAlign = 'middle';- content.style.display = 'table-cell';+ this.consumePath();+ },+ eoFillStroke: function CanvasGraphics_eoFillStroke() {+ this.pendingEOFill = true;+ this.fillStroke();+ },+ closeFillStroke: function CanvasGraphics_closeFillStroke() {+ this.closePath();+ this.fillStroke();+ },+ closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {+ this.pendingEOFill = true;+ this.closePath();+ this.fillStroke();+ },+ endPath: function CanvasGraphics_endPath() {+ this.consumePath();+ },- var fontObj = item.fontRefName ?- commonObjs.getData(item.fontRefName) : null;- var cssRules = setTextStyles(content, item, fontObj);+ // Clipping+ clip: function CanvasGraphics_clip() {+ this.pendingClip = NORMAL_CLIP;+ },+ eoClip: function CanvasGraphics_eoClip() {+ this.pendingClip = EO_CLIP;+ },- element.appendChild(content);+ // Text+ beginText: function CanvasGraphics_beginText() {+ this.current.textMatrix = IDENTITY_MATRIX;+ this.current.x = this.current.lineX = 0;+ this.current.y = this.current.lineY = 0;+ },+ endText: function CanvasGraphics_endText() {+ if (!('pendingTextPaths' in this)) {+ this.ctx.beginPath();+ return;+ }+ var paths = this.pendingTextPaths;+ var ctx = this.ctx;- return element;+ ctx.save();+ ctx.beginPath();+ for (var i = 0; i < paths.length; i++) {+ var path = paths[i];+ ctx.setTransform.apply(ctx, path.transform);+ ctx.translate(path.x, path.y);+ path.addToPath(ctx, path.fontSize);+ }+ ctx.restore();+ ctx.clip();+ ctx.beginPath();+ delete this.pendingTextPaths;+ },+ setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {+ this.current.charSpacing = spacing;+ },+ setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {+ this.current.wordSpacing = spacing;},+ setHScale: function CanvasGraphics_setHScale(scale) {+ this.current.textHScale = scale / 100;+ },+ setLeading: function CanvasGraphics_setLeading(leading) {+ this.current.leading = -leading;+ },+ setFont: function CanvasGraphics_setFont(fontRefName, size) {+ var fontObj = this.commonObjs.get(fontRefName);+ var current = this.current;- getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {- if (this.appearance) {- return Annotation.prototype.getOperatorList.call(this, evaluator);- }+ if (!fontObj)+ error('Can\'t find font for ' + fontRefName);- var promise = new LegacyPromise();- var opList = new OperatorList();- var data = this.data;+ current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix :+ FONT_IDENTITY_MATRIX;- // Even if there is an appearance stream, ignore it. This is the- // behaviour used by Adobe Reader.+ // A valid matrix needs all main diagonal elements to be non-zero+ // This also ensures we bypass FF bugzilla bug #719844.+ if (current.fontMatrix[0] === 0 ||+ current.fontMatrix[3] === 0) {+ warn('Invalid font matrix for font ' + fontRefName);+ }- var defaultAppearance = data.defaultAppearance;- if (!defaultAppearance) {- promise.resolve(opList);- return promise;+ // The spec for Tf (setFont) says that 'size' specifies the font 'scale',+ // and in some docs this can be negative (inverted x-y axes).+ if (size < 0) {+ size = -size;+ current.fontDirection = -1;+ } else {+ current.fontDirection = 1;}- // Include any font resources found in the default appearance+ this.current.font = fontObj;+ this.current.fontSize = size;- var stream = new Stream(stringToBytes(defaultAppearance));- evaluator.getOperatorList(stream, this.fieldResources, opList);- var appearanceFnArray = opList.fnArray;- var appearanceArgsArray = opList.argsArray;- var fnArray = [];- var argsArray = [];+ if (fontObj.coded)+ return; // we don't need ctx.font for Type3 fonts- // TODO(mack): Add support for stroke color- data.rgb = [0, 0, 0];- // TODO THIS DOESN'T MAKE ANY SENSE SINCE THE fnArray IS EMPTY!- for (var i = 0, n = fnArray.length; i < n; ++i) {- var fnId = appearanceFnArray[i];- var args = appearanceArgsArray[i];-- if (fnId === OPS.setFont) {- data.fontRefName = args[0];- var size = args[1];- if (size < 0) {- data.fontDirection = -1;- data.fontSize = -size;- } else {- data.fontDirection = 1;- data.fontSize = size;- }- } else if (fnId === OPS.setFillRGBColor) {- data.rgb = args;- } else if (fnId === OPS.setFillGray) {- var rgbValue = args[0] * 255;- data.rgb = [rgbValue, rgbValue, rgbValue];- }- }- promise.resolve(opList);- return promise;- }- });+ var name = fontObj.loadedName || 'sans-serif';+ var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :+ (fontObj.bold ? 'bold' : 'normal');- return TextWidgetAnnotation;-})();+ var italic = fontObj.italic ? 'italic' : 'normal';+ var typeface = '"' + name + '", ' + fontObj.fallbackName;-var InteractiveAnnotation = (function InteractiveAnnotationClosure() {- function InteractiveAnnotation(params) {- Annotation.call(this, params);- }+ // Some font backends cannot handle fonts below certain size.+ // Keeping the font at minimal size and using the fontSizeScale to change+ // the current transformation matrix before the fillText/strokeText.+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227+ var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;+ this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :+ size / MIN_FONT_SIZE;- Util.inherit(InteractiveAnnotation, Annotation, {- hasHtml: function InteractiveAnnotation_hasHtml() {- return true;+ var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;+ this.ctx.font = rule;+ },+ setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {+ this.current.textRenderingMode = mode;+ },+ setTextRise: function CanvasGraphics_setTextRise(rise) {+ this.current.textRise = rise;+ },+ moveText: function CanvasGraphics_moveText(x, y) {+ this.current.x = this.current.lineX += x;+ this.current.y = this.current.lineY += y;+ },+ setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {+ this.setLeading(-y);+ this.moveText(x, y);},+ setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {+ this.current.textMatrix = [a, b, c, d, e, f];- highlight: function InteractiveAnnotation_highlight() {- if (this.highlightElement &&- this.highlightElement.hasAttribute('hidden')) {- this.highlightElement.removeAttribute('hidden');- }+ this.current.x = this.current.lineX = 0;+ this.current.y = this.current.lineY = 0;+ },+ nextLine: function CanvasGraphics_nextLine() {+ this.moveText(0, this.current.leading);},+ applyTextTransforms: function CanvasGraphics_applyTextTransforms() {+ var ctx = this.ctx;+ var current = this.current;+ ctx.transform.apply(ctx, current.textMatrix);+ ctx.translate(current.x, current.y + current.textRise);+ if (current.fontDirection > 0) {+ ctx.scale(current.textHScale, -1);+ } else {+ ctx.scale(-current.textHScale, 1);+ }+ },+ createTextGeometry: function CanvasGraphics_createTextGeometry() {+ var geometry = {};+ var ctx = this.ctx;+ var font = this.current.font;+ var ctxMatrix = ctx.mozCurrentTransform;+ var a = ctxMatrix[0], b = ctxMatrix[1], c = ctxMatrix[2];+ var d = ctxMatrix[3], e = ctxMatrix[4], f = ctxMatrix[5];+ var sx = (a >= 0) ?+ Math.sqrt((a * a) + (b * b)) : -Math.sqrt((a * a) + (b * b));+ var sy = (d >= 0) ?+ Math.sqrt((c * c) + (d * d)) : -Math.sqrt((c * c) + (d * d));+ var angle = Math.atan2(b, a);+ var x = e;+ var y = f;+ geometry.x = x;+ geometry.y = y;+ geometry.hScale = sx;+ geometry.vScale = sy;+ geometry.angle = angle;+ geometry.spaceWidth = font.spaceWidth;+ geometry.fontName = font.loadedName;+ geometry.fontFamily = font.fallbackName;+ geometry.fontSize = this.current.fontSize;+ return geometry;+ },++ paintChar: function (character, x, y) {+ var ctx = this.ctx;+ var current = this.current;+ var font = current.font;+ var fontSize = current.fontSize / current.fontSizeScale;+ var textRenderingMode = current.textRenderingMode;+ var fillStrokeMode = textRenderingMode &+ TextRenderingMode.FILL_STROKE_MASK;+ var isAddToPathSet = !!(textRenderingMode &+ TextRenderingMode.ADD_TO_PATH_FLAG);++ var addToPath;+ if (font.disableFontFace || isAddToPathSet) {+ addToPath = font.renderer.getPathGenerator(character);+ }++ if (font.disableFontFace) {+ ctx.save();+ ctx.translate(x, y);+ ctx.beginPath();+ addToPath(ctx, fontSize);+ if (fillStrokeMode === TextRenderingMode.FILL ||+ fillStrokeMode === TextRenderingMode.FILL_STROKE) {+ ctx.fill();+ }+ if (fillStrokeMode === TextRenderingMode.STROKE ||+ fillStrokeMode === TextRenderingMode.FILL_STROKE) {+ ctx.stroke();+ }+ ctx.restore();+ } else {+ if (fillStrokeMode === TextRenderingMode.FILL ||+ fillStrokeMode === TextRenderingMode.FILL_STROKE) {+ ctx.fillText(character, x, y);+ }+ if (fillStrokeMode === TextRenderingMode.STROKE ||+ fillStrokeMode === TextRenderingMode.FILL_STROKE) {+ ctx.strokeText(character, x, y);+ }+ }- unhighlight: function InteractiveAnnotation_unhighlight() {- if (this.highlightElement &&- !this.highlightElement.hasAttribute('hidden')) {- this.highlightElement.setAttribute('hidden', true);+ if (isAddToPathSet) {+ var paths = this.pendingTextPaths || (this.pendingTextPaths = []);+ paths.push({+ transform: ctx.mozCurrentTransform,+ x: x,+ y: y,+ fontSize: fontSize,+ addToPath: addToPath+ });}},- initContainer: function InteractiveAnnotation_initContainer() {+ showText: function CanvasGraphics_showText(str, skipTextSelection) {+ var ctx = this.ctx;+ var current = this.current;+ var font = current.font;+ var glyphs = font.charsToGlyphs(str);+ var fontSize = current.fontSize;+ var fontSizeScale = current.fontSizeScale;+ var charSpacing = current.charSpacing;+ var wordSpacing = current.wordSpacing;+ var textHScale = current.textHScale * current.fontDirection;+ var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;+ var glyphsLength = glyphs.length;+ var textLayer = this.textLayer;+ var geom;+ var textSelection = textLayer && !skipTextSelection ? true : false;+ var canvasWidth = 0.0;+ var vertical = font.vertical;+ var defaultVMetrics = font.defaultVMetrics;++ // Type3 fonts - each glyph is a "mini-PDF"+ if (font.coded) {+ ctx.save();+ ctx.transform.apply(ctx, current.textMatrix);+ ctx.translate(current.x, current.y);++ ctx.scale(textHScale, 1);++ if (textSelection) {+ this.save();+ ctx.scale(1, -1);+ geom = this.createTextGeometry();+ this.restore();+ }+ for (var i = 0; i < glyphsLength; ++i) {- var item = this.data;- var rect = item.rect;+ var glyph = glyphs[i];+ if (glyph === null) {+ // word break+ this.ctx.translate(wordSpacing, 0);+ current.x += wordSpacing * textHScale;+ continue;+ }- var container = this.getEmptyContainer('section', rect, item.borderWidth);- container.style.backgroundColor = item.color;+ this.processingType3 = glyph;+ this.save();+ ctx.scale(fontSize, fontSize);+ ctx.transform.apply(ctx, fontMatrix);+ this.executeOperatorList(glyph.operatorList);+ this.restore();- var color = item.color;- var rgb = [];- for (var i = 0; i < 3; ++i) {- rgb[i] = Math.round(color[i] * 255);- }- item.colorCssRgb = Util.makeCssRgb(rgb);+ var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);+ var width = (transformed[0] * fontSize + charSpacing) *+ current.fontDirection;- var highlight = document.createElement('div');- highlight.className = 'annotationHighlight';- highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';- highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';- highlight.setAttribute('hidden', true);+ ctx.translate(width, 0);+ current.x += width * textHScale;- this.highlightElement = highlight;- container.appendChild(this.highlightElement);+ canvasWidth += width;+ }+ ctx.restore();+ this.processingType3 = null;+ } else {+ ctx.save();+ this.applyTextTransforms();- return container;- }- });+ var lineWidth = current.lineWidth;+ var a1 = current.textMatrix[0], b1 = current.textMatrix[1];+ var scale = Math.sqrt(a1 * a1 + b1 * b1);+ if (scale === 0 || lineWidth === 0)+ lineWidth = this.getSinglePixelWidth();+ else+ lineWidth /= scale;- return InteractiveAnnotation;-})();+ if (textSelection)+ geom = this.createTextGeometry();-var TextAnnotation = (function TextAnnotationClosure() {- function TextAnnotation(params) {- InteractiveAnnotation.call(this, params);+ if (fontSizeScale != 1.0) {+ ctx.scale(fontSizeScale, fontSizeScale);+ lineWidth /= fontSizeScale;+ }- if (params.data) {- return;- }+ ctx.lineWidth = lineWidth;- var dict = params.dict;- var data = this.data;+ var x = 0;+ for (var i = 0; i < glyphsLength; ++i) {+ var glyph = glyphs[i];+ if (glyph === null) {+ // word break+ x += current.fontDirection * wordSpacing;+ continue;+ }- var content = dict.get('Contents');- var title = dict.get('T');- data.content = stringToPDFString(content || '');- data.title = stringToPDFString(title || '');+ var restoreNeeded = false;+ var character = glyph.fontChar;+ var vmetric = glyph.vmetric || defaultVMetrics;+ if (vertical) {+ var vx = glyph.vmetric ? vmetric[1] : glyph.width * 0.5;+ vx = -vx * fontSize * current.fontMatrix[0];+ var vy = vmetric[2] * fontSize * current.fontMatrix[0];+ }+ var width = vmetric ? -vmetric[0] : glyph.width;+ var charWidth = width * fontSize * current.fontMatrix[0] ++ charSpacing * current.fontDirection;+ var accent = glyph.accent;++ var scaledX, scaledY, scaledAccentX, scaledAccentY;+ if (!glyph.disabled) {+ if (vertical) {+ scaledX = vx / fontSizeScale;+ scaledY = (x + vy) / fontSizeScale;+ } else {+ scaledX = x / fontSizeScale;+ scaledY = 0;+ }- if (data.hasAppearance) {- data.name = 'NoIcon';- } else {- data.name = dict.has('Name') ? dict.get('Name').name : 'Note';- }+ if (font.remeasure && width > 0) {+ // some standard fonts may not have the exact width, trying to+ // rescale per character+ var measuredWidth = ctx.measureText(character).width * 1000 /+ current.fontSize * current.fontSizeScale;+ var characterScaleX = width / measuredWidth;+ restoreNeeded = true;+ ctx.save();+ ctx.scale(characterScaleX, 1);+ scaledX /= characterScaleX;+ if (accent) {+ scaledAccentX /= characterScaleX;+ }+ }- if (dict.has('C')) {- data.hasBgColor = true;- }- }+ this.paintChar(character, scaledX, scaledY);+ if (accent) {+ scaledAccentX = scaledX + accent.offset.x / fontSizeScale;+ scaledAccentY = scaledY - accent.offset.y / fontSizeScale;+ this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);+ }+ }- var ANNOT_MIN_SIZE = 10;+ x += charWidth;- Util.inherit(TextAnnotation, InteractiveAnnotation, {+ canvasWidth += charWidth;- getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');+ if (restoreNeeded) {+ ctx.restore();+ }+ }+ if (vertical) {+ current.y -= x * textHScale;+ } else {+ current.x += x * textHScale;+ }+ ctx.restore();+ }++ if (textSelection) {+ geom.canvasWidth = canvasWidth;+ if (vertical) {+ var vmetric = font.defaultVMetrics;+ geom.x += vmetric[1] * fontSize * current.fontMatrix[0] /+ fontSizeScale * geom.hScale;+ geom.y += vmetric[2] * fontSize * current.fontMatrix[0] /+ fontSizeScale * geom.vScale;+ }+ this.textLayer.appendText(geom);+ }++ return canvasWidth;+ },+ showSpacedText: function CanvasGraphics_showSpacedText(arr) {+ var ctx = this.ctx;+ var current = this.current;+ var font = current.font;+ var fontSize = current.fontSize;+ // TJ array's number is independent from fontMatrix+ var textHScale = current.textHScale * 0.001 * current.fontDirection;+ var arrLength = arr.length;+ var textLayer = this.textLayer;+ var geom;+ var canvasWidth = 0.0;+ var textSelection = textLayer ? true : false;+ var vertical = font.vertical;+ var spacingAccumulator = 0;++ if (textSelection) {+ ctx.save();+ this.applyTextTransforms();+ geom = this.createTextGeometry();+ ctx.restore();+ }++ for (var i = 0; i < arrLength; ++i) {+ var e = arr[i];+ if (isNum(e)) {+ var spacingLength = -e * fontSize * textHScale;+ if (vertical) {+ current.y += spacingLength;+ } else {+ current.x += spacingLength;+ }- var item = this.data;- var rect = item.rect;+ if (textSelection)+ spacingAccumulator += spacingLength;+ } else if (isString(e)) {+ var shownCanvasWidth = this.showText(e, true);- // sanity check because of OOo-generated PDFs- if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {- rect[3] = rect[1] + ANNOT_MIN_SIZE;- }- if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {- rect[2] = rect[0] + (rect[3] - rect[1]); // make it square+ if (textSelection) {+ canvasWidth += spacingAccumulator + shownCanvasWidth;+ spacingAccumulator = 0;+ }+ } else {+ error('TJ array element ' + e + ' is not string or num');+ }}- var container = this.initContainer();- container.className = 'annotText';+ if (textSelection) {+ geom.canvasWidth = canvasWidth;+ if (vertical) {+ var fontSizeScale = current.fontSizeScale;+ var vmetric = font.defaultVMetrics;+ geom.x += vmetric[1] * fontSize * current.fontMatrix[0] /+ fontSizeScale * geom.hScale;+ geom.y += vmetric[2] * fontSize * current.fontMatrix[0] /+ fontSizeScale * geom.vScale;+ }+ this.textLayer.appendText(geom);+ }+ },+ nextLineShowText: function CanvasGraphics_nextLineShowText(text) {+ this.nextLine();+ this.showText(text);+ },+ nextLineSetSpacingShowText:+ function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing,+ charSpacing,+ text) {+ this.setWordSpacing(wordSpacing);+ this.setCharSpacing(charSpacing);+ this.nextLineShowText(text);+ },- var image = document.createElement('img');- image.style.height = container.style.height;- image.style.width = container.style.width;- var iconName = item.name;- image.src = PDFJS.imageResourcesPath + 'annotation-' +- iconName.toLowerCase() + '.svg';- image.alt = '[{{type}} Annotation]';- image.dataset.l10nId = 'text_annotation_type';- image.dataset.l10nArgs = JSON.stringify({type: iconName});+ // Type3 fonts+ setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {+ // We can safely ignore this since the width should be the same+ // as the width in the Widths array.+ },+ setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,+ yWidth,+ llx,+ lly,+ urx,+ ury) {+ // TODO According to the spec we're also suppose to ignore any operators+ // that set color or include images while processing this type3 font.+ this.rectangle(llx, lly, urx - llx, ury - lly);+ this.clip();+ this.endPath();+ },- var contentWrapper = document.createElement('div');- contentWrapper.className = 'annotTextContentWrapper';- contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';- contentWrapper.style.top = '-10px';+ // Color+ setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) {+ this.current.strokeColorSpace = ColorSpace.fromIR(raw);+ },+ setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) {+ this.current.fillColorSpace = ColorSpace.fromIR(raw);+ },+ setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) {+ var cs = this.current.strokeColorSpace;+ var rgbColor = cs.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.strokeStyle = color;+ this.current.strokeColor = color;+ },+ getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) {+ if (IR[0] == 'TilingPattern') {+ var args = IR[1];+ var base = cs.base;+ var color;+ if (base) {+ var baseComps = base.numComps;++ color = base.getRgb(args, 0);+ }+ var pattern = new TilingPattern(IR, color, this.ctx, this.objs,+ this.commonObjs);+ } else if (IR[0] == 'RadialAxial' || IR[0] == 'Dummy') {+ var pattern = Pattern.shadingFromIR(IR);+ } else {+ error('Unkown IR type ' + IR[0]);+ }+ return pattern;+ },+ setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {+ var cs = this.current.strokeColorSpace;- var content = document.createElement('div');- content.className = 'annotTextContent';- content.setAttribute('hidden', true);+ if (cs.name == 'Pattern') {+ this.current.strokeColor = this.getColorN_Pattern(arguments, cs);+ } else {+ this.setStrokeColor.apply(this, arguments);+ }+ },+ setFillColor: function CanvasGraphics_setFillColor(/*...*/) {+ var cs = this.current.fillColorSpace;+ var rgbColor = cs.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.fillStyle = color;+ this.current.fillColor = color;+ },+ setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {+ var cs = this.current.fillColorSpace;- var i, ii;- if (item.hasBgColor) {- var color = item.color;- var rgb = [];- for (i = 0; i < 3; ++i) {- // Enlighten the color (70%)- var c = Math.round(color[i] * 255);- rgb[i] = Math.round((255 - c) * 0.7) + c;- }- content.style.backgroundColor = Util.makeCssRgb(rgb);+ if (cs.name == 'Pattern') {+ this.current.fillColor = this.getColorN_Pattern(arguments, cs);+ } else {+ this.setFillColor.apply(this, arguments);}+ },+ setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {+ if (!(this.current.strokeColorSpace instanceof DeviceGrayCS))+ this.current.strokeColorSpace = new DeviceGrayCS();- var title = document.createElement('h1');- var text = document.createElement('p');- title.textContent = item.title;+ var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.strokeStyle = color;+ this.current.strokeColor = color;+ },+ setFillGray: function CanvasGraphics_setFillGray(gray) {+ if (!(this.current.fillColorSpace instanceof DeviceGrayCS))+ this.current.fillColorSpace = new DeviceGrayCS();- if (!item.content && !item.title) {- content.setAttribute('hidden', true);+ var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.fillStyle = color;+ this.current.fillColor = color;+ },+ setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {+ if (!(this.current.strokeColorSpace instanceof DeviceRgbCS))+ this.current.strokeColorSpace = new DeviceRgbCS();++ var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.strokeStyle = color;+ this.current.strokeColor = color;+ },+ setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {+ if (!(this.current.fillColorSpace instanceof DeviceRgbCS))+ this.current.fillColorSpace = new DeviceRgbCS();++ var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);+ var color = Util.makeCssRgb(rgbColor);+ this.ctx.fillStyle = color;+ this.current.fillColor = color;+ },+ setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) {+ if (!(this.current.strokeColorSpace instanceof DeviceCmykCS))+ this.current.strokeColorSpace = new DeviceCmykCS();++ var color = Util.makeCssCmyk(arguments);+ this.ctx.strokeStyle = color;+ this.current.strokeColor = color;+ },+ setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) {+ if (!(this.current.fillColorSpace instanceof DeviceCmykCS))+ this.current.fillColorSpace = new DeviceCmykCS();++ var color = Util.makeCssCmyk(arguments);+ this.ctx.fillStyle = color;+ this.current.fillColor = color;+ },++ shadingFill: function CanvasGraphics_shadingFill(patternIR) {+ var ctx = this.ctx;++ this.save();+ var pattern = Pattern.shadingFromIR(patternIR);+ ctx.fillStyle = pattern.getPattern(ctx);++ var inv = ctx.mozCurrentTransformInverse;+ if (inv) {+ var canvas = ctx.canvas;+ var width = canvas.width;+ var height = canvas.height;++ var bl = Util.applyTransform([0, 0], inv);+ var br = Util.applyTransform([0, height], inv);+ var ul = Util.applyTransform([width, 0], inv);+ var ur = Util.applyTransform([width, height], inv);++ var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);+ var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);+ var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);+ var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);++ this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);} else {- var e = document.createElement('span');- var lines = item.content.split(/(?:\r\n?|\n)/);- for (i = 0, ii = lines.length; i < ii; ++i) {- var line = lines[i];- e.appendChild(document.createTextNode(line));- if (i < (ii - 1)) {- e.appendChild(document.createElement('br'));- }- }- text.appendChild(e);+ // HACK to draw the gradient onto an infinite rectangle.+ // PDF gradients are drawn across the entire image while+ // Canvas only allows gradients to be drawn in a rectangle+ // The following bug should allow us to remove this.+ // https://bugzilla.mozilla.org/show_bug.cgi?id=664884- var pinned = false;+ this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);+ }- var showAnnotation = function showAnnotation(pin) {- if (pin) {- pinned = true;- }- if (content.hasAttribute('hidden')) {- container.style.zIndex += 1;- content.removeAttribute('hidden');- }- };+ this.restore();+ },- var hideAnnotation = function hideAnnotation(unpin) {- if (unpin) {- pinned = false;- }- if (!content.hasAttribute('hidden') && !pinned) {- container.style.zIndex -= 1;- content.setAttribute('hidden', true);- }- };+ // Images+ beginInlineImage: function CanvasGraphics_beginInlineImage() {+ error('Should not call beginInlineImage');+ },+ beginImageData: function CanvasGraphics_beginImageData() {+ error('Should not call beginImageData');+ },- var toggleAnnotation = function toggleAnnotation() {- if (pinned) {- hideAnnotation(true);- } else {- showAnnotation(true);- }- };+ paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,+ bbox) {+ this.save();+ this.current.paintFormXObjectDepth++;- var self = this;- image.addEventListener('click', function image_clickHandler() {- toggleAnnotation();- }, false);- image.addEventListener('mouseover', function image_mouseOverHandler() {- showAnnotation();- }, false);- image.addEventListener('mouseout', function image_mouseOutHandler() {- hideAnnotation();- }, false);+ if (matrix && isArray(matrix) && 6 == matrix.length)+ this.transform.apply(this, matrix);- content.addEventListener('click', function content_clickHandler() {- hideAnnotation(true);- }, false);+ if (bbox && isArray(bbox) && 4 == bbox.length) {+ var width = bbox[2] - bbox[0];+ var height = bbox[3] - bbox[1];+ this.rectangle(bbox[0], bbox[1], width, height);+ this.clip();+ this.endPath();}+ },- content.appendChild(title);- content.appendChild(text);- contentWrapper.appendChild(content);- container.appendChild(image);- container.appendChild(contentWrapper);+ paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {+ var depth = this.current.paintFormXObjectDepth;+ do {+ this.restore();+ // some pdf don't close all restores inside object+ // closing those for them+ } while (this.current.paintFormXObjectDepth >= depth);+ },++ beginGroup: function CanvasGraphics_beginGroup(group) {+ this.save();+ var currentCtx = this.ctx;+ // TODO non-isolated groups - according to Rik at adobe non-isolated+ // group results aren't usually that different and they even have tools+ // that ignore this setting. Notes from Rik on implmenting:+ // - When you encounter an transparency group, create a new canvas with+ // the dimensions of the bbox+ // - copy the content from the previous canvas to the new canvas+ // - draw as usual+ // - remove the backdrop alpha:+ // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha+ // value of your transparency group and 'alphaBackdrop' the alpha of the+ // backdrop+ // - remove background color:+ // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)+ if (!group.isolated) {+ info('TODO: Support non-isolated groups.');+ }++ // TODO knockout - supposedly possible with the clever use of compositing+ // modes.+ if (group.knockout) {+ TODO('Support knockout groups.');+ }++ var currentTransform = currentCtx.mozCurrentTransform;+ if (group.matrix) {+ currentCtx.transform.apply(currentCtx, group.matrix);+ }+ assert(group.bbox, 'Bounding box is required.');++ // Based on the current transform figure out how big the bounding box+ // will actually be.+ var bounds = Util.getAxialAlignedBoundingBox(+ group.bbox,+ currentCtx.mozCurrentTransform);+ // Use ceil in case we're between sizes so we don't create canvas that is+ // too small and make the canvas at least 1x1 pixels.+ var drawnWidth = Math.max(Math.ceil(bounds[2] - bounds[0]), 1);+ var drawnHeight = Math.max(Math.ceil(bounds[3] - bounds[1]), 1);++ var scratchCanvas = createScratchCanvas(drawnWidth, drawnHeight);+ var groupCtx = scratchCanvas.getContext('2d');+ addContextCurrentTransform(groupCtx);+ // Since we created a new canvas that is just the size of the bounding box+ // we have to translate the group ctx.+ var offsetX = bounds[0];+ var offsetY = bounds[1];+ groupCtx.translate(-offsetX, -offsetY);+ groupCtx.transform.apply(groupCtx, currentTransform);++ // Setup the current ctx so when the group is popped we draw it the right+ // location.+ currentCtx.setTransform(1, 0, 0, 1, 0, 0);+ currentCtx.translate(offsetX, offsetY);++ // The transparency group inherits all off the current graphics state+ // except the blend mode, soft mask, and alpha constants.+ copyCtxState(currentCtx, groupCtx);+ this.ctx = groupCtx;+ this.setGState([+ ['SMask', 'None'],+ ['BM', 'Normal'],+ ['ca', 1],+ ['CA', 1]+ ]);+ this.groupStack.push(currentCtx);+ },- return container;- }- });+ endGroup: function CanvasGraphics_endGroup(group) {+ var groupCtx = this.ctx;+ this.ctx = this.groupStack.pop();+ // Turn off image smoothing to avoid sub pixel interpolation which can+ // look kind of blurry for some pdfs.+ if ('imageSmoothingEnabled' in this.ctx) {+ this.ctx.imageSmoothingEnabled = false;+ } else {+ this.ctx.mozImageSmoothingEnabled = false;+ }+ this.ctx.drawImage(groupCtx.canvas, 0, 0);+ this.restore();+ },- return TextAnnotation;-})();+ beginAnnotations: function CanvasGraphics_beginAnnotations() {+ this.save();+ this.current = new CanvasExtraState();+ },-var LinkAnnotation = (function LinkAnnotationClosure() {- function LinkAnnotation(params) {- InteractiveAnnotation.call(this, params);+ endAnnotations: function CanvasGraphics_endAnnotations() {+ this.restore();+ },- if (params.data) {- return;- }+ beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,+ matrix) {+ this.save();- var dict = params.dict;- var data = this.data;+ if (rect && isArray(rect) && 4 == rect.length) {+ var width = rect[2] - rect[0];+ var height = rect[3] - rect[1];+ this.rectangle(rect[0], rect[1], width, height);+ this.clip();+ this.endPath();+ }- var action = dict.get('A');- if (action) {- var linkType = action.get('S').name;- if (linkType === 'URI') {- var url = action.get('URI');- if (isName(url)) {- // Some bad PDFs do not put parentheses around relative URLs.- url = '/' + url.name;- } else if (url) {- url = addDefaultProtocolToUrl(url);- }- // TODO: pdf spec mentions urls can be relative to a Base- // entry in the dictionary.- if (!isValidUrl(url, false)) {- url = '';- }- data.url = url;- } else if (linkType === 'GoTo') {- data.dest = action.get('D');- } else if (linkType === 'GoToR') {- var urlDict = action.get('F');- if (isDict(urlDict)) {- // We assume that the 'url' is a Filspec dictionary- // and fetch the url without checking any further- url = urlDict.get('F') || '';- }+ this.transform.apply(this, transform);+ this.transform.apply(this, matrix);+ },- // TODO: pdf reference says that GoToR- // can also have 'NewWindow' attribute- if (!isValidUrl(url, false)) {- url = '';- }- data.url = url;- data.dest = action.get('D');- } else if (linkType === 'Named') {- data.action = action.get('N').name;- } else {- warn('unrecognized link type: ' + linkType);+ endAnnotation: function CanvasGraphics_endAnnotation() {+ this.restore();+ },++ paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {+ var domImage = this.objs.get(objId);+ if (!domImage) {+ error('Dependent image isn\'t ready yet');}- } else if (dict.has('Dest')) {- // simple destination link- var dest = dict.get('Dest');- data.dest = isName(dest) ? dest.name : dest;- }- }- // Lets URLs beginning with 'www.' default to using the 'http://' protocol.- function addDefaultProtocolToUrl(url) {- if (url && url.indexOf('www.') === 0) {- return ('http://' + url);- }- return url;- }+ this.save();- Util.inherit(LinkAnnotation, InteractiveAnnotation, {- hasOperatorList: function LinkAnnotation_hasOperatorList() {- return false;+ var ctx = this.ctx;+ // scale the image to the unit square+ ctx.scale(1 / w, -1 / h);++ ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,+ 0, -h, w, h);+ if (this.imageLayer) {+ var currentTransform = ctx.mozCurrentTransformInverse;+ var position = this.getCanvasPosition(0, 0);+ this.imageLayer.appendImage({+ objId: objId,+ left: position[0],+ top: position[1],+ width: w / currentTransform[0],+ height: h / currentTransform[3]+ });+ }+ this.restore();},- getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {+ paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {+ var ctx = this.ctx;+ var width = img.width, height = img.height;- var container = this.initContainer();- container.className = 'annotLink';+ var glyph = this.processingType3;- var item = this.data;- var rect = item.rect;+ if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {+ var MAX_SIZE_TO_COMPILE = 1000;+ if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {+ glyph.compiled =+ compileType3Glyph({data: img.data, width: width, height: height});+ } else {+ glyph.compiled = null;+ }+ }- container.style.borderColor = item.colorCssRgb;- container.style.borderStyle = 'solid';+ if (glyph && glyph.compiled) {+ glyph.compiled(ctx);+ return;+ }- var link = document.createElement('a');- link.href = link.title = this.data.url || '';+ var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);+ var maskCtx = maskCanvas.getContext('2d');+ maskCtx.save();- container.appendChild(link);+ putBinaryImageData(maskCtx, img);- return container;- }- });+ maskCtx.globalCompositeOperation = 'source-in';- return LinkAnnotation;-})();+ var fillColor = this.current.fillColor;+ maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&+ fillColor.type === 'Pattern') ?+ fillColor.getPattern(maskCtx) : fillColor;+ maskCtx.fillRect(0, 0, width, height);+ maskCtx.restore();+ this.paintInlineImageXObject(maskCanvas);+ },+ paintImageMaskXObjectGroup:+ function CanvasGraphics_paintImageMaskXObjectGroup(images) {+ var ctx = this.ctx;-var NetworkManager = (function NetworkManagerClosure() {+ for (var i = 0, ii = images.length; i < ii; i++) {+ var image = images[i];+ var width = image.width, height = image.height;- var OK_RESPONSE = 200;- var PARTIAL_CONTENT_RESPONSE = 206;+ var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);+ var maskCtx = maskCanvas.getContext('2d');+ maskCtx.save();- function NetworkManager(url, args) {- this.url = url;- args = args || {};- this.isHttp = /^https?:/i.test(url);- this.httpHeaders = (this.isHttp && args.httpHeaders) || {};- this.withCredentials = args.withCredentials || false;- this.getXhr = args.getXhr ||- function NetworkManager_getXhr() {- return new XMLHttpRequest();- };+ putBinaryImageData(maskCtx, image);- this.currXhrId = 0;- this.pendingRequests = {};- this.loadedRequests = {};- }+ maskCtx.globalCompositeOperation = 'source-in';- function getArrayBuffer(xhr) {- var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||- xhr.responseArrayBuffer || xhr.response);- if (typeof data !== 'string') {- return data;- }- var length = data.length;- var buffer = new Uint8Array(length);- for (var i = 0; i < length; i++) {- buffer[i] = data.charCodeAt(i) & 0xFF;- }- return buffer;- }+ var fillColor = this.current.fillColor;+ maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&+ fillColor.type === 'Pattern') ?+ fillColor.getPattern(maskCtx) : fillColor;+ maskCtx.fillRect(0, 0, width, height);- NetworkManager.prototype = {- requestRange: function NetworkManager_requestRange(begin, end, listeners) {- var args = {- begin: begin,- end: end- };- for (var prop in listeners) {- args[prop] = listeners[prop];+ maskCtx.restore();++ ctx.save();+ ctx.transform.apply(ctx, image.transform);+ ctx.scale(1, -1);+ ctx.drawImage(maskCanvas, 0, 0, width, height,+ 0, -1, 1, 1);+ ctx.restore();}- return this.request(args);},- requestFull: function NetworkManager_requestRange(listeners) {- return this.request(listeners);+ paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {+ var imgData = this.objs.get(objId);+ if (!imgData)+ error('Dependent image isn\'t ready yet');++ this.paintInlineImageXObject(imgData);},- request: function NetworkManager_requestRange(args) {- var xhr = this.getXhr();- var xhrId = this.currXhrId++;- var pendingRequest = this.pendingRequests[xhrId] = {- xhr: xhr- };+ paintInlineImageXObject:+ function CanvasGraphics_paintInlineImageXObject(imgData) {+ var width = imgData.width;+ var height = imgData.height;+ var ctx = this.ctx;- xhr.open('GET', this.url);- xhr.withCredentials = this.withCredentials;- for (var property in this.httpHeaders) {- var value = this.httpHeaders[property];- if (typeof value === 'undefined') {- continue;- }- xhr.setRequestHeader(property, value);- }- if (this.isHttp && 'begin' in args && 'end' in args) {- var rangeStr = args.begin + '-' + (args.end - 1);- xhr.setRequestHeader('Range', 'bytes=' + rangeStr);- pendingRequest.expectedStatus = 206;- } else {- pendingRequest.expectedStatus = 200;- }-- xhr.mozResponseType = xhr.responseType = 'arraybuffer';-- if (args.onProgress) {- xhr.onprogress = args.onProgress;- }- if (args.onError) {- xhr.onerror = function(evt) {- args.onError(xhr.status);- };- }- xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);-- pendingRequest.onHeadersReceived = args.onHeadersReceived;- pendingRequest.onDone = args.onDone;- pendingRequest.onError = args.onError;-- xhr.send(null);-- return xhrId;- },-- onStateChange: function NetworkManager_onStateChange(xhrId, evt) {- var pendingRequest = this.pendingRequests[xhrId];- if (!pendingRequest) {- // Maybe abortRequest was called...- return;- }-- var xhr = pendingRequest.xhr;- if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {- pendingRequest.onHeadersReceived();- delete pendingRequest.onHeadersReceived;- }-- if (xhr.readyState !== 4) {- return;- }-- if (!(xhrId in this.pendingRequests)) {- // The XHR request might have been aborted in onHeadersReceived()- // callback, in which case we should abort request- return;- }+ this.save();+ // scale the image to the unit square+ ctx.scale(1 / width, -1 / height);- delete this.pendingRequests[xhrId];+ var currentTransform = ctx.mozCurrentTransformInverse;+ var a = currentTransform[0], b = currentTransform[1];+ var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);+ var c = currentTransform[2], d = currentTransform[3];+ var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);- // success status == 0 can be on ftp, file and other protocols- if (xhr.status === 0 && this.isHttp) {- if (pendingRequest.onError) {- pendingRequest.onError(xhr.status);- }- return;+ var imgToPaint;+ if (imgData instanceof HTMLElement) {+ imgToPaint = imgData;+ } else {+ var tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);+ var tmpCtx = tmpCanvas.getContext('2d');+ putBinaryImageData(tmpCtx, imgData);+ imgToPaint = tmpCanvas;+ }++ var paintWidth = width, paintHeight = height;+ var tmpCanvasId = 'prescale1';+ // Vertial or horizontal scaling shall not be more than 2 to not loose the+ // pixels during drawImage operation, painting on the temporary canvas(es)+ // that are twice smaller in size+ while ((widthScale > 2 && paintWidth > 1) ||+ (heightScale > 2 && paintHeight > 1)) {+ var newWidth = paintWidth, newHeight = paintHeight;+ if (widthScale > 2 && paintWidth > 1) {+ newWidth = Math.ceil(paintWidth / 2);+ widthScale /= paintWidth / newWidth;+ }+ if (heightScale > 2 && paintHeight > 1) {+ newHeight = Math.ceil(paintHeight / 2);+ heightScale /= paintHeight / newHeight;+ }+ var tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId,+ newWidth, newHeight);+ tmpCtx = tmpCanvas.getContext('2d');+ tmpCtx.clearRect(0, 0, newWidth, newHeight);+ tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,+ 0, 0, newWidth, newHeight);+ imgToPaint = tmpCanvas;+ paintWidth = newWidth;+ paintHeight = newHeight;+ tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';+ }+ ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,+ 0, -height, width, height);++ if (this.imageLayer) {+ var position = this.getCanvasPosition(0, -height);+ this.imageLayer.appendImage({+ imgData: imgData,+ left: position[0],+ top: position[1],+ width: width / currentTransform[0],+ height: height / currentTransform[3]+ });}- var xhrStatus = xhr.status || OK_RESPONSE;-- // From http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2:- // "A server MAY ignore the Range header". This means it's possible to- // get a 200 rather than a 206 response from a range request.- var ok_response_on_range_request =- xhrStatus === OK_RESPONSE &&- pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;-- if (!ok_response_on_range_request &&- xhrStatus !== pendingRequest.expectedStatus) {- if (pendingRequest.onError) {- pendingRequest.onError(xhr.status);+ this.restore();+ },++ paintInlineImageXObjectGroup:+ function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {+ var ctx = this.ctx;+ var w = imgData.width;+ var h = imgData.height;++ var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);+ var tmpCtx = tmpCanvas.getContext('2d');+ putBinaryImageData(tmpCtx, imgData);++ for (var i = 0, ii = map.length; i < ii; i++) {+ var entry = map[i];+ ctx.save();+ ctx.transform.apply(ctx, entry.transform);+ ctx.scale(1, -1);+ ctx.drawImage(tmpCanvas, entry.x, entry.y, entry.w, entry.h,+ 0, -1, 1, 1);+ if (this.imageLayer) {+ var position = this.getCanvasPosition(entry.x, entry.y);+ this.imageLayer.appendImage({+ imgData: imgData,+ left: position[0],+ top: position[1],+ width: w,+ height: h+ });}- return;+ ctx.restore();}+ },- this.loadedRequests[xhrId] = true;+ // Marked content- var chunk = getArrayBuffer(xhr);- if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {- var rangeHeader = xhr.getResponseHeader('Content-Range');- var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);- var begin = parseInt(matches[1], 10);- pendingRequest.onDone({- begin: begin,- chunk: chunk- });- } else {- pendingRequest.onDone({- begin: 0,- chunk: chunk- });- }+ markPoint: function CanvasGraphics_markPoint(tag) {+ // TODO Marked content.},-- hasPendingRequests: function NetworkManager_hasPendingRequests() {- for (var xhrId in this.pendingRequests) {- return true;- }- return false;+ markPointProps: function CanvasGraphics_markPointProps(tag, properties) {+ // TODO Marked content.},-- getRequestXhr: function NetworkManager_getXhr(xhrId) {- return this.pendingRequests[xhrId].xhr;+ beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {+ // TODO Marked content.},-- isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {- return xhrId in this.pendingRequests;+ beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(+ tag, properties) {+ // TODO Marked content.+ },+ endMarkedContent: function CanvasGraphics_endMarkedContent() {+ // TODO Marked content.},- isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {- return xhrId in this.loadedRequests;+ // Compatibility++ beginCompat: function CanvasGraphics_beginCompat() {+ // TODO ignore undefined operators (should we do that anyway?)+ },+ endCompat: function CanvasGraphics_endCompat() {+ // TODO stop ignoring undefined operators},- abortAllRequests: function NetworkManager_abortAllRequests() {- for (var xhrId in this.pendingRequests) {- this.abortRequest(xhrId | 0);+ // Helper functions++ consumePath: function CanvasGraphics_consumePath() {+ if (this.pendingClip) {+ if (this.pendingClip == EO_CLIP) {+ if ('mozFillRule' in this.ctx) {+ this.ctx.mozFillRule = 'evenodd';+ this.ctx.clip();+ this.ctx.mozFillRule = 'nonzero';+ } else {+ try {+ this.ctx.clip('evenodd');+ } catch (ex) {+ // shouldn't really happen, but browsers might think differently+ this.ctx.clip();+ }+ }+ } else {+ this.ctx.clip();+ }+ this.pendingClip = null;}+ this.ctx.beginPath();},-- abortRequest: function NetworkManager_abortRequest(xhrId) {- var xhr = this.pendingRequests[xhrId].xhr;- delete this.pendingRequests[xhrId];- xhr.abort();+ getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {+ var inverse = this.ctx.mozCurrentTransformInverse;+ // max of the current horizontal and vertical scale+ return Math.sqrt(Math.max(+ (inverse[0] * inverse[0] + inverse[1] * inverse[1]),+ (inverse[2] * inverse[2] + inverse[3] * inverse[3])));+ },+ getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {+ var transform = this.ctx.mozCurrentTransform;+ return [+ transform[0] * x + transform[2] * y + transform[4],+ transform[1] * x + transform[3] * y + transform[5]+ ];}};- return NetworkManager;+ return CanvasGraphics;})();-var ChunkedStream = (function ChunkedStreamClosure() {- function ChunkedStream(length, chunkSize, manager) {- this.bytes = new Uint8Array(length);- this.start = 0;- this.pos = 0;- this.end = length;- this.chunkSize = chunkSize;- this.loadedChunks = [];- this.numChunksLoaded = 0;- this.numChunks = Math.ceil(length / chunkSize);- this.manager = manager;- this.initialDataLength = 0;+var Name = (function NameClosure() {+ function Name(name) {+ this.name = name;}- // required methods for a stream. if a particular stream does not- // implement these, an error should be thrown- ChunkedStream.prototype = {+ Name.prototype = {};- getMissingChunks: function ChunkedStream_getMissingChunks() {- var chunks = [];- for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) {- if (!(chunk in this.loadedChunks)) {- chunks.push(chunk);- }- }- return chunks;- },+ return Name;+})();- getBaseStreams: function ChunkedStream_getBaseStreams() {- return [this];- },+var Cmd = (function CmdClosure() {+ function Cmd(cmd) {+ this.cmd = cmd;+ }- allChunksLoaded: function ChunkedStream_allChunksLoaded() {- return this.numChunksLoaded === this.numChunks;- },+ Cmd.prototype = {};- onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) {- var end = begin + chunk.byteLength;+ var cmdCache = {};- assert(begin % this.chunkSize === 0, 'Bad begin offset: ' + begin);- // Using this.length is inaccurate here since this.start can be moved- // See ChunkedStream.moveStart()- var length = this.bytes.length;- assert(end % this.chunkSize === 0 || end === length,- 'Bad end offset: ' + end);+ Cmd.get = function Cmd_get(cmd) {+ var cmdValue = cmdCache[cmd];+ if (cmdValue)+ return cmdValue;- this.bytes.set(new Uint8Array(chunk), begin);- var chunkSize = this.chunkSize;- var beginChunk = Math.floor(begin / chunkSize);- var endChunk = Math.floor((end - 1) / chunkSize) + 1;- var curChunk;+ return cmdCache[cmd] = new Cmd(cmd);+ };- for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) {- if (!(curChunk in this.loadedChunks)) {- this.loadedChunks[curChunk] = true;- ++this.numChunksLoaded;- }- }- },+ return Cmd;+})();- onReceiveInitialData: function ChunkedStream_onReceiveInitialData(data) {- this.bytes.set(data);- this.initialDataLength = data.length;- var endChunk = (this.end === data.length ?- this.numChunks : Math.floor(data.length / this.chunkSize));- for (var i = 0; i < endChunk; i++) {- this.loadedChunks[i] = true;- ++this.numChunksLoaded;- }- },+var Dict = (function DictClosure() {+ var nonSerializable = function nonSerializableClosure() {+ return nonSerializable; // creating closure on some variable+ };- ensureRange: function ChunkedStream_ensureRange(begin, end) {- if (begin >= end) {- return;- }+ // xref is optional+ function Dict(xref) {+ // Map should only be used internally, use functions below to access.+ this.map = Object.create(null);+ this.xref = xref;+ this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict+ }- if (end <= this.initialDataLength) {- return;- }+ Dict.prototype = {+ assignXref: function Dict_assignXref(newXref) {+ this.xref = newXref;+ },- var chunkSize = this.chunkSize;- var beginChunk = Math.floor(begin / chunkSize);- var endChunk = Math.floor((end - 1) / chunkSize) + 1;- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- if (!(chunk in this.loadedChunks)) {- throw new MissingDataException(begin, end);- }+ // automatically dereferences Ref objects+ get: function Dict_get(key1, key2, key3) {+ var value;+ var xref = this.xref;+ if (typeof (value = this.map[key1]) != 'undefined' || key1 in this.map ||+ typeof key2 == 'undefined') {+ return xref ? xref.fetchIfRef(value) : value;+ }+ if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map ||+ typeof key3 == 'undefined') {+ return xref ? xref.fetchIfRef(value) : value;}+ value = this.map[key3] || null;+ return xref ? xref.fetchIfRef(value) : value;},- nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) {- var chunk, n;- for (chunk = beginChunk, n = this.numChunks; chunk < n; ++chunk) {- if (!(chunk in this.loadedChunks)) {- return chunk;+ // Same as get(), but returns a promise and uses fetchIfRefAsync().+ getAsync: function Dict_getAsync(key1, key2, key3) {+ var value;+ var promise;+ var xref = this.xref;+ if (typeof (value = this.map[key1]) !== undefined || key1 in this.map ||+ typeof key2 === undefined) {+ if (xref) {+ return xref.fetchIfRefAsync(value);}+ promise = new Promise();+ promise.resolve(value);+ return promise;}- // Wrap around to beginning- for (chunk = 0; chunk < beginChunk; ++chunk) {- if (!(chunk in this.loadedChunks)) {- return chunk;+ if (typeof (value = this.map[key2]) !== undefined || key2 in this.map ||+ typeof key3 === undefined) {+ if (xref) {+ return xref.fetchIfRefAsync(value);}+ promise = new Promise();+ promise.resolve(value);+ return promise;}- return null;- },-- hasChunk: function ChunkedStream_hasChunk(chunk) {- return chunk in this.loadedChunks;+ value = this.map[key3] || null;+ if (xref) {+ return xref.fetchIfRefAsync(value);+ }+ promise = new Promise();+ promise.resolve(value);+ return promise;},- get length() {- return this.end - this.start;+ // no dereferencing+ getRaw: function Dict_getRaw(key) {+ return this.map[key];},- getByte: function ChunkedStream_getByte() {- var pos = this.pos;- if (pos >= this.end) {- return -1;+ // creates new map and dereferences all Refs+ getAll: function Dict_getAll() {+ var all = {};+ for (var key in this.map) {+ var obj = this.get(key);+ all[key] = obj instanceof Dict ? obj.getAll() : obj;}- this.ensureRange(pos, pos + 1);- return this.bytes[this.pos++];+ return all;},- getUint16: function ChunkedStream_getUint16() {- var b0 = this.getByte();- var b1 = this.getByte();- return (b0 << 8) + b1;+ set: function Dict_set(key, value) {+ this.map[key] = value;},- getUint32: function ChunkedStream_getUint32() {- var b0 = this.getByte();- var b1 = this.getByte();- var b2 = this.getByte();- var b3 = this.getByte();- return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;+ has: function Dict_has(key) {+ return key in this.map;},- // returns subarray of original buffer- // should only be read- getBytes: function ChunkedStream_getBytes(length) {- var bytes = this.bytes;- var pos = this.pos;- var strEnd = this.end;-- if (!length) {- this.ensureRange(pos, strEnd);- return bytes.subarray(pos, strEnd);- }-- var end = pos + length;- if (end > strEnd) {- end = strEnd;+ forEach: function Dict_forEach(callback) {+ for (var key in this.map) {+ callback(key, this.get(key));}- this.ensureRange(pos, end);+ }+ };- this.pos = end;- return bytes.subarray(pos, end);- },+ return Dict;+})();- peekBytes: function ChunkedStream_peekBytes(length) {- var bytes = this.getBytes(length);- this.pos -= bytes.length;- return bytes;- },+var Ref = (function RefClosure() {+ function Ref(num, gen) {+ this.num = num;+ this.gen = gen;+ }- getByteRange: function ChunkedStream_getBytes(begin, end) {- this.ensureRange(begin, end);- return this.bytes.subarray(begin, end);- },+ Ref.prototype = {};- skip: function ChunkedStream_skip(n) {- if (!n) {- n = 1;- }- this.pos += n;- },+ return Ref;+})();- reset: function ChunkedStream_reset() {- this.pos = this.start;- },+// The reference is identified by number and generation,+// this structure stores only one instance of the reference.+var RefSet = (function RefSetClosure() {+ function RefSet() {+ this.dict = {};+ }- moveStart: function ChunkedStream_moveStart() {- this.start = this.pos;+ RefSet.prototype = {+ has: function RefSet_has(ref) {+ return ('R' + ref.num + '.' + ref.gen) in this.dict;},- makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) {- this.ensureRange(start, start + length);-- function ChunkedStreamSubstream() {}- ChunkedStreamSubstream.prototype = Object.create(this);- ChunkedStreamSubstream.prototype.getMissingChunks = function() {- var chunkSize = this.chunkSize;- var beginChunk = Math.floor(this.start / chunkSize);- var endChunk = Math.floor((this.end - 1) / chunkSize) + 1;- var missingChunks = [];- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- if (!(chunk in this.loadedChunks)) {- missingChunks.push(chunk);- }- }- return missingChunks;- };- var subStream = new ChunkedStreamSubstream();- subStream.pos = subStream.start = start;- subStream.end = start + length || this.end;- subStream.dict = dict;- return subStream;+ put: function RefSet_put(ref) {+ this.dict['R' + ref.num + '.' + ref.gen] = true;},- isStream: true+ remove: function RefSet_remove(ref) {+ delete this.dict['R' + ref.num + '.' + ref.gen];+ }};- return ChunkedStream;+ return RefSet;})();-var ChunkedStreamManager = (function ChunkedStreamManagerClosure() {+var RefSetCache = (function RefSetCacheClosure() {+ function RefSetCache() {+ this.dict = {};+ }- function ChunkedStreamManager(length, chunkSize, url, args) {- var self = this;- this.stream = new ChunkedStream(length, chunkSize, this);- this.length = length;- this.chunkSize = chunkSize;- this.url = url;- this.disableAutoFetch = args.disableAutoFetch;- var msgHandler = this.msgHandler = args.msgHandler;+ RefSetCache.prototype = {+ get: function RefSetCache_get(ref) {+ return this.dict['R' + ref.num + '.' + ref.gen];+ },- if (args.chunkedViewerLoading) {- msgHandler.on('OnDataRange', this.onReceiveData.bind(this));- msgHandler.on('OnDataProgress', this.onProgress.bind(this));- this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {- msgHandler.send('RequestDataRange', { begin: begin, end: end });- };- } else {+ has: function RefSetCache_has(ref) {+ return ('R' + ref.num + '.' + ref.gen) in this.dict;+ },- var getXhr = function getXhr() {- return new XMLHttpRequest();- };- this.networkManager = new NetworkManager(this.url, {- getXhr: getXhr,- httpHeaders: args.httpHeaders,- withCredentials: args.withCredentials- });- this.sendRequest = function ChunkedStreamManager_sendRequest(begin, end) {- this.networkManager.requestRange(begin, end, {- onDone: this.onReceiveData.bind(this),- onProgress: this.onProgress.bind(this)- });- };+ put: function RefSetCache_put(ref, obj) {+ this.dict['R' + ref.num + '.' + ref.gen] = obj;}+ };- this.currRequestId = 0;+ return RefSetCache;+})();- this.chunksNeededByRequest = {};- this.requestsByChunk = {};- this.callbacksByRequest = {};+var Catalog = (function CatalogClosure() {+ function Catalog(pdfManager, xref) {+ this.pdfManager = pdfManager;+ this.xref = xref;+ this.catDict = xref.getCatalogObj();+ assertWellFormed(isDict(this.catDict),+ 'catalog object is not a dictionary');- this.loadedStream = new LegacyPromise();- if (args.initialData) {- this.setInitialData(args.initialData);- }+ // Stores state as we traverse the pages catalog so that we can resume+ // parsing if an exception is thrown+ this.traversePagesQueue = [{+ pagesDict: this.toplevelPagesDict,+ posInKids: 0+ }];+ this.pagePromises = [];+ this.currPageIndex = 0;}- ChunkedStreamManager.prototype = {-- setInitialData: function ChunkedStreamManager_setInitialData(data) {- this.stream.onReceiveInitialData(data);- if (this.stream.allChunksLoaded()) {- this.loadedStream.resolve(this.stream);- } else if (this.msgHandler) {- this.msgHandler.send('DocProgress', {- loaded: data.length,- total: this.length- });- }- },-- onLoadedStream: function ChunkedStreamManager_getLoadedStream() {- return this.loadedStream;- },-- // Get all the chunks that are not yet loaded and groups them into- // contiguous ranges to load in as few requests as possible- requestAllChunks: function ChunkedStreamManager_requestAllChunks() {- var missingChunks = this.stream.getMissingChunks();- this.requestChunks(missingChunks);- return this.loadedStream;- },+ Catalog.prototype = {+ get metadata() {+ var streamRef = this.catDict.getRaw('Metadata');+ if (!isRef(streamRef))+ return shadow(this, 'metadata', null);- requestChunks: function ChunkedStreamManager_requestChunks(chunks,- callback) {- var requestId = this.currRequestId++;+ var encryptMetadata = !this.xref.encrypt ? false :+ this.xref.encrypt.encryptMetadata;- var chunksNeeded;- var i, ii;- this.chunksNeededByRequest[requestId] = chunksNeeded = {};- for (i = 0, ii = chunks.length; i < ii; i++) {- if (!this.stream.hasChunk(chunks[i])) {- chunksNeeded[chunks[i]] = true;- }- }+ var stream = this.xref.fetch(streamRef, !encryptMetadata);+ var metadata;+ if (stream && isDict(stream.dict)) {+ var type = stream.dict.get('Type');+ var subtype = stream.dict.get('Subtype');- if (isEmptyObj(chunksNeeded)) {- if (callback) {- callback();+ if (isName(type) && isName(subtype) &&+ type.name === 'Metadata' && subtype.name === 'XML') {+ // XXX: This should examine the charset the XML document defines,+ // however since there are currently no real means to decode+ // arbitrary charsets, let's just hope that the author of the PDF+ // was reasonable enough to stick with the XML default charset,+ // which is UTF-8.+ try {+ metadata = stringToUTF8String(bytesToString(stream.getBytes()));+ } catch (e) {+ info('Skipping invalid metadata.');+ }}- return;}- this.callbacksByRequest[requestId] = callback;-- var chunksToRequest = [];- for (var chunk in chunksNeeded) {- chunk = chunk | 0;- if (!(chunk in this.requestsByChunk)) {- this.requestsByChunk[chunk] = [];- chunksToRequest.push(chunk);+ return shadow(this, 'metadata', metadata);+ },+ get toplevelPagesDict() {+ var pagesObj = this.catDict.get('Pages');+ assertWellFormed(isDict(pagesObj), 'invalid top-level pages dictionary');+ // shadow the prototype getter+ return shadow(this, 'toplevelPagesDict', pagesObj);+ },+ get documentOutline() {+ var obj = null;+ try {+ obj = this.readDocumentOutline();+ } catch (ex) {+ if (ex instanceof MissingDataException) {+ throw ex;}- this.requestsByChunk[chunk].push(requestId);- }-- if (!chunksToRequest.length) {- return;+ warn('Unable to read document outline');}-- var groupedChunksToRequest = this.groupChunks(chunksToRequest);-- for (i = 0; i < groupedChunksToRequest.length; ++i) {- var groupedChunk = groupedChunksToRequest[i];- var begin = groupedChunk.beginChunk * this.chunkSize;- var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);- this.sendRequest(begin, end);+ return shadow(this, 'documentOutline', obj);+ },+ readDocumentOutline: function Catalog_readDocumentOutline() {+ var xref = this.xref;+ var obj = this.catDict.get('Outlines');+ var root = { items: [] };+ if (isDict(obj)) {+ obj = obj.getRaw('First');+ var processed = new RefSet();+ if (isRef(obj)) {+ var queue = [{obj: obj, parent: root}];+ // to avoid recursion keeping track of the items+ // in the processed dictionary+ processed.put(obj);+ while (queue.length > 0) {+ var i = queue.shift();+ var outlineDict = xref.fetchIfRef(i.obj);+ if (outlineDict === null)+ continue;+ if (!outlineDict.has('Title'))+ error('Invalid outline item');+ var dest = outlineDict.get('A');+ if (dest)+ dest = dest.get('D');+ else if (outlineDict.has('Dest')) {+ dest = outlineDict.getRaw('Dest');+ if (isName(dest))+ dest = dest.name;+ }+ var title = outlineDict.get('Title');+ var outlineItem = {+ dest: dest,+ title: stringToPDFString(title),+ color: outlineDict.get('C') || [0, 0, 0],+ count: outlineDict.get('Count'),+ bold: !!(outlineDict.get('F') & 2),+ italic: !!(outlineDict.get('F') & 1),+ items: []+ };+ i.parent.items.push(outlineItem);+ obj = outlineDict.getRaw('First');+ if (isRef(obj) && !processed.has(obj)) {+ queue.push({obj: obj, parent: outlineItem});+ processed.put(obj);+ }+ obj = outlineDict.getRaw('Next');+ if (isRef(obj) && !processed.has(obj)) {+ queue.push({obj: obj, parent: i.parent});+ processed.put(obj);+ }+ }+ }}+ return root.items.length > 0 ? root.items : null;},-- getStream: function ChunkedStreamManager_getStream() {- return this.stream;+ get numPages() {+ var obj = this.toplevelPagesDict.get('Count');+ assertWellFormed(+ isInt(obj),+ 'page count in top level pages object is not an integer'+ );+ // shadow the prototype getter+ return shadow(this, 'num', obj);},-- // Loads any chunks in the requested range that are not yet loaded- requestRange: function ChunkedStreamManager_requestRange(- begin, end, callback) {-- end = Math.min(end, this.length);-- var beginChunk = this.getBeginChunk(begin);- var endChunk = this.getEndChunk(end);-- var chunks = [];- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- chunks.push(chunk);+ get destinations() {+ function fetchDestination(dest) {+ return isDict(dest) ? dest.get('D') : dest;}- this.requestChunks(chunks, callback);- },-- requestRanges: function ChunkedStreamManager_requestRanges(ranges,- callback) {- ranges = ranges || [];- var chunksToRequest = [];+ var xref = this.xref;+ var dests = {}, nameTreeRef, nameDictionaryRef;+ var obj = this.catDict.get('Names');+ if (obj)+ nameTreeRef = obj.getRaw('Dests');+ else if (this.catDict.has('Dests'))+ nameDictionaryRef = this.catDict.get('Dests');- for (var i = 0; i < ranges.length; i++) {- var beginChunk = this.getBeginChunk(ranges[i].begin);- var endChunk = this.getEndChunk(ranges[i].end);- for (var chunk = beginChunk; chunk < endChunk; ++chunk) {- if (chunksToRequest.indexOf(chunk) < 0) {- chunksToRequest.push(chunk);+ if (nameDictionaryRef) {+ // reading simple destination dictionary+ obj = nameDictionaryRef;+ obj.forEach(function catalogForEach(key, value) {+ if (!value) return;+ dests[key] = fetchDestination(value);+ });+ }+ if (nameTreeRef) {+ var nameTree = new NameTree(nameTreeRef, xref);+ var names = nameTree.getAll();+ for (var name in names) {+ if (!names.hasOwnProperty(name)) {+ continue;}+ dests[name] = fetchDestination(names[name]);}}-- chunksToRequest.sort(function(a, b) { return a - b; });- this.requestChunks(chunksToRequest, callback);+ return shadow(this, 'destinations', dests);},+ get javaScript() {+ var xref = this.xref;+ var obj = this.catDict.get('Names');- // Groups a sorted array of chunks into as few continguous larger- // chunks as possible- groupChunks: function ChunkedStreamManager_groupChunks(chunks) {- var groupedChunks = [];- var beginChunk = -1;- var prevChunk = -1;- for (var i = 0; i < chunks.length; ++i) {- var chunk = chunks[i];-- if (beginChunk < 0) {- beginChunk = chunk;- }-- if (prevChunk >= 0 && prevChunk + 1 !== chunk) {- groupedChunks.push({ beginChunk: beginChunk,- endChunk: prevChunk + 1 });- beginChunk = chunk;- }- if (i + 1 === chunks.length) {- groupedChunks.push({ beginChunk: beginChunk,- endChunk: chunk + 1 });+ var javaScript = [];+ if (obj && obj.has('JavaScript')) {+ var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);+ var names = nameTree.getAll();+ for (var name in names) {+ if (!names.hasOwnProperty(name)) {+ continue;+ }+ // We don't really use the JavaScript right now so this code is+ // defensive so we don't cause errors on document load.+ var jsDict = names[name];+ if (!isDict(jsDict)) {+ continue;+ }+ var type = jsDict.get('S');+ if (!isName(type) || type.name !== 'JavaScript') {+ continue;+ }+ var js = jsDict.get('JS');+ if (!isString(js) && !isStream(js)) {+ continue;+ }+ if (isStream(js)) {+ js = bytesToString(js.getBytes());+ }+ javaScript.push(stringToPDFString(js));}-- prevChunk = chunk;}- return groupedChunks;+ return shadow(this, 'javaScript', javaScript);},- onProgress: function ChunkedStreamManager_onProgress(args) {- var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize +- args.loaded);- this.msgHandler.send('DocProgress', {- loaded: bytesLoaded,- total: this.length- });+ getPage: function Catalog_getPage(pageIndex) {+ if (!(pageIndex in this.pagePromises)) {+ this.pagePromises[pageIndex] = new Promise();+ }+ return this.pagePromises[pageIndex];},- onReceiveData: function ChunkedStreamManager_onReceiveData(args) {- var chunk = args.chunk;- var begin = args.begin;- var end = begin + chunk.byteLength;-- var beginChunk = this.getBeginChunk(begin);- var endChunk = this.getEndChunk(end);-- this.stream.onReceiveData(begin, chunk);- if (this.stream.allChunksLoaded()) {- this.loadedStream.resolve(this.stream);- }+ // Traverses pages in DFS order so that pages are processed in increasing+ // order+ traversePages: function Catalog_traversePages() {+ var queue = this.traversePagesQueue;+ while (queue.length) {+ var queueItem = queue[queue.length - 1];+ var pagesDict = queueItem.pagesDict;- var loadedRequests = [];- var i, requestId;- for (chunk = beginChunk; chunk < endChunk; ++chunk) {- // The server might return more chunks than requested- var requestIds = this.requestsByChunk[chunk] || [];- delete this.requestsByChunk[chunk];+ var kids = pagesDict.get('Kids');+ assert(isArray(kids), 'page dictionary kids object is not an array');+ if (queueItem.posInKids >= kids.length) {+ queue.pop();+ continue;+ }+ var kidRef = kids[queueItem.posInKids];+ assert(isRef(kidRef), 'page dictionary kid is not a reference');- for (i = 0; i < requestIds.length; ++i) {- requestId = requestIds[i];- var chunksNeeded = this.chunksNeededByRequest[requestId];- if (chunk in chunksNeeded) {- delete chunksNeeded[chunk];+ var kid = this.xref.fetch(kidRef);+ if (isDict(kid, 'Page') || (isDict(kid) && !kid.has('Kids'))) {+ var pageIndex = this.currPageIndex++;+ var page = new Page(this.pdfManager, this.xref, pageIndex, kid,+ kidRef);+ if (!(pageIndex in this.pagePromises)) {+ this.pagePromises[pageIndex] = new Promise();}+ this.pagePromises[pageIndex].resolve(page);- if (!isEmptyObj(chunksNeeded)) {- continue;- }+ } else { // must be a child page dictionary+ assert(+ isDict(kid),+ 'page dictionary kid reference points to wrong type of object'+ );- loadedRequests.push(requestId);+ queue.push({+ pagesDict: kid,+ posInKids: 0+ });}+ ++queueItem.posInKids;}+ }+ };- // If there are no pending requests, automatically fetch the next- // unfetched chunk of the PDF- if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) {- var nextEmptyChunk;- if (this.stream.numChunksLoaded === 1) {- // This is a special optimization so that after fetching the first- // chunk, rather than fetching the second chunk, we fetch the last- // chunk.- var lastChunk = this.stream.numChunks - 1;- if (!this.stream.hasChunk(lastChunk)) {- nextEmptyChunk = lastChunk;- }- } else {- nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);- }- if (isInt(nextEmptyChunk)) {- this.requestChunks([nextEmptyChunk]);- }- }+ return Catalog;+})();- for (i = 0; i < loadedRequests.length; ++i) {- requestId = loadedRequests[i];- var callback = this.callbacksByRequest[requestId];- delete this.callbacksByRequest[requestId];- if (callback) {- callback();- }- }+var XRef = (function XRefClosure() {+ function XRef(stream, password) {- this.msgHandler.send('DocProgress', {- loaded: this.stream.numChunksLoaded * this.chunkSize,- total: this.length- });- },+ this.stream = stream;+ this.entries = [];+ this.xrefstms = {};+ // prepare the XRef cache+ this.cache = [];+ this.password = password;+ }- getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) {- var chunk = Math.floor(begin / this.chunkSize);- return chunk;+ XRef.prototype = {+ setStartXRef: function XRef_setStartXRef(startXRef) {+ // Store the starting positions of xref tables as we process them+ // so we can recover from missing data errors+ this.startXRefQueue = [startXRef];},- getEndChunk: function ChunkedStreamManager_getEndChunk(end) {- if (end % this.chunkSize === 0) {- return end / this.chunkSize;+ parse: function XRef_parse(recoveryMode) {+ var trailerDict;+ if (!recoveryMode) {+ trailerDict = this.readXRef();+ } else {+ warn('Indexing all PDF objects');+ trailerDict = this.indexObjects();+ }+ trailerDict.assignXref(this);+ this.trailer = trailerDict;+ var encrypt = trailerDict.get('Encrypt');+ if (encrypt) {+ var ids = trailerDict.get('ID');+ var fileId = (ids && ids.length) ? ids[0] : '';+ this.encrypt = new CipherTransformFactory(+ encrypt, fileId, this.password);}- // 0 -> 0- // 1 -> 1- // 99 -> 1- // 100 -> 1- // 101 -> 2- var chunk = Math.floor((end - 1) / this.chunkSize) + 1;- return chunk;- }- };-- return ChunkedStreamManager;-})();-+ // get the root dictionary (catalog) object+ if (!(this.root = trailerDict.get('Root'))) {+ error('Invalid root reference');+ }+ },+ processXRefTable: function XRef_processXRefTable(parser) {+ if (!('tableState' in this)) {+ // Stores state of the table as we process it so we can resume+ // from middle of table in case of missing data error+ this.tableState = {+ entryNum: 0,+ streamPos: parser.lexer.stream.pos,+ parserBuf1: parser.buf1,+ parserBuf2: parser.buf2+ };+ }-// The maximum number of bytes fetched per range request-var RANGE_CHUNK_SIZE = 65536;+ var obj = this.readXRefTable(parser);-// TODO(mack): Make use of PDFJS.Util.inherit() when it becomes available-var BasePdfManager = (function BasePdfManagerClosure() {- function BasePdfManager() {- throw new Error('Cannot initialize BaseManagerManager');- }+ // Sanity check+ if (!isCmd(obj, 'trailer'))+ error('Invalid XRef table: could not find trailer dictionary');- BasePdfManager.prototype = {- onLoadedStream: function BasePdfManager_onLoadedStream() {- throw new NotImplementedException();- },+ // Read trailer dictionary, e.g.+ // trailer+ // << /Size 22+ // /Root 20R+ // /Info 10R+ // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]+ // >>+ // The parser goes through the entire stream << ... >> and provides+ // a getter interface for the key-value table+ var dict = parser.getObj();+ if (!isDict(dict))+ error('Invalid XRef table: could not parse trailer dictionary');- ensureDoc: function BasePdfManager_ensureDoc(prop, args) {- return this.ensure(this.pdfDocument, prop, args);- },+ delete this.tableState;- ensureXRef: function BasePdfManager_ensureXRef(prop, args) {- return this.ensure(this.pdfDocument.xref, prop, args);+ return dict;},- ensureCatalog: function BasePdfManager_ensureCatalog(prop, args) {- return this.ensure(this.pdfDocument.catalog, prop, args);- },+ readXRefTable: function XRef_readXRefTable(parser) {+ // Example of cross-reference table:+ // xref+ // 0 1 <-- subsection header (first obj #, obj count)+ // 0000000000 65535 f <-- actual object (offset, generation #, f/n)+ // 23 2 <-- subsection header ... and so on ...+ // 0000025518 00002 n+ // 0000025635 00000 n+ // trailer+ // ...- getPage: function BasePdfManager_pagePage(pageIndex) {- return this.pdfDocument.getPage(pageIndex);- },+ var stream = parser.lexer.stream;+ var tableState = this.tableState;+ stream.pos = tableState.streamPos;+ parser.buf1 = tableState.parserBuf1;+ parser.buf2 = tableState.parserBuf2;- cleanup: function BasePdfManager_cleanup() {- return this.pdfDocument.cleanup();- },+ // Outer loop is over subsection headers+ var obj;- ensure: function BasePdfManager_ensure(obj, prop, args) {- return new NotImplementedException();- },+ while (true) {+ if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {+ if (isCmd(obj = parser.getObj(), 'trailer')) {+ break;+ }+ tableState.firstEntryNum = obj;+ tableState.entryCount = parser.getObj();+ }- requestRange: function BasePdfManager_ensure(begin, end) {- return new NotImplementedException();- },+ var first = tableState.firstEntryNum;+ var count = tableState.entryCount;+ if (!isInt(first) || !isInt(count))+ error('Invalid XRef table: wrong types in subsection header');- requestLoadedStream: function BasePdfManager_requestLoadedStream() {- return new NotImplementedException();- },+ // Inner loop is over objects themselves+ for (var i = tableState.entryNum; i < count; i++) {+ tableState.streamPos = stream.pos;+ tableState.entryNum = i;+ tableState.parserBuf1 = parser.buf1;+ tableState.parserBuf2 = parser.buf2;- updatePassword: function BasePdfManager_updatePassword(password) {- this.pdfDocument.xref.password = this.password = password;- if (this.passwordChangedPromise) {- this.passwordChangedPromise.resolve();- }- },+ var entry = {};+ entry.offset = parser.getObj();+ entry.gen = parser.getObj();+ var type = parser.getObj();- terminate: function BasePdfManager_terminate() {- return new NotImplementedException();- }- };+ if (isCmd(type, 'f'))+ entry.free = true;+ else if (isCmd(type, 'n'))+ entry.uncompressed = true;- return BasePdfManager;-})();+ // Validate entry obj+ if (!isInt(entry.offset) || !isInt(entry.gen) ||+ !(entry.free || entry.uncompressed)) {+ console.log(entry.offset, entry.gen, entry.free,+ entry.uncompressed);+ error('Invalid entry in XRef subsection: ' + first + ', ' + count);+ }-var LocalPdfManager = (function LocalPdfManagerClosure() {- function LocalPdfManager(data, password) {- var stream = new Stream(data);- this.pdfDocument = new PDFDocument(this, stream, password);- this.loadedStream = new LegacyPromise();- this.loadedStream.resolve(stream);- }+ if (!this.entries[i + first])+ this.entries[i + first] = entry;+ }- LocalPdfManager.prototype = Object.create(BasePdfManager.prototype);- LocalPdfManager.prototype.constructor = LocalPdfManager;+ tableState.entryNum = 0;+ tableState.streamPos = stream.pos;+ tableState.parserBuf1 = parser.buf1;+ tableState.parserBuf2 = parser.buf2;+ delete tableState.firstEntryNum;+ delete tableState.entryCount;+ }- LocalPdfManager.prototype.ensure =- function LocalPdfManager_ensure(obj, prop, args) {- var promise = new LegacyPromise();- try {- var value = obj[prop];- var result;- if (typeof(value) === 'function') {- result = value.apply(obj, args);- } else {- result = value;+ // Per issue 3248: hp scanners generate bad XRef+ if (first === 1 && this.entries[1] && this.entries[1].free) {+ // shifting the entries+ this.entries.shift();}- promise.resolve(result);- } catch (e) {- console.log(e.stack);- promise.reject(e);- }- return promise;- };- LocalPdfManager.prototype.requestRange =- function LocalPdfManager_requestRange(begin, end) {- var promise = new LegacyPromise();- promise.resolve();- return promise;- };+ // Sanity check: as per spec, first object must be free+ if (this.entries[0] && !this.entries[0].free)+ error('Invalid XRef table: unexpected first object');- LocalPdfManager.prototype.requestLoadedStream =- function LocalPdfManager_requestLoadedStream() {- };+ return obj;+ },- LocalPdfManager.prototype.onLoadedStream =- function LocalPdfManager_getLoadedStream() {- return this.loadedStream;- };+ processXRefStream: function XRef_processXRefStream(stream) {+ if (!('streamState' in this)) {+ // Stores state of the stream as we process it so we can resume+ // from middle of stream in case of missing data error+ var streamParameters = stream.dict;+ var byteWidths = streamParameters.get('W');+ var range = streamParameters.get('Index');+ if (!range) {+ range = [0, streamParameters.get('Size')];+ }- LocalPdfManager.prototype.terminate =- function LocalPdfManager_terminate() {- return;- };+ this.streamState = {+ entryRanges: range,+ byteWidths: byteWidths,+ entryNum: 0,+ streamPos: stream.pos+ };+ }+ this.readXRefStream(stream);+ delete this.streamState;- return LocalPdfManager;-})();+ return stream.dict;+ },-var NetworkPdfManager = (function NetworkPdfManagerClosure() {- function NetworkPdfManager(args, msgHandler) {+ readXRefStream: function XRef_readXRefStream(stream) {+ var i, j;+ var streamState = this.streamState;+ stream.pos = streamState.streamPos;- this.msgHandler = msgHandler;+ var byteWidths = streamState.byteWidths;+ var typeFieldWidth = byteWidths[0];+ var offsetFieldWidth = byteWidths[1];+ var generationFieldWidth = byteWidths[2];- var params = {- msgHandler: msgHandler,- httpHeaders: args.httpHeaders,- withCredentials: args.withCredentials,- chunkedViewerLoading: args.chunkedViewerLoading,- disableAutoFetch: args.disableAutoFetch,- initialData: args.initialData- };- this.streamManager = new ChunkedStreamManager(args.length, RANGE_CHUNK_SIZE,- args.url, params);+ var entryRanges = streamState.entryRanges;+ while (entryRanges.length > 0) {- this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(),- args.password);- }+ var first = entryRanges[0];+ var n = entryRanges[1];- NetworkPdfManager.prototype = Object.create(BasePdfManager.prototype);- NetworkPdfManager.prototype.constructor = NetworkPdfManager;+ if (!isInt(first) || !isInt(n))+ error('Invalid XRef range fields: ' + first + ', ' + n);- NetworkPdfManager.prototype.ensure =- function NetworkPdfManager_ensure(obj, prop, args) {- var promise = new LegacyPromise();- this.ensureHelper(promise, obj, prop, args);- return promise;- };+ if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||+ !isInt(generationFieldWidth)) {+ error('Invalid XRef entry fields length: ' + first + ', ' + n);+ }+ for (i = streamState.entryNum; i < n; ++i) {+ streamState.entryNum = i;+ streamState.streamPos = stream.pos;- NetworkPdfManager.prototype.ensureHelper =- function NetworkPdfManager_ensureHelper(promise, obj, prop, args) {- try {- var result;- var value = obj[prop];- if (typeof(value) === 'function') {- result = value.apply(obj, args);- } else {- result = value;+ var type = 0, offset = 0, generation = 0;+ for (j = 0; j < typeFieldWidth; ++j)+ type = (type << 8) | stream.getByte();+ // if type field is absent, its default value = 1+ if (typeFieldWidth === 0)+ type = 1;+ for (j = 0; j < offsetFieldWidth; ++j)+ offset = (offset << 8) | stream.getByte();+ for (j = 0; j < generationFieldWidth; ++j)+ generation = (generation << 8) | stream.getByte();+ var entry = {};+ entry.offset = offset;+ entry.gen = generation;+ switch (type) {+ case 0:+ entry.free = true;+ break;+ case 1:+ entry.uncompressed = true;+ break;+ case 2:+ break;+ default:+ error('Invalid XRef entry type: ' + type);+ }+ if (!this.entries[first + i])+ this.entries[first + i] = entry;+ }++ streamState.entryNum = 0;+ streamState.streamPos = stream.pos;+ entryRanges.splice(0, 2);}- promise.resolve(result);- } catch(e) {- if (!(e instanceof MissingDataException)) {- console.log(e.stack);- promise.reject(e);- return;+ },+ indexObjects: function XRef_indexObjects() {+ // Simple scan through the PDF content to find objects,+ // trailers and XRef streams.+ function readToken(data, offset) {+ var token = '', ch = data[offset];+ while (ch !== 13 && ch !== 10) {+ if (++offset >= data.length)+ break;+ token += String.fromCharCode(ch);+ ch = data[offset];+ }+ return token;}+ function skipUntil(data, offset, what) {+ var length = what.length, dataLength = data.length;+ var skipped = 0;+ // finding byte sequence+ while (offset < dataLength) {+ var i = 0;+ while (i < length && data[offset + i] == what[i])+ ++i;+ if (i >= length)+ break; // sequence found- this.streamManager.requestRange(e.begin, e.end, function() {- this.ensureHelper(promise, obj, prop, args);- }.bind(this));- }- };+ offset++;+ skipped++;+ }+ return skipped;+ }+ var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);+ var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,+ 101, 102]);+ var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);+ var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);- NetworkPdfManager.prototype.requestRange =- function NetworkPdfManager_requestRange(begin, end) {- var promise = new LegacyPromise();- this.streamManager.requestRange(begin, end, function() {- promise.resolve();- });- return promise;- };+ var stream = this.stream;+ stream.pos = 0;+ var buffer = stream.getBytes();+ var position = stream.start, length = buffer.length;+ var trailers = [], xrefStms = [];+ var state = 0;+ var currentToken;+ while (position < length) {+ var ch = buffer[position];+ if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {+ ++position;+ continue;+ }+ if (ch === 37) { // %-comment+ do {+ ++position;+ ch = buffer[position];+ } while (ch !== 13 && ch !== 10);+ continue;+ }+ var token = readToken(buffer, position);+ var m;+ if (token === 'xref') {+ position += skipUntil(buffer, position, trailerBytes);+ trailers.push(position);+ position += skipUntil(buffer, position, startxrefBytes);+ } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {+ this.entries[m[1]] = {+ offset: position,+ gen: m[2] | 0,+ uncompressed: true+ };- NetworkPdfManager.prototype.requestLoadedStream =- function NetworkPdfManager_requestLoadedStream() {- this.streamManager.requestAllChunks();- };+ var contentLength = skipUntil(buffer, position, endobjBytes) + 7;+ var content = buffer.subarray(position, position + contentLength);- NetworkPdfManager.prototype.onLoadedStream =- function NetworkPdfManager_getLoadedStream() {- return this.streamManager.onLoadedStream();- };+ // checking XRef stream suspect+ // (it shall have '/XRef' and next char is not a letter)+ var xrefTagOffset = skipUntil(content, 0, xrefBytes);+ if (xrefTagOffset < contentLength &&+ content[xrefTagOffset + 5] < 64) {+ xrefStms.push(position);+ this.xrefstms[position] = 1; // don't read it recursively+ }- NetworkPdfManager.prototype.terminate =- function NetworkPdfManager_terminate() {- this.streamManager.networkManager.abortAllRequests();- };+ position += contentLength;+ } else+ position += token.length + 1;+ }+ // reading XRef streams+ for (var i = 0, ii = xrefStms.length; i < ii; ++i) {+ this.startXRefQueue.push(xrefStms[i]);+ this.readXRef(/* recoveryMode */ true);+ }+ // finding main trailer+ var dict;+ for (var i = 0, ii = trailers.length; i < ii; ++i) {+ stream.pos = trailers[i];+ var parser = new Parser(new Lexer(stream), true, null);+ var obj = parser.getObj();+ if (!isCmd(obj, 'trailer'))+ continue;+ // read the trailer dictionary+ if (!isDict(dict = parser.getObj()))+ continue;+ // taking the first one with 'ID'+ if (dict.has('ID'))+ return dict;+ }+ // no tailer with 'ID', taking last one (if exists)+ if (dict)+ return dict;+ // nothing helps+ // calling error() would reject worker with an UnknownErrorException.+ throw new InvalidPDFException('Invalid PDF structure');+ },- return NetworkPdfManager;-})();+ readXRef: function XRef_readXRef(recoveryMode) {+ var stream = this.stream;+ try {+ while (this.startXRefQueue.length) {+ var startXRef = this.startXRefQueue[0];+ stream.pos = startXRef;-var Page = (function PageClosure() {+ var parser = new Parser(new Lexer(stream), true, null);+ var obj = parser.getObj();+ var dict;- var LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];+ // Get dictionary+ if (isCmd(obj, 'xref')) {- function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {- this.pdfManager = pdfManager;- this.pageIndex = pageIndex;- this.pageDict = pageDict;- this.xref = xref;- this.ref = ref;- this.fontCache = fontCache;- this.idCounters = {- obj: 0- };- this.resourcesPromise = null;- }+ // Parse end-of-file XRef+ dict = this.processXRefTable(parser);+ if (!this.topDict) {+ this.topDict = dict;+ }- Page.prototype = {- getPageProp: function Page_getPageProp(key) {- return this.pageDict.get(key);- },+ // Recursively get other XRefs 'XRefStm', if any+ obj = dict.get('XRefStm');+ if (isInt(obj)) {+ var pos = obj;+ // ignore previously loaded xref streams+ // (possible infinite recursion)+ if (!(pos in this.xrefstms)) {+ this.xrefstms[pos] = 1;+ this.startXRefQueue.push(pos);+ }+ }+ } else if (isInt(obj)) {- getInheritedPageProp: function Page_inheritPageProp(key) {- var dict = this.pageDict;- var value = dict.get(key);- while (value === undefined) {- dict = dict.get('Parent');- if (!dict) {- break;+ // Parse in-stream XRef+ if (!isInt(parser.getObj()) ||+ !isCmd(parser.getObj(), 'obj') ||+ !isStream(obj = parser.getObj())) {+ error('Invalid XRef stream');+ }+ dict = this.processXRefStream(obj);+ if (!this.topDict) {+ this.topDict = dict;+ }++ if (!dict)+ error('Failed to read XRef stream');+ }++ // Recursively get previous dictionary, if any+ obj = dict.get('Prev');+ if (isInt(obj)) {+ this.startXRefQueue.push(obj);+ } else if (isRef(obj)) {+ // The spec says Prev must not be a reference, i.e. "/Prev NNN"+ // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"+ this.startXRefQueue.push(obj.num);+ }++ this.startXRefQueue.shift();}- value = dict.get(key);++ return this.topDict;+ } catch (e) {+ if (e instanceof MissingDataException) {+ throw e;+ }+ log('(while reading XRef): ' + e);}- return value;- },- get content() {- return this.getPageProp('Contents');+ if (recoveryMode)+ return;+ throw new XRefParseException();},- get resources() {- var value = this.getInheritedPageProp('Resources');- // For robustness: The spec states that a \Resources entry has to be- // present, but can be empty. Some document omit it still. In this case- // return an empty dictionary:- if (value === undefined) {- value = Dict.empty;- }- return shadow(this, 'resources', value);+ getEntry: function XRef_getEntry(i) {+ var e = this.entries[i];+ if (e === null)+ return null;+ return e.free || !e.offset ? null : e; // returns null if entry is free},-- get mediaBox() {- var obj = this.getInheritedPageProp('MediaBox');- // Reset invalid media box to letter size.- if (!isArray(obj) || obj.length !== 4) {- obj = LETTER_SIZE_MEDIABOX;- }- return shadow(this, 'mediaBox', obj);+ fetchIfRef: function XRef_fetchIfRef(obj) {+ if (!isRef(obj))+ return obj;+ return this.fetch(obj);},-- get view() {- var mediaBox = this.mediaBox;- var cropBox = this.getInheritedPageProp('CropBox');- if (!isArray(cropBox) || cropBox.length !== 4) {- return shadow(this, 'view', mediaBox);+ fetch: function XRef_fetch(ref, suppressEncryption) {+ assertWellFormed(isRef(ref), 'ref object is not a reference');+ var num = ref.num;+ var e;+ if (num in this.cache) {+ e = this.cache[num];+ if (e instanceof Stream) {+ return e.makeSubStream(e.start, e.length, e.dict);+ }+ return e;}- // From the spec, 6th ed., p.963:- // "The crop, bleed, trim, and art boxes should not ordinarily- // extend beyond the boundaries of the media box. If they do, they are- // effectively reduced to their intersection with the media box."- cropBox = Util.intersect(cropBox, mediaBox);- if (!cropBox) {- return shadow(this, 'view', mediaBox);- }- return shadow(this, 'view', cropBox);- },+ e = this.getEntry(num);- get annotationRefs() {- return shadow(this, 'annotationRefs',- this.getInheritedPageProp('Annots'));- },+ // the referenced entry can be free+ if (e === null)+ return (this.cache[num] = e);- get rotate() {- var rotate = this.getInheritedPageProp('Rotate') || 0;- // Normalize rotation so it's a multiple of 90 and between 0 and 270- if (rotate % 90 !== 0) {- rotate = 0;- } else if (rotate >= 360) {- rotate = rotate % 360;- } else if (rotate < 0) {- // The spec doesn't cover negatives, assume its counterclockwise- // rotation. The following is the other implementation of modulo.- rotate = ((rotate % 360) + 360) % 360;+ var gen = ref.gen;+ var stream, parser;+ if (e.uncompressed) {+ if (e.gen != gen)+ error('inconsistent generation in XRef');+ stream = this.stream.makeSubStream(e.offset);+ parser = new Parser(new Lexer(stream), true, this);+ var obj1 = parser.getObj();+ var obj2 = parser.getObj();+ var obj3 = parser.getObj();+ if (!isInt(obj1) || obj1 != num ||+ !isInt(obj2) || obj2 != gen ||+ !isCmd(obj3)) {+ error('bad XRef entry');+ }+ if (!isCmd(obj3, 'obj')) {+ // some bad pdfs use "obj1234" and really mean 1234+ if (obj3.cmd.indexOf('obj') === 0) {+ num = parseInt(obj3.cmd.substring(3), 10);+ if (!isNaN(num))+ return num;+ }+ error('bad XRef entry');+ }+ if (this.encrypt && !suppressEncryption) {+ try {+ e = parser.getObj(this.encrypt.createCipherTransform(num, gen));+ } catch (ex) {+ // almost all streams must be encrypted, but sometimes+ // they are not probably due to some broken generators+ // re-trying without encryption+ return this.fetch(ref, true);+ }+ } else {+ e = parser.getObj();+ }+ if (!isStream(e) || e instanceof JpegStream) {+ this.cache[num] = e;+ } else if (e instanceof Stream) {+ e = e.makeSubStream(e.start, e.length, e.dict);+ this.cache[num] = e;+ } else if ('readBlock' in e) {+ e.getBytes();+ e = e.makeSubStream(0, e.bufferLength, e.dict);+ this.cache[num] = e;+ }+ return e;}- return shadow(this, 'rotate', rotate);- },- getContentStream: function Page_getContentStream() {- var content = this.content;- var stream;- if (isArray(content)) {- // fetching items- var xref = this.xref;- var i, n = content.length;- var streams = [];- for (i = 0; i < n; ++i) {- streams.push(xref.fetchIfRef(content[i]));+ // compressed entry+ var tableOffset = e.offset;+ stream = this.fetch(new Ref(tableOffset, 0));+ if (!isStream(stream))+ error('bad ObjStm stream');+ var first = stream.dict.get('First');+ var n = stream.dict.get('N');+ if (!isInt(first) || !isInt(n)) {+ error('invalid first and n parameters for ObjStm stream');+ }+ parser = new Parser(new Lexer(stream), false, this);+ parser.allowStreams = true;+ var i, entries = [], nums = [];+ // read the object numbers to populate cache+ for (i = 0; i < n; ++i) {+ num = parser.getObj();+ if (!isInt(num)) {+ error('invalid object number in the ObjStm stream: ' + num);+ }+ nums.push(num);+ var offset = parser.getObj();+ if (!isInt(offset)) {+ error('invalid object offset in the ObjStm stream: ' + offset);}- stream = new StreamsSequenceStream(streams);- } else if (isStream(content)) {- stream = content;- } else {- // replacing non-existent page content with empty one- stream = new NullStream();}- return stream;+ // read stream objects for cache+ for (i = 0; i < n; ++i) {+ entries.push(parser.getObj());+ num = nums[i];+ var entry = this.entries[num];+ if (entry && entry.offset === tableOffset && entry.gen === i) {+ this.cache[num] = entries[i];+ }+ }+ e = entries[e.gen];+ if (e === undefined) {+ error('bad XRef entry for compressed object');+ }+ return e;},-- loadResources: function(keys) {- if (!this.resourcesPromise) {- // TODO: add async getInheritedPageProp and remove this.- this.resourcesPromise = this.pdfManager.ensure(this, 'resources');+ fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {+ if (!isRef(obj)) {+ var promise = new Promise();+ promise.resolve(obj);+ return promise;}- var promise = new LegacyPromise();- this.resourcesPromise.then(function resourceSuccess() {- var objectLoader = new ObjectLoader(this.resources.map,- keys,- this.xref);- objectLoader.load().then(function objectLoaderSuccess() {- promise.resolve();- });- }.bind(this));+ return this.fetchAsync(obj);+ },+ fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {+ var promise = new Promise();+ var tryFetch = function (promise) {+ try {+ promise.resolve(this.fetch(ref, suppressEncryption));+ } catch (e) {+ if (e instanceof MissingDataException) {+ this.stream.manager.requestRange(e.begin, e.end, tryFetch);+ return;+ }+ promise.reject(e);+ }+ }.bind(this, promise);+ tryFetch();return promise;},+ getCatalogObj: function XRef_getCatalogObj() {+ return this.root;+ }+ };- getOperatorList: function Page_getOperatorList(handler, intent) {- var self = this;- var promise = new LegacyPromise();-- function reject(e) {- promise.reject(e);- }+ return XRef;+})();- var pageListPromise = new LegacyPromise();+/**+ * A NameTree is like a Dict but has some adventagous properties, see the spec+ * (7.9.6) for more details.+ * TODO: implement all the Dict functions and make this more efficent.+ */+var NameTree = (function NameTreeClosure() {+ function NameTree(root, xref) {+ this.root = root;+ this.xref = xref;+ }- var pdfManager = this.pdfManager;- var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',- []);- var resourcesPromise = this.loadResources([- 'ExtGState',- 'ColorSpace',- 'Pattern',- 'Shading',- 'XObject',- 'Font'- // ProcSet- // Properties- ]);+ NameTree.prototype = {+ getAll: function NameTree_getAll() {+ var dict = {};+ if (!this.root) {+ return dict;+ }+ var xref = this.xref;+ // reading name tree+ var processed = new RefSet();+ processed.put(this.root);+ var queue = [this.root];+ while (queue.length > 0) {+ var i, n;+ var obj = xref.fetchIfRef(queue.shift());+ if (!isDict(obj)) {+ continue;+ }+ if (obj.has('Kids')) {+ var kids = obj.get('Kids');+ for (i = 0, n = kids.length; i < n; i++) {+ var kid = kids[i];+ if (processed.has(kid))+ error('invalid destinations');+ queue.push(kid);+ processed.put(kid);+ }+ continue;+ }+ var names = obj.get('Names');+ if (names) {+ for (i = 0, n = names.length; i < n; i += 2) {+ dict[names[i]] = xref.fetchIfRef(names[i + 1]);+ }+ }+ }+ return dict;+ }+ };+ return NameTree;+})();- var partialEvaluator = new PartialEvaluator(pdfManager, this.xref,- handler, this.pageIndex,- 'p' + this.pageIndex + '_',- this.idCounters,- this.fontCache);+/**+ * A PDF document and page is built of many objects. E.g. there are objects+ * for fonts, images, rendering code and such. These objects might get processed+ * inside of a worker. The `PDFObjects` implements some basic functions to+ * manage these objects.+ */+var PDFObjects = (function PDFObjectsClosure() {+ function PDFObjects() {+ this.objs = {};+ }- var dataPromises = Promise.all([contentStreamPromise, resourcesPromise],- reject);- dataPromises.then(function(data) {- var contentStream = data[0];- var opList = new OperatorList(intent, handler, self.pageIndex);+ PDFObjects.prototype = {+ /**+ * Internal function.+ * Ensures there is an object defined for `objId`.+ */+ ensureObj: function PDFObjects_ensureObj(objId) {+ if (this.objs[objId])+ return this.objs[objId];++ var obj = {+ promise: new Promise(objId),+ data: null,+ resolved: false+ };+ this.objs[objId] = obj;- handler.send('StartRenderPage', {- transparency: partialEvaluator.hasBlendModes(self.resources),- pageIndex: self.pageIndex,- intent: intent- });- partialEvaluator.getOperatorList(contentStream, self.resources, opList);- pageListPromise.resolve(opList);- });+ return obj;+ },- var annotationsPromise = pdfManager.ensure(this, 'annotations');- Promise.all([pageListPromise, annotationsPromise]).then(function(datas) {- var pageOpList = datas[0];- var annotations = datas[1];+ /**+ * If called *without* callback, this returns the data of `objId` but the+ * object needs to be resolved. If it isn't, this function throws.+ *+ * If called *with* a callback, the callback is called with the data of the+ * object once the object is resolved. That means, if you call this+ * function and the object is already resolved, the callback gets called+ * right away.+ */+ get: function PDFObjects_get(objId, callback) {+ // If there is a callback, then the get can be async and the object is+ // not required to be resolved right now+ if (callback) {+ this.ensureObj(objId).promise.then(callback);+ return null;+ }- if (annotations.length === 0) {- pageOpList.flush(true);- promise.resolve(pageOpList);- return;- }+ // If there isn't a callback, the user expects to get the resolved data+ // directly.+ var obj = this.objs[objId];- var annotationsReadyPromise = Annotation.appendToOperatorList(- annotations, pageOpList, pdfManager, partialEvaluator, intent);- annotationsReadyPromise.then(function () {- pageOpList.flush(true);- promise.resolve(pageOpList);- }, reject);- }, reject);+ // If there isn't an object yet or the object isn't resolved, then the+ // data isn't ready yet!+ if (!obj || !obj.resolved)+ error('Requesting object that isn\'t resolved yet ' + objId);- return promise;+ return obj.data;},- extractTextContent: function Page_extractTextContent() {- var handler = {- on: function nullHandlerOn() {},- send: function nullHandlerSend() {}- };+ /**+ * Resolves the object `objId` with optional `data`.+ */+ resolve: function PDFObjects_resolve(objId, data) {+ var obj = this.ensureObj(objId);- var self = this;+ obj.resolved = true;+ obj.data = data;+ obj.promise.resolve(data);+ },- var pdfManager = this.pdfManager;- var contentStreamPromise = pdfManager.ensure(this, 'getContentStream',- []);+ isResolved: function PDFObjects_isResolved(objId) {+ var objs = this.objs;- var resourcesPromise = this.loadResources([- 'ExtGState',- 'XObject',- 'Font'- ]);+ if (!objs[objId]) {+ return false;+ } else {+ return objs[objId].resolved;+ }+ },- var dataPromises = Promise.all([contentStreamPromise,- resourcesPromise]);- return dataPromises.then(function(data) {- var contentStream = data[0];- var partialEvaluator = new PartialEvaluator(pdfManager, self.xref,- handler, self.pageIndex,- 'p' + self.pageIndex + '_',- self.idCounters,- self.fontCache);-- return partialEvaluator.getTextContent(contentStream,- self.resources);- });+ hasData: function PDFObjects_hasData(objId) {+ return this.isResolved(objId);},- getAnnotationsData: function Page_getAnnotationsData() {- var annotations = this.annotations;- var annotationsData = [];- for (var i = 0, n = annotations.length; i < n; ++i) {- annotationsData.push(annotations[i].getData());+ /**+ * Returns the data of `objId` if object exists, null otherwise.+ */+ getData: function PDFObjects_getData(objId) {+ var objs = this.objs;+ if (!objs[objId] || !objs[objId].resolved) {+ return null;+ } else {+ return objs[objId].data;}- return annotationsData;},- get annotations() {- var annotations = [];- var annotationRefs = (this.annotationRefs || []);- for (var i = 0, n = annotationRefs.length; i < n; ++i) {- var annotationRef = annotationRefs[i];- var annotation = Annotation.fromRef(this.xref, annotationRef);- if (annotation) {- annotations.push(annotation);- }- }- return shadow(this, 'annotations', annotations);+ clear: function PDFObjects_clear() {+ this.objs = {};}};-- return Page;+ return PDFObjects;})();/**- * The `PDFDocument` holds all the data of the PDF file. Compared to the- * `PDFDoc`, this one doesn't have any job management code.- * Right now there exists one PDFDocument on the main thread + one object- * for each worker. If there is no worker support enabled, there are two- * `PDFDocument` objects on the main thread created.+ * A helper for loading missing data in object graphs. It traverses the graph+ * depth first and queues up any objects that have missing data. Once it has+ * has traversed as many objects that are available it attempts to bundle the+ * missing data requests and then resume from the nodes that weren't ready.+ *+ * NOTE: It provides protection from circular references by keeping track of+ * of loaded references. However, you must be careful not to load any graphs+ * that have references to the catalog or other pages since that will cause the+ * entire PDF document object graph to be traversed.*/-var PDFDocument = (function PDFDocumentClosure() {- function PDFDocument(pdfManager, arg, password) {- if (isStream(arg)) {- init.call(this, pdfManager, arg, password);- } else if (isArrayBuffer(arg)) {- init.call(this, pdfManager, new Stream(arg), password);- } else {- error('PDFDocument: Unknown argument type');+var ObjectLoader = (function() {++ function mayHaveChildren(value) {+ return isRef(value) || isDict(value) || isArray(value) || isStream(value);+ }++ function addChildren(node, nodesToVisit) {+ if (isDict(node) || isStream(node)) {+ var map;+ if (isDict(node)) {+ map = node.map;+ } else {+ map = node.dict.map;+ }+ for (var key in map) {+ var value = map[key];+ if (mayHaveChildren(value)) {+ nodesToVisit.push(value);+ }+ }+ } else if (isArray(node)) {+ for (var i = 0, ii = node.length; i < ii; i++) {+ var value = node[i];+ if (mayHaveChildren(value)) {+ nodesToVisit.push(value);+ }+ }}}- function init(pdfManager, stream, password) {- assert(stream.length > 0, 'stream must have data');- this.pdfManager = pdfManager;- this.stream = stream;- var xref = new XRef(this.stream, password, pdfManager);+ function ObjectLoader(obj, keys, xref) {+ this.obj = obj;+ this.keys = keys;this.xref = xref;+ this.refSet = null;}- function find(stream, needle, limit, backwards) {- var pos = stream.pos;- var end = stream.end;- var strBuf = [];- if (pos + limit > end) {- limit = end - pos;- }- for (var n = 0; n < limit; ++n) {- strBuf.push(String.fromCharCode(stream.getByte()));- }- var str = strBuf.join('');- stream.pos = pos;- var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);- if (index == -1) {- return false; /* not found */- }- stream.pos += index;- return true; /* found */- }+ ObjectLoader.prototype = {- var DocumentInfoValidators = {- get entries() {- // Lazily build this since all the validation functions below are not- // defined until after this file loads.- return shadow(this, 'entries', {- Title: isString,- Author: isString,- Subject: isString,- Keywords: isString,- Creator: isString,- Producer: isString,- CreationDate: isString,- ModDate: isString,- Trapped: isName- });- }- };+ load: function ObjectLoader_load() {+ var keys = this.keys;+ this.promise = new Promise();+ // Don't walk the graph if all the data is already loaded.+ if (!(this.xref.stream instanceof ChunkedStream) ||+ this.xref.stream.getMissingChunks().length === 0) {+ this.promise.resolve();+ return this.promise;+ }- PDFDocument.prototype = {- parse: function PDFDocument_parse(recoveryMode) {- this.setup(recoveryMode);- try {- // checking if AcroForm is present- this.acroForm = this.catalog.catDict.get('AcroForm');- if (this.acroForm) {- this.xfa = this.acroForm.get('XFA');- var fields = this.acroForm.get('Fields');- if ((!fields || !isArray(fields) || fields.length === 0) &&- !this.xfa) {- // no fields and no XFA -- not a form (?)- this.acroForm = null;- }- }- } catch (ex) {- info('Something wrong with AcroForm entry');- this.acroForm = null;+ this.refSet = new RefSet();+ // Setup the initial nodes to visit.+ var nodesToVisit = [];+ for (var i = 0; i < keys.length; i++) {+ nodesToVisit.push(this.obj[keys[i]]);}++ this.walk(nodesToVisit);+ return this.promise;},- get linearization() {- var length = this.stream.length;- var linearization = false;- if (length) {- try {- linearization = new Linearization(this.stream);- if (linearization.length != length) {- linearization = false;- }- } catch (err) {- if (err instanceof MissingDataException) {- throw err;- }+ walk: function ObjectLoader_walk(nodesToVisit) {+ var nodesToRevisit = [];+ var pendingRequests = [];+ // DFS walk of the object graph.+ while (nodesToVisit.length) {+ var currentNode = nodesToVisit.pop();- info('The linearization data is not available ' +- 'or unreadable PDF data is found');- linearization = false;- }- }- // shadow the prototype getter with a data property- return shadow(this, 'linearization', linearization);- },- get startXRef() {- var stream = this.stream;- var startXRef = 0;- var linearization = this.linearization;- if (linearization) {- // Find end of first obj.- stream.reset();- if (find(stream, 'endobj', 1024)) {- startXRef = stream.pos + 6;- }- } else {- // Find startxref by jumping backward from the end of the file.- var step = 1024;- var found = false, pos = stream.end;- while (!found && pos > 0) {- pos -= step - 'startxref'.length;- if (pos < 0) {- pos = 0;- }- stream.pos = pos;- found = find(stream, 'startxref', step, true);- }- if (found) {- stream.skip(9);- var ch;- do {- ch = stream.getByte();- } while (Lexer.isSpace(ch));- var str = '';- while (ch >= 0x20 && ch <= 0x39) { // < '9'- str += String.fromCharCode(ch);- ch = stream.getByte();- }- startXRef = parseInt(str, 10);- if (isNaN(startXRef)) {- startXRef = 0;- }- }- }- // shadow the prototype getter with a data property- return shadow(this, 'startXRef', startXRef);- },- get mainXRefEntriesOffset() {- var mainXRefEntriesOffset = 0;- var linearization = this.linearization;- if (linearization) {- mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;- }- // shadow the prototype getter with a data property- return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);- },- // Find the header, remove leading garbage and setup the stream- // starting from the header.- checkHeader: function PDFDocument_checkHeader() {- var stream = this.stream;- stream.reset();- if (find(stream, '%PDF-', 1024)) {- // Found the header, trim off any garbage before it.- stream.moveStart();- // Reading file format version- var MAX_VERSION_LENGTH = 12;- var version = '', ch;- while ((ch = stream.getByte()) > 0x20) { // SPACE- if (version.length >= MAX_VERSION_LENGTH) {- break;+ // Only references or chunked streams can cause missing data exceptions.+ if (isRef(currentNode)) {+ // Skip nodes that have already been visited.+ if (this.refSet.has(currentNode)) {+ continue;}- version += String.fromCharCode(ch);- }- // removing "%PDF-"-prefix- this.pdfFormatVersion = version.substring(5);- return;- }- // May not be a PDF file, continue anyway.- },- parseStartXRef: function PDFDocument_parseStartXRef() {- var startXRef = this.startXRef;- this.xref.setStartXRef(startXRef);- },- setup: function PDFDocument_setup(recoveryMode) {- this.xref.parse(recoveryMode);- this.catalog = new Catalog(this.pdfManager, this.xref);- },- get numPages() {- var linearization = this.linearization;- var num = linearization ? linearization.numPages : this.catalog.numPages;- // shadow the prototype getter- return shadow(this, 'numPages', num);- },- get documentInfo() {- var docInfo = {- PDFFormatVersion: this.pdfFormatVersion,- IsAcroFormPresent: !!this.acroForm,- IsXFAPresent: !!this.xfa- };- var infoDict;- try {- infoDict = this.xref.trailer.get('Info');- } catch (err) {- info('The document information dictionary is invalid.');- }- if (infoDict) {- var validEntries = DocumentInfoValidators.entries;- // Only fill the document info with valid entries from the spec.- for (var key in validEntries) {- if (infoDict.has(key)) {- var value = infoDict.get(key);- // Make sure the value conforms to the spec.- if (validEntries[key](value)) {- docInfo[key] = (typeof value !== 'string' ?- value : stringToPDFString(value));- } else {- info('Bad value in document info for "' + key + '"');+ try {+ var ref = currentNode;+ this.refSet.put(ref);+ currentNode = this.xref.fetch(currentNode);+ } catch (e) {+ if (!(e instanceof MissingDataException)) {+ throw e;}+ nodesToRevisit.push(currentNode);+ pendingRequests.push({ begin: e.begin, end: e.end });}}- }- return shadow(this, 'documentInfo', docInfo);- },- get fingerprint() {- var xref = this.xref, hash, fileID = '';+ if (currentNode instanceof ChunkedStream &&+ currentNode.getMissingChunks().length) {+ nodesToRevisit.push(currentNode);+ pendingRequests.push({+ begin: currentNode.start,+ end: currentNode.end+ });+ }- if (xref.trailer.has('ID')) {- hash = stringToBytes(xref.trailer.get('ID')[0]);- } else {- hash = calculateMD5(this.stream.bytes.subarray(0, 100), 0, 100);+ addChildren(currentNode, nodesToVisit);}- for (var i = 0, n = hash.length; i < n; i++) {- fileID += hash[i].toString(16);+ if (pendingRequests.length) {+ this.xref.stream.manager.requestRanges(pendingRequests,+ function pendingRequestCallback() {+ nodesToVisit = nodesToRevisit;+ for (var i = 0; i < nodesToRevisit.length; i++) {+ var node = nodesToRevisit[i];+ // Remove any reference nodes from the currrent refset so they+ // aren't skipped when we revist them.+ if (isRef(node)) {+ this.refSet.remove(node);+ }+ }+ this.walk(nodesToVisit);+ }.bind(this));+ return;}-- return shadow(this, 'fingerprint', fileID);- },-- getPage: function PDFDocument_getPage(pageIndex) {- return this.catalog.getPage(pageIndex);- },-- cleanup: function PDFDocument_cleanup() {- return this.catalog.cleanup();+ // Everything is loaded.+ this.refSet = null;+ this.promise.resolve();}+};- return PDFDocument;+ return ObjectLoader;})();-var Name = (function NameClosure() {- function Name(name) {- this.name = name;- }-- Name.prototype = {};-- var nameCache = {};- Name.get = function Name_get(name) {- var nameValue = nameCache[name];- return (nameValue ? nameValue : (nameCache[name] = new Name(name)));- };+var Annotation = (function AnnotationClosure() {+ // 12.5.5: Algorithm: Appearance streams+ function getTransformMatrix(rect, bbox, matrix) {+ var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);+ var minX = bounds[0];+ var minY = bounds[1];+ var maxX = bounds[2];+ var maxY = bounds[3];- return Name;-})();+ if (minX === maxX || minY === maxY) {+ // From real-life file, bbox was [0, 0, 0, 0]. In this case,+ // just apply the transform for rect+ return [1, 0, 0, 1, rect[0], rect[1]];+ }-var Cmd = (function CmdClosure() {- function Cmd(cmd) {- this.cmd = cmd;+ var xRatio = (rect[2] - rect[0]) / (maxX - minX);+ var yRatio = (rect[3] - rect[1]) / (maxY - minY);+ return [+ xRatio,+ 0,+ 0,+ yRatio,+ rect[0] - minX * xRatio,+ rect[1] - minY * yRatio+ ];}- Cmd.prototype = {};+ function getDefaultAppearance(dict) {+ var appearanceState = dict.get('AP');+ if (!isDict(appearanceState)) {+ return;+ }- var cmdCache = {};+ var appearance;+ var appearances = appearanceState.get('N');+ if (isDict(appearances)) {+ var as = dict.get('AS');+ if (as && appearances.has(as.name)) {+ appearance = appearances.get(as.name);+ }+ } else {+ appearance = appearances;+ }+ return appearance;+ }- Cmd.get = function Cmd_get(cmd) {- var cmdValue = cmdCache[cmd];- return (cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)));- };+ function Annotation(params) {+ if (params.data) {+ this.data = params.data;+ return;+ }- return Cmd;-})();+ var dict = params.dict;+ var data = this.data = {};-var Dict = (function DictClosure() {- var nonSerializable = function nonSerializableClosure() {- return nonSerializable; // creating closure on some variable- };+ data.subtype = dict.get('Subtype').name;+ var rect = dict.get('Rect');+ data.rect = Util.normalizeRect(rect);+ data.annotationFlags = dict.get('F');- var GETALL_DICTIONARY_TYPES_WHITELIST = {- 'Background': true,- 'ExtGState': true,- 'Halftone': true,- 'Layout': true,- 'Mask': true,- 'Pagination': true,- 'Printing': true- };+ var color = dict.get('C');+ if (isArray(color) && color.length === 3) {+ // TODO(mack): currently only supporting rgb; need support different+ // colorspaces+ data.color = color;+ } else {+ data.color = [0, 0, 0];+ }- function isRecursionAllowedFor(dict) {- if (!isName(dict.Type)) {- return true;+ // Some types of annotations have border style dict which has more+ // info than the border array+ if (dict.has('BS')) {+ var borderStyle = dict.get('BS');+ data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;+ } else {+ var borderArray = dict.get('Border') || [0, 0, 1];+ data.borderWidth = borderArray[2];}- var dictType = dict.Type.name;- return GETALL_DICTIONARY_TYPES_WHITELIST[dictType] === true;- }- // xref is optional- function Dict(xref) {- // Map should only be used internally, use functions below to access.- this.map = Object.create(null);- this.xref = xref;- this.objId = null;- this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict+ this.appearance = getDefaultAppearance(dict);}- Dict.prototype = {- assignXref: function Dict_assignXref(newXref) {- this.xref = newXref;- },+ Annotation.prototype = {- // automatically dereferences Ref objects- get: function Dict_get(key1, key2, key3) {- var value;- var xref = this.xref;- if (typeof (value = this.map[key1]) != 'undefined' || key1 in this.map ||- typeof key2 == 'undefined') {- return xref ? xref.fetchIfRef(value) : value;- }- if (typeof (value = this.map[key2]) != 'undefined' || key2 in this.map ||- typeof key3 == 'undefined') {- return xref ? xref.fetchIfRef(value) : value;- }- value = this.map[key3] || null;- return xref ? xref.fetchIfRef(value) : value;+ getData: function Annotation_getData() {+ return this.data;},- // Same as get(), but returns a promise and uses fetchIfRefAsync().- getAsync: function Dict_getAsync(key1, key2, key3) {- var value;- var promise;- var xref = this.xref;- if (typeof (value = this.map[key1]) !== undefined || key1 in this.map ||- typeof key2 === undefined) {- if (xref) {- return xref.fetchIfRefAsync(value);- }- promise = new LegacyPromise();- promise.resolve(value);- return promise;- }- if (typeof (value = this.map[key2]) !== undefined || key2 in this.map ||- typeof key3 === undefined) {- if (xref) {- return xref.fetchIfRefAsync(value);- }- promise = new LegacyPromise();- promise.resolve(value);- return promise;- }- value = this.map[key3] || null;- if (xref) {- return xref.fetchIfRefAsync(value);- }- promise = new LegacyPromise();- promise.resolve(value);- return promise;+ hasHtml: function Annotation_hasHtml() {+ return false;},- // no dereferencing- getRaw: function Dict_getRaw(key) {- return this.map[key];+ getHtmlElement: function Annotation_getHtmlElement(commonObjs) {+ throw new NotImplementedException(+ 'getHtmlElement() should be implemented in subclass');},- // creates new map and dereferences all Refs- getAll: function Dict_getAll() {- var all = Object.create(null);- var queue = null;- var key, obj;- for (key in this.map) {- obj = this.get(key);- if (obj instanceof Dict) {- if (isRecursionAllowedFor(obj)) {- (queue || (queue = [])).push({target: all, key: key, obj: obj});- } else {- all[key] = this.getRaw(key);- }- } else {- all[key] = obj;- }- }- if (!queue) {- return all;- }+ // TODO(mack): Remove this, it's not really that helpful.+ getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect) {+ assert(!isWorker,+ 'getEmptyContainer() should be called from main thread');- // trying to take cyclic references into the account- var processed = Object.create(null);- while (queue.length > 0) {- var item = queue.shift();- var itemObj = item.obj;- var objId = itemObj.objId;- if (objId && objId in processed) {- item.target[item.key] = processed[objId];- continue;- }- var dereferenced = Object.create(null);- for (key in itemObj.map) {- obj = itemObj.get(key);- if (obj instanceof Dict) {- if (isRecursionAllowedFor(obj)) {- queue.push({target: dereferenced, key: key, obj: obj});- } else {- dereferenced[key] = itemObj.getRaw(key);- }- } else {- dereferenced[key] = obj;- }- }- if (objId) {- processed[objId] = dereferenced;- }- item.target[item.key] = dereferenced;- }- return all;+ rect = rect || this.data.rect;+ var element = document.createElement(tagName);+ element.style.width = Math.ceil(rect[2] - rect[0]) + 'px';+ element.style.height = Math.ceil(rect[3] - rect[1]) + 'px';+ return element;},- set: function Dict_set(key, value) {- this.map[key] = value;+ isViewable: function Annotation_isViewable() {+ var data = this.data;+ return !!(+ data &&+ (!data.annotationFlags ||+ !(data.annotationFlags & 0x22)) && // Hidden or NoView+ data.rect // rectangle is nessessary+ );},- has: function Dict_has(key) {- return key in this.map;+ loadResources: function(keys) {+ var promise = new Promise();+ this.appearance.dict.getAsync('Resources').then(function(resources) {+ if (!resources) {+ promise.resolve();+ return;+ }+ var objectLoader = new ObjectLoader(resources.map,+ keys,+ resources.xref);+ objectLoader.load().then(function() {+ promise.resolve(resources);+ });+ }.bind(this));++ return promise;},- forEach: function Dict_forEach(callback) {- for (var key in this.map) {- callback(key, this.get(key));- }- }- };+ getOperatorList: function Annotation_getToOperatorList(evaluator) {- Dict.empty = new Dict(null);+ var promise = new Promise();- return Dict;-})();+ if (!this.appearance) {+ promise.resolve({+ queue: {+ fnArray: [],+ argsArray: []+ },+ dependency: {}+ });+ return promise;+ }-var Ref = (function RefClosure() {- function Ref(num, gen) {- this.num = num;- this.gen = gen;- }+ var data = this.data;- Ref.prototype = {};+ var appearanceDict = this.appearance.dict;+ var resourcesPromise = this.loadResources([+ 'ExtGState',+ 'ColorSpace',+ 'Pattern',+ 'Shading',+ 'XObject',+ 'Font'+ // ProcSet+ // Properties+ ]);+ var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];+ var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];+ var transform = getTransformMatrix(data.rect, bbox, matrix);- return Ref;-})();+ var border = data.border;-// The reference is identified by number and generation.-// This structure stores only one instance of the reference.-var RefSet = (function RefSetClosure() {- function RefSet() {- this.dict = {};- }+ resourcesPromise.then(function(resources) {+ var listPromise = evaluator.getOperatorList(this.appearance, resources);+ listPromise.then(function(appearanceStreamData) {+ var fnArray = appearanceStreamData.queue.fnArray;+ var argsArray = appearanceStreamData.queue.argsArray;- RefSet.prototype = {- has: function RefSet_has(ref) {- return ('R' + ref.num + '.' + ref.gen) in this.dict;- },+ fnArray.unshift('beginAnnotation');+ argsArray.unshift([data.rect, transform, matrix]);- put: function RefSet_put(ref) {- this.dict['R' + ref.num + '.' + ref.gen] = true;- },+ fnArray.push('endAnnotation');+ argsArray.push([]);- remove: function RefSet_remove(ref) {- delete this.dict['R' + ref.num + '.' + ref.gen];+ promise.resolve(appearanceStreamData);+ });+ }.bind(this));++ return promise;}};- return RefSet;-})();+ Annotation.getConstructor =+ function Annotation_getConstructor(subtype, fieldType) {-var RefSetCache = (function RefSetCacheClosure() {- function RefSetCache() {- this.dict = Object.create(null);- }+ if (!subtype) {+ return;+ }- RefSetCache.prototype = {- get: function RefSetCache_get(ref) {- return this.dict['R' + ref.num + '.' + ref.gen];- },+ // TODO(mack): Implement FreeText annotations+ if (subtype === 'Link') {+ return LinkAnnotation;+ } else if (subtype === 'Text') {+ return TextAnnotation;+ } else if (subtype === 'Widget') {+ if (!fieldType) {+ return;+ }- has: function RefSetCache_has(ref) {- return ('R' + ref.num + '.' + ref.gen) in this.dict;- },+ if (fieldType === 'Tx') {+ return TextWidgetAnnotation;+ } else {+ return WidgetAnnotation;+ }+ } else {+ return Annotation;+ }+ };- put: function RefSetCache_put(ref, obj) {- this.dict['R' + ref.num + '.' + ref.gen] = obj;- },+ // TODO(mack): Support loading annotation from data+ Annotation.fromData = function Annotation_fromData(data) {+ var subtype = data.subtype;+ var fieldType = data.fieldType;+ var Constructor = Annotation.getConstructor(subtype, fieldType);+ if (Constructor) {+ return new Constructor({ data: data });+ }+ };- putAlias: function RefSetCache_putAlias(ref, aliasRef) {- this.dict['R' + ref.num + '.' + ref.gen] = this.get(aliasRef);- },+ Annotation.fromRef = function Annotation_fromRef(xref, ref) {- forEach: function RefSetCache_forEach(fn, thisArg) {- for (var i in this.dict) {- fn.call(thisArg, this.dict[i]);- }- },+ var dict = xref.fetchIfRef(ref);+ if (!isDict(dict)) {+ return;+ }- clear: function RefSetCache_clear() {- this.dict = Object.create(null);+ var subtype = dict.get('Subtype');+ subtype = isName(subtype) ? subtype.name : '';+ if (!subtype) {+ return;}- };- return RefSetCache;-})();+ var fieldType = Util.getInheritableProperty(dict, 'FT');+ fieldType = isName(fieldType) ? fieldType.name : '';-var Catalog = (function CatalogClosure() {- function Catalog(pdfManager, xref) {- this.pdfManager = pdfManager;- this.xref = xref;- this.catDict = xref.getCatalogObj();- this.fontCache = new RefSetCache();- assert(isDict(this.catDict),- 'catalog object is not a dictionary');+ var Constructor = Annotation.getConstructor(subtype, fieldType);+ if (!Constructor) {+ return;+ }- this.pagePromises = [];- }+ var params = {+ dict: dict,+ ref: ref,+ };- Catalog.prototype = {- get metadata() {- var streamRef = this.catDict.getRaw('Metadata');- if (!isRef(streamRef)) {- return shadow(this, 'metadata', null);- }+ var annotation = new Constructor(params);- var encryptMetadata = (!this.xref.encrypt ? false :- this.xref.encrypt.encryptMetadata);+ if (annotation.isViewable()) {+ return annotation;+ } else {+ TODO('unimplemented annotation type: ' + subtype);+ }+ };- var stream = this.xref.fetch(streamRef, !encryptMetadata);- var metadata;- if (stream && isDict(stream.dict)) {- var type = stream.dict.get('Type');- var subtype = stream.dict.get('Subtype');+ Annotation.appendToOperatorList = function Annotation_appendToOperatorList(+ annotations, pageQueue, pdfManager, dependencies, partialEvaluator) {- if (isName(type) && isName(subtype) &&- type.name === 'Metadata' && subtype.name === 'XML') {- // XXX: This should examine the charset the XML document defines,- // however since there are currently no real means to decode- // arbitrary charsets, let's just hope that the author of the PDF- // was reasonable enough to stick with the XML default charset,- // which is UTF-8.- try {- metadata = stringToUTF8String(bytesToString(stream.getBytes()));- } catch (e) {- info('Skipping invalid metadata.');- }- }- }+ function reject(e) {+ annotationsReadyPromise.reject(e);+ }- return shadow(this, 'metadata', metadata);- },- get toplevelPagesDict() {- var pagesObj = this.catDict.get('Pages');- assert(isDict(pagesObj), 'invalid top-level pages dictionary');- // shadow the prototype getter- return shadow(this, 'toplevelPagesDict', pagesObj);- },- get documentOutline() {- var obj = null;- try {- obj = this.readDocumentOutline();- } catch (ex) {- if (ex instanceof MissingDataException) {- throw ex;- }- warn('Unable to read document outline');- }- return shadow(this, 'documentOutline', obj);- },- readDocumentOutline: function Catalog_readDocumentOutline() {- var xref = this.xref;- var obj = this.catDict.get('Outlines');- var root = { items: [] };- if (isDict(obj)) {- obj = obj.getRaw('First');- var processed = new RefSet();- if (isRef(obj)) {- var queue = [{obj: obj, parent: root}];- // to avoid recursion keeping track of the items- // in the processed dictionary- processed.put(obj);- while (queue.length > 0) {- var i = queue.shift();- var outlineDict = xref.fetchIfRef(i.obj);- if (outlineDict === null) {- continue;- }- if (!outlineDict.has('Title')) {- error('Invalid outline item');- }- var dest = outlineDict.get('A');- if (dest) {- dest = dest.get('D');- } else if (outlineDict.has('Dest')) {- dest = outlineDict.getRaw('Dest');- if (isName(dest)) {- dest = dest.name;- }- }- var title = outlineDict.get('Title');- var outlineItem = {- dest: dest,- title: stringToPDFString(title),- color: outlineDict.get('C') || [0, 0, 0],- count: outlineDict.get('Count'),- bold: !!(outlineDict.get('F') & 2),- italic: !!(outlineDict.get('F') & 1),- items: []- };- i.parent.items.push(outlineItem);- obj = outlineDict.getRaw('First');- if (isRef(obj) && !processed.has(obj)) {- queue.push({obj: obj, parent: outlineItem});- processed.put(obj);- }- obj = outlineDict.getRaw('Next');- if (isRef(obj) && !processed.has(obj)) {- queue.push({obj: obj, parent: i.parent});- processed.put(obj);- }- }- }- }- return (root.items.length > 0 ? root.items : null);- },- get numPages() {- var obj = this.toplevelPagesDict.get('Count');- assert(- isInt(obj),- 'page count in top level pages object is not an integer'- );- // shadow the prototype getter- return shadow(this, 'num', obj);- },- get destinations() {- function fetchDestination(dest) {- return isDict(dest) ? dest.get('D') : dest;- }+ var annotationsReadyPromise = new Promise();- var xref = this.xref;- var dests = {}, nameTreeRef, nameDictionaryRef;- var obj = this.catDict.get('Names');- if (obj) {- nameTreeRef = obj.getRaw('Dests');- } else if (this.catDict.has('Dests')) {- nameDictionaryRef = this.catDict.get('Dests');- }+ var annotationPromises = [];+ for (var i = 0, n = annotations.length; i < n; ++i) {+ annotationPromises.push(annotations[i].getOperatorList(partialEvaluator));+ }- if (nameDictionaryRef) {- // reading simple destination dictionary- obj = nameDictionaryRef;- obj.forEach(function catalogForEach(key, value) {- if (!value) {- return;- }- dests[key] = fetchDestination(value);- });- }- if (nameTreeRef) {- var nameTree = new NameTree(nameTreeRef, xref);- var names = nameTree.getAll();- for (var name in names) {- if (!names.hasOwnProperty(name)) {- continue;- }- dests[name] = fetchDestination(names[name]);- }+ Promise.all(annotationPromises).then(function(datas) {+ var fnArray = pageQueue.fnArray;+ var argsArray = pageQueue.argsArray;+ fnArray.push('beginAnnotations');+ argsArray.push([]);+ for (var i = 0, n = datas.length; i < n; ++i) {+ var annotationData = datas[i];+ var annotationQueue = annotationData.queue;+ Util.concatenateToArray(fnArray, annotationQueue.fnArray);+ Util.concatenateToArray(argsArray, annotationQueue.argsArray);+ Util.extendObj(dependencies, annotationData.dependencies);}- return shadow(this, 'destinations', dests);- },- get javaScript() {- var xref = this.xref;- var obj = this.catDict.get('Names');+ fnArray.push('endAnnotations');+ argsArray.push([]);- var javaScript = [];- if (obj && obj.has('JavaScript')) {- var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);- var names = nameTree.getAll();- for (var name in names) {- if (!names.hasOwnProperty(name)) {- continue;- }- // We don't really use the JavaScript right now. This code is- // defensive so we don't cause errors on document load.- var jsDict = names[name];- if (!isDict(jsDict)) {- continue;- }- var type = jsDict.get('S');- if (!isName(type) || type.name !== 'JavaScript') {- continue;- }- var js = jsDict.get('JS');- if (!isString(js) && !isStream(js)) {- continue;- }- if (isStream(js)) {- js = bytesToString(js.getBytes());- }- javaScript.push(stringToPDFString(js));- }- }- return shadow(this, 'javaScript', javaScript);- },+ annotationsReadyPromise.resolve();+ }, reject);- cleanup: function Catalog_cleanup() {- this.fontCache.forEach(function (font) {- delete font.sent;- delete font.translated;- });- this.fontCache.clear();- },+ return annotationsReadyPromise;+ };- getPage: function Catalog_getPage(pageIndex) {- if (!(pageIndex in this.pagePromises)) {- this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(- function (a) {- var dict = a[0];- var ref = a[1];- return new Page(this.pdfManager, this.xref, pageIndex, dict, ref,- this.fontCache);- }.bind(this)- );- }- return this.pagePromises[pageIndex];- },+ return Annotation;+})();+PDFJS.Annotation = Annotation;- getPageDict: function Catalog_getPageDict(pageIndex) {- var promise = new LegacyPromise();- var nodesToVisit = [this.catDict.getRaw('Pages')];- var currentPageIndex = 0;- var xref = this.xref;- function next() {- while (nodesToVisit.length) {- var currentNode = nodesToVisit.pop();-- if (isRef(currentNode)) {- xref.fetchAsync(currentNode).then(function (obj) {- if ((isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids')))) {- if (pageIndex === currentPageIndex) {- promise.resolve([obj, currentNode]);- } else {- currentPageIndex++;- next();- }- return;- }- nodesToVisit.push(obj);- next();- }.bind(this), promise.reject.bind(promise));- return;- }+var WidgetAnnotation = (function WidgetAnnotationClosure() {- // must be a child page dictionary- assert(- isDict(currentNode),- 'page dictionary kid reference points to wrong type of object'- );- var count = currentNode.get('Count');- // Skip nodes where the page can't be.- if (currentPageIndex + count <= pageIndex) {- currentPageIndex += count;- continue;- }+ function WidgetAnnotation(params) {+ Annotation.call(this, params);- var kids = currentNode.get('Kids');- assert(isArray(kids), 'page dictionary kids object is not an array');- if (count === kids.length) {- // Nodes that don't have the page have been skipped and this is the- // bottom of the tree which means the page requested must be a- // descendant of this pages node. Ideally we would just resolve the- // promise with the page ref here, but there is the case where more- // pages nodes could link to single a page (see issue 3666 pdf). To- // handle this push it back on the queue so if it is a pages node it- // will be descended into.- nodesToVisit = [kids[pageIndex - currentPageIndex]];- currentPageIndex = pageIndex;- continue;- } else {- for (var last = kids.length - 1; last >= 0; last--) {- nodesToVisit.push(kids[last]);- }- }- }- promise.reject('Page index ' + pageIndex + ' not found.');- }- next();- return promise;- },+ if (params.data) {+ return;+ }- getPageIndex: function Catalog_getPageIndex(ref) {- // The page tree nodes have the count of all the leaves below them. To get- // how many pages are before we just have to walk up the tree and keep- // adding the count of siblings to the left of the node.- var xref = this.xref;- function pagesBeforeRef(kidRef) {- var total = 0;- var parentRef;- return xref.fetchAsync(kidRef).then(function (node) {- if (!node) {- return null;- }- parentRef = node.getRaw('Parent');- return node.getAsync('Parent');- }).then(function (parent) {- if (!parent) {- return null;- }- return parent.getAsync('Kids');- }).then(function (kids) {- if (!kids) {- return null;- }- var kidPromises = [];- var found = false;- for (var i = 0; i < kids.length; i++) {- var kid = kids[i];- assert(isRef(kid), 'kids must be a ref');- if (kid.num == kidRef.num) {- found = true;- break;- }- kidPromises.push(xref.fetchAsync(kid).then(function (kid) {- if (kid.has('Count')) {- var count = kid.get('Count');- total += count;- } else { // page leaf node- total++;- }- }));- }- if (!found) {- error('kid ref not found in parents kids');- }- return Promise.all(kidPromises).then(function () {- return [total, parentRef];- });- });+ var dict = params.dict;+ var data = this.data;++ data.fieldValue = stringToPDFString(+ Util.getInheritableProperty(dict, 'V') || '');+ data.alternativeText = stringToPDFString(dict.get('TU') || '');+ data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';+ var fieldType = Util.getInheritableProperty(dict, 'FT');+ data.fieldType = isName(fieldType) ? fieldType.name : '';+ data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;+ this.fieldResources = Util.getInheritableProperty(dict, 'DR') || new Dict();++ // Building the full field name by collecting the field and+ // its ancestors 'T' data and joining them using '.'.+ var fieldName = [];+ var namedItem = dict;+ var ref = params.ref;+ while (namedItem) {+ var parent = namedItem.get('Parent');+ var parentRef = namedItem.getRaw('Parent');+ var name = namedItem.get('T');+ if (name) {+ fieldName.unshift(stringToPDFString(name));+ } else {+ // The field name is absent, that means more than one field+ // with the same name may exist. Replacing the empty name+ // with the '`' plus index in the parent's 'Kids' array.+ // This is not in the PDF spec but necessary to id the+ // the input controls.+ var kids = parent.get('Kids');+ var j, jj;+ for (j = 0, jj = kids.length; j < jj; j++) {+ var kidRef = kids[j];+ if (kidRef.num == ref.num && kidRef.gen == ref.gen)+ break;+ }+ fieldName.unshift('`' + j);}+ namedItem = parent;+ ref = parentRef;+ }+ data.fullName = fieldName.join('.');+ }- var total = 0;- function next(ref) {- return pagesBeforeRef(ref).then(function (args) {- if (!args) {- return total;- }- var count = args[0];- var parentRef = args[1];- total += count;- return next(parentRef);- });+ var parent = Annotation.prototype;+ Util.inherit(WidgetAnnotation, Annotation, {+ isViewable: function WidgetAnnotation_isViewable() {+ if (this.data.fieldType === 'Sig') {+ TODO('unimplemented annotation type: Widget signature');+ return false;}- return next(ref);+ return parent.isViewable.call(this);}- };+ });- return Catalog;+ return WidgetAnnotation;})();-var XRef = (function XRefClosure() {- function XRef(stream, password) {- this.stream = stream;- this.entries = [];- this.xrefstms = {};- // prepare the XRef cache- this.cache = [];- this.password = password;+var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {+ function TextWidgetAnnotation(params) {+ WidgetAnnotation.call(this, params);++ if (params.data) {+ return;+ }++ this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');}- XRef.prototype = {- setStartXRef: function XRef_setStartXRef(startXRef) {- // Store the starting positions of xref tables as we process them- // so we can recover from missing data errors- this.startXRefQueue = [startXRef];- },+ // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()+ function setTextStyles(element, item, fontObj) {- parse: function XRef_parse(recoveryMode) {- var trailerDict;- if (!recoveryMode) {- trailerDict = this.readXRef();- } else {- warn('Indexing all PDF objects');- trailerDict = this.indexObjects();- }- trailerDict.assignXref(this);- this.trailer = trailerDict;- var encrypt = trailerDict.get('Encrypt');- if (encrypt) {- var ids = trailerDict.get('ID');- var fileId = (ids && ids.length) ? ids[0] : '';- this.encrypt = new CipherTransformFactory(encrypt, fileId,- this.password);- }+ var style = element.style;+ style.fontSize = item.fontSize + 'px';+ style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';- // get the root dictionary (catalog) object- if (!(this.root = trailerDict.get('Root'))) {- error('Invalid root reference');- }- },+ if (!fontObj) {+ return;+ }- processXRefTable: function XRef_processXRefTable(parser) {- if (!('tableState' in this)) {- // Stores state of the table as we process it so we can resume- // from middle of table in case of missing data error- this.tableState = {- entryNum: 0,- streamPos: parser.lexer.stream.pos,- parserBuf1: parser.buf1,- parserBuf2: parser.buf2- };- }+ style.fontWeight = fontObj.black ?+ (fontObj.bold ? 'bolder' : 'bold') :+ (fontObj.bold ? 'bold' : 'normal');+ style.fontStyle = fontObj.italic ? 'italic' : 'normal';- var obj = this.readXRefTable(parser);+ var fontName = fontObj.loadedName;+ var fontFamily = fontName ? '"' + fontName + '", ' : '';+ // Use a reasonable default font if the font doesn't specify a fallback+ var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';+ style.fontFamily = fontFamily + fallbackName;+ }- // Sanity check- if (!isCmd(obj, 'trailer')) {- error('Invalid XRef table: could not find trailer dictionary');- }- // Read trailer dictionary, e.g.- // trailer- // << /Size 22- // /Root 20R- // /Info 10R- // /ID [ <81b14aafa313db63dbd6f981e49f94f4> ]- // >>- // The parser goes through the entire stream << ... >> and provides- // a getter interface for the key-value table- var dict = parser.getObj();- if (!isDict(dict)) {- error('Invalid XRef table: could not parse trailer dictionary');- }- delete this.tableState;- return dict;+ var parent = WidgetAnnotation.prototype;+ Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {+ hasHtml: function TextWidgetAnnotation_hasHtml() {+ return !!this.data.fieldValue;},- readXRefTable: function XRef_readXRefTable(parser) {- // Example of cross-reference table:- // xref- // 0 1 <-- subsection header (first obj #, obj count)- // 0000000000 65535 f <-- actual object (offset, generation #, f/n)- // 23 2 <-- subsection header ... and so on ...- // 0000025518 00002 n- // 0000025635 00000 n- // trailer- // ...-- var stream = parser.lexer.stream;- var tableState = this.tableState;- stream.pos = tableState.streamPos;- parser.buf1 = tableState.parserBuf1;- parser.buf2 = tableState.parserBuf2;+ getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {+ assert(!isWorker, 'getHtmlElement() shall be called from main thread');- // Outer loop is over subsection headers- var obj;+ var item = this.data;- while (true) {- if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {- if (isCmd(obj = parser.getObj(), 'trailer')) {- break;- }- tableState.firstEntryNum = obj;- tableState.entryCount = parser.getObj();- }+ var element = this.getEmptyContainer('div');+ element.style.display = 'table';- var first = tableState.firstEntryNum;- var count = tableState.entryCount;- if (!isInt(first) || !isInt(count)) {- error('Invalid XRef table: wrong types in subsection header');- }- // Inner loop is over objects themselves- for (var i = tableState.entryNum; i < count; i++) {- tableState.streamPos = stream.pos;- tableState.entryNum = i;- tableState.parserBuf1 = parser.buf1;- tableState.parserBuf2 = parser.buf2;+ var content = document.createElement('div');+ content.textContent = item.fieldValue;+ var textAlignment = item.textAlignment;+ content.style.textAlign = ['left', 'center', 'right'][textAlignment];+ content.style.verticalAlign = 'middle';+ content.style.display = 'table-cell';- var entry = {};- entry.offset = parser.getObj();- entry.gen = parser.getObj();- var type = parser.getObj();+ var fontObj = item.fontRefName ?+ commonObjs.getData(item.fontRefName) : null;+ var cssRules = setTextStyles(content, item, fontObj);- if (isCmd(type, 'f')) {- entry.free = true;- } else if (isCmd(type, 'n')) {- entry.uncompressed = true;- }+ element.appendChild(content);- // Validate entry obj- if (!isInt(entry.offset) || !isInt(entry.gen) ||- !(entry.free || entry.uncompressed)) {- console.log(entry.offset, entry.gen, entry.free,- entry.uncompressed);- error('Invalid entry in XRef subsection: ' + first + ', ' + count);- }+ return element;+ },- if (!this.entries[i + first]) {- this.entries[i + first] = entry;- }- }+ getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {- tableState.entryNum = 0;- tableState.streamPos = stream.pos;- tableState.parserBuf1 = parser.buf1;- tableState.parserBuf2 = parser.buf2;- delete tableState.firstEntryNum;- delete tableState.entryCount;- }- // Per issue 3248: hp scanners generate bad XRef- if (first === 1 && this.entries[1] && this.entries[1].free) {- // shifting the entries- this.entries.shift();- }+ var promise = new Promise();+ var data = this.data;- // Sanity check: as per spec, first object must be free- if (this.entries[0] && !this.entries[0].free) {- error('Invalid XRef table: unexpected first object');+ // Even if there is an appearance stream, ignore it. This is the+ // behaviour used by Adobe Reader.++ var defaultAppearance = data.defaultAppearance;+ if (!defaultAppearance) {+ promise.resolve({+ queue: {+ fnArray: [],+ argsArray: []+ },+ dependency: {}+ });+ return promise;}- return obj;- },- processXRefStream: function XRef_processXRefStream(stream) {- if (!('streamState' in this)) {- // Stores state of the stream as we process it so we can resume- // from middle of stream in case of missing data error- var streamParameters = stream.dict;- var byteWidths = streamParameters.get('W');- var range = streamParameters.get('Index');- if (!range) {- range = [0, streamParameters.get('Size')];- }+ // Include any font resources found in the default appearance- this.streamState = {- entryRanges: range,- byteWidths: byteWidths,- entryNum: 0,- streamPos: stream.pos- };- }- this.readXRefStream(stream);- delete this.streamState;+ var stream = new Stream(stringToBytes(defaultAppearance));+ var listPromise = evaluator.getOperatorList(stream, this.fieldResources);+ listPromise.then(function(appearanceStreamData) {+ var appearanceFnArray = appearanceStreamData.queue.fnArray;+ var appearanceArgsArray = appearanceStreamData.queue.argsArray;+ var fnArray = [];+ var argsArray = [];++ // TODO(mack): Add support for stroke color+ data.rgb = [0, 0, 0];+ for (var i = 0, n = fnArray.length; i < n; ++i) {+ var fnName = appearanceFnArray[i];+ var args = appearanceArgsArray[i];+ if (fnName === 'dependency') {+ var dependency = args[i];+ if (dependency.indexOf('g_font_') === 0) {+ data.fontRefName = dependency;+ }+ fnArray.push(fnName);+ argsArray.push(args);+ } else if (fnName === 'setFont') {+ data.fontRefName = args[0];+ var size = args[1];+ if (size < 0) {+ data.fontDirection = -1;+ data.fontSize = -size;+ } else {+ data.fontDirection = 1;+ data.fontSize = size;+ }+ } else if (fnName === 'setFillRGBColor') {+ data.rgb = args;+ } else if (fnName === 'setFillGray') {+ var rgbValue = args[0] * 255;+ data.rgb = [rgbValue, rgbValue, rgbValue];+ }+ }+ promise.resolve({+ queue: {+ fnArray: fnArray,+ argsArray: argsArray+ },+ dependency: {}+ });- return stream.dict;- },+ });- readXRefStream: function XRef_readXRefStream(stream) {- var i, j;- var streamState = this.streamState;- stream.pos = streamState.streamPos;+ return promise;+ }+ });- var byteWidths = streamState.byteWidths;- var typeFieldWidth = byteWidths[0];- var offsetFieldWidth = byteWidths[1];- var generationFieldWidth = byteWidths[2];+ return TextWidgetAnnotation;+})();- var entryRanges = streamState.entryRanges;- while (entryRanges.length > 0) {- var first = entryRanges[0];- var n = entryRanges[1];+var TextAnnotation = (function TextAnnotationClosure() {+ function TextAnnotation(params) {+ Annotation.call(this, params);- if (!isInt(first) || !isInt(n)) {- error('Invalid XRef range fields: ' + first + ', ' + n);- }- if (!isInt(typeFieldWidth) || !isInt(offsetFieldWidth) ||- !isInt(generationFieldWidth)) {- error('Invalid XRef entry fields length: ' + first + ', ' + n);- }- for (i = streamState.entryNum; i < n; ++i) {- streamState.entryNum = i;- streamState.streamPos = stream.pos;+ if (params.data) {+ return;+ }- var type = 0, offset = 0, generation = 0;- for (j = 0; j < typeFieldWidth; ++j) {- type = (type << 8) | stream.getByte();- }- // if type field is absent, its default value is 1- if (typeFieldWidth === 0) {- type = 1;- }- for (j = 0; j < offsetFieldWidth; ++j) {- offset = (offset << 8) | stream.getByte();- }- for (j = 0; j < generationFieldWidth; ++j) {- generation = (generation << 8) | stream.getByte();- }- var entry = {};- entry.offset = offset;- entry.gen = generation;- switch (type) {- case 0:- entry.free = true;- break;- case 1:- entry.uncompressed = true;- break;- case 2:- break;- default:- error('Invalid XRef entry type: ' + type);- }- if (!this.entries[first + i]) {- this.entries[first + i] = entry;- }- }+ var dict = params.dict;+ var data = this.data;- streamState.entryNum = 0;- streamState.streamPos = stream.pos;- entryRanges.splice(0, 2);- }- },+ var content = dict.get('Contents');+ var title = dict.get('T');+ data.content = stringToPDFString(content || '');+ data.title = stringToPDFString(title || '');+ data.name = !dict.has('Name') ? 'Note' : dict.get('Name').name;+ }- indexObjects: function XRef_indexObjects() {- // Simple scan through the PDF content to find objects,- // trailers and XRef streams.- function readToken(data, offset) {- var token = '', ch = data[offset];- while (ch !== 13 && ch !== 10) {- if (++offset >= data.length) {- break;- }- token += String.fromCharCode(ch);- ch = data[offset];- }- return token;- }- function skipUntil(data, offset, what) {- var length = what.length, dataLength = data.length;- var skipped = 0;- // finding byte sequence- while (offset < dataLength) {- var i = 0;- while (i < length && data[offset + i] == what[i]) {- ++i;- }- if (i >= length) {- break; // sequence found- }- offset++;- skipped++;- }- return skipped;- }- var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);- var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114,- 101, 102]);- var endobjBytes = new Uint8Array([101, 110, 100, 111, 98, 106]);- var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);+ var ANNOT_MIN_SIZE = 10;+ var IMAGE_DIR = './images/';- var stream = this.stream;- stream.pos = 0;- var buffer = stream.getBytes();- var position = stream.start, length = buffer.length;- var trailers = [], xrefStms = [];- var state = 0;- var currentToken;- while (position < length) {- var ch = buffer[position];- if (ch === 32 || ch === 9 || ch === 13 || ch === 10) {- ++position;- continue;- }- if (ch === 37) { // %-comment- do {- ++position;- if (position >= length) {- break;- }- ch = buffer[position];- } while (ch !== 13 && ch !== 10);- continue;- }- var token = readToken(buffer, position);- var m;- if (token === 'xref') {- position += skipUntil(buffer, position, trailerBytes);- trailers.push(position);- position += skipUntil(buffer, position, startxrefBytes);- } else if ((m = /^(\d+)\s+(\d+)\s+obj\b/.exec(token))) {- this.entries[m[1]] = {- offset: position,- gen: m[2] | 0,- uncompressed: true- };+ Util.inherit(TextAnnotation, Annotation, {- var contentLength = skipUntil(buffer, position, endobjBytes) + 7;- var content = buffer.subarray(position, position + contentLength);+ getOperatorList: function TextAnnotation_getOperatorList(evaluator) {+ var promise = new Promise();+ promise.resolve({+ queue: {+ fnArray: [],+ argsArray: []+ },+ dependency: {}+ });+ return promise;+ },- // checking XRef stream suspect- // (it shall have '/XRef' and next char is not a letter)- var xrefTagOffset = skipUntil(content, 0, xrefBytes);- if (xrefTagOffset < contentLength &&- content[xrefTagOffset + 5] < 64) {- xrefStms.push(position);- this.xrefstms[position] = 1; // don't read it recursively- }+ hasHtml: function TextAnnotation_hasHtml() {+ return true;+ },- position += contentLength;- } else {- position += token.length + 1;- }+ getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {+ assert(!isWorker, 'getHtmlElement() shall be called from main thread');++ var item = this.data;+ var rect = item.rect;++ // sanity check because of OOo-generated PDFs+ if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {+ rect[3] = rect[1] + ANNOT_MIN_SIZE;}- // reading XRef streams- var i, ii;- for (i = 0, ii = xrefStms.length; i < ii; ++i) {- this.startXRefQueue.push(xrefStms[i]);- this.readXRef(/* recoveryMode */ true);+ if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {+ rect[2] = rect[0] + (rect[3] - rect[1]); // make it square}- // finding main trailer- var dict;- for (i = 0, ii = trailers.length; i < ii; ++i) {- stream.pos = trailers[i];- var parser = new Parser(new Lexer(stream), true, null);- var obj = parser.getObj();- if (!isCmd(obj, 'trailer')) {- continue;- }- // read the trailer dictionary- if (!isDict(dict = parser.getObj())) {- continue;- }- // taking the first one with 'ID'- if (dict.has('ID')) {- return dict;++ var container = this.getEmptyContainer('section', rect);+ container.className = 'annotText';++ var image = document.createElement('img');+ image.style.width = container.style.width;+ image.style.height = container.style.height;+ var iconName = item.name;+ image.src = IMAGE_DIR + 'annotation-' ++ iconName.toLowerCase() + '.svg';+ image.alt = '[{{type}} Annotation]';+ image.dataset.l10nId = 'text_annotation_type';+ image.dataset.l10nArgs = JSON.stringify({type: iconName});+ var content = document.createElement('div');+ content.setAttribute('hidden', true);+ var title = document.createElement('h1');+ var text = document.createElement('p');+ content.style.left = Math.floor(rect[2] - rect[0]) + 'px';+ content.style.top = '0px';+ title.textContent = item.title;++ if (!item.content && !item.title) {+ content.setAttribute('hidden', true);+ } else {+ var e = document.createElement('span');+ var lines = item.content.split(/(?:\r\n?|\n)/);+ for (var i = 0, ii = lines.length; i < ii; ++i) {+ var line = lines[i];+ e.appendChild(document.createTextNode(line));+ if (i < (ii - 1))+ e.appendChild(document.createElement('br'));}+ text.appendChild(e);+ image.addEventListener('mouseover', function annotationImageOver() {+ container.style.zIndex += 1;+ content.removeAttribute('hidden');+ }, false);++ image.addEventListener('mouseout', function annotationImageOut() {+ container.style.zIndex -= 1;+ content.setAttribute('hidden', true);+ }, false);}- // no tailer with 'ID', taking last one (if exists)- if (dict) {- return dict;- }- // nothing helps- // calling error() would reject worker with an UnknownErrorException.- throw new InvalidPDFException('Invalid PDF structure');- },- readXRef: function XRef_readXRef(recoveryMode) {- var stream = this.stream;+ content.appendChild(title);+ content.appendChild(text);+ container.appendChild(image);+ container.appendChild(content);- try {- while (this.startXRefQueue.length) {- var startXRef = this.startXRefQueue[0];+ return container;+ }+ });- stream.pos = startXRef + stream.start;+ return TextAnnotation;+})();- var parser = new Parser(new Lexer(stream), true, null);- var obj = parser.getObj();- var dict;+var LinkAnnotation = (function LinkAnnotationClosure() {+ function isValidUrl(url) {+ if (!url)+ return false;+ var colon = url.indexOf(':');+ if (colon < 0)+ return false;+ var protocol = url.substr(0, colon);+ switch (protocol) {+ case 'http':+ case 'https':+ case 'ftp':+ case 'mailto':+ return true;+ default:+ return false;+ }+ }- // Get dictionary- if (isCmd(obj, 'xref')) {- // Parse end-of-file XRef- dict = this.processXRefTable(parser);- if (!this.topDict) {- this.topDict = dict;- }+ function LinkAnnotation(params) {+ Annotation.call(this, params);- // Recursively get other XRefs 'XRefStm', if any- obj = dict.get('XRefStm');- if (isInt(obj)) {- var pos = obj;- // ignore previously loaded xref streams- // (possible infinite recursion)- if (!(pos in this.xrefstms)) {- this.xrefstms[pos] = 1;- this.startXRefQueue.push(pos);- }- }- } else if (isInt(obj)) {- // Parse in-stream XRef- if (!isInt(parser.getObj()) ||- !isCmd(parser.getObj(), 'obj') ||- !isStream(obj = parser.getObj())) {- error('Invalid XRef stream');- }- dict = this.processXRefStream(obj);- if (!this.topDict) {- this.topDict = dict;- }- if (!dict) {- error('Failed to read XRef stream');- }- } else {- error('Invalid XRef stream header');- }+ if (params.data) {+ return;+ }- // Recursively get previous dictionary, if any- obj = dict.get('Prev');- if (isInt(obj)) {- this.startXRefQueue.push(obj);- } else if (isRef(obj)) {- // The spec says Prev must not be a reference, i.e. "/Prev NNN"- // This is a fallback for non-compliant PDFs, i.e. "/Prev NNN 0 R"- this.startXRefQueue.push(obj.num);- }+ var dict = params.dict;+ var data = this.data;- this.startXRefQueue.shift();+ var action = dict.get('A');+ if (action) {+ var linkType = action.get('S').name;+ if (linkType === 'URI') {+ var url = action.get('URI');+ // TODO: pdf spec mentions urls can be relative to a Base+ // entry in the dictionary.+ if (!isValidUrl(url)) {+ url = '';+ }+ data.url = url;+ } else if (linkType === 'GoTo') {+ data.dest = action.get('D');+ } else if (linkType === 'GoToR') {+ var urlDict = action.get('F');+ if (isDict(urlDict)) {+ // We assume that the 'url' is a Filspec dictionary+ // and fetch the url without checking any further+ url = urlDict.get('F') || '';}- return this.topDict;- } catch (e) {- if (e instanceof MissingDataException) {- throw e;+ // TODO: pdf reference says that GoToR+ // can also have 'NewWindow' attribute+ if (!isValidUrl(url)) {+ url = '';}- info('(while reading XRef): ' + e);+ data.url = url;+ data.dest = action.get('D');+ } else {+ TODO('unrecognized link type: ' + linkType);}+ } else if (dict.has('Dest')) {+ // simple destination link+ var dest = dict.get('Dest');+ data.dest = isName(dest) ? dest.name : dest;+ }+ }- if (recoveryMode) {- return;- }- throw new XRefParseException();+ Util.inherit(LinkAnnotation, Annotation, {+ hasOperatorList: function LinkAnnotation_hasOperatorList() {+ return false;},- getEntry: function XRef_getEntry(i) {- var xrefEntry = this.entries[i];- if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {- return xrefEntry;- }- return null;+ hasHtml: function LinkAnnotation_hasHtml() {+ return true;},- fetchIfRef: function XRef_fetchIfRef(obj) {- if (!isRef(obj)) {- return obj;- }- return this.fetch(obj);- },+ getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {+ var rect = this.data.rect;+ var element = document.createElement('a');+ var borderWidth = this.data.borderWidth;- fetch: function XRef_fetch(ref, suppressEncryption) {- assert(isRef(ref), 'ref object is not a reference');- var num = ref.num;- if (num in this.cache) {- var cacheEntry = this.cache[num];- return cacheEntry;+ element.style.borderWidth = borderWidth + 'px';+ var color = this.data.color;+ var rgb = [];+ for (var i = 0; i < 3; ++i) {+ rgb[i] = Math.round(color[i] * 255);}+ element.style.borderColor = Util.makeCssRgb(rgb);+ element.style.borderStyle = 'solid';- var xrefEntry = this.getEntry(num);+ var width = rect[2] - rect[0] - 2 * borderWidth;+ var height = rect[3] - rect[1] - 2 * borderWidth;+ element.style.width = width + 'px';+ element.style.height = height + 'px';- // the referenced entry can be free- if (xrefEntry === null) {- return (this.cache[num] = null);- }+ element.href = this.data.url || '';+ return element;+ }+ });- if (xrefEntry.uncompressed) {- xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);- } else {- xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);- }+ return LinkAnnotation;+})();- if (isDict(xrefEntry)) {- xrefEntry.objId = 'R' + ref.num + '.' + ref.gen;- }- return xrefEntry;- },- fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry,- suppressEncryption) {- var gen = ref.gen;- var num = ref.num;- if (xrefEntry.gen !== gen) {- error('inconsistent generation in XRef');- }- var stream = this.stream.makeSubStream(xrefEntry.offset +- this.stream.start);- var parser = new Parser(new Lexer(stream), true, this);- var obj1 = parser.getObj();- var obj2 = parser.getObj();- var obj3 = parser.getObj();- if (!isInt(obj1) || parseInt(obj1, 10) !== num ||- !isInt(obj2) || parseInt(obj2, 10) !== gen ||- !isCmd(obj3)) {- error('bad XRef entry');- }- if (!isCmd(obj3, 'obj')) {- // some bad PDFs use "obj1234" and really mean 1234- if (obj3.cmd.indexOf('obj') === 0) {- num = parseInt(obj3.cmd.substring(3), 10);- if (!isNaN(num)) {- return num;- }- }- error('bad XRef entry');- }- if (this.encrypt && !suppressEncryption) {- try {- xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num,- gen));- } catch (ex) {- // Almost all streams must be encrypted, but sometimes- // they are not, probably due to some broken generators.- // Retrying without encryption...- return this.fetch(ref, true);+var PDFFunction = (function PDFFunctionClosure() {+ var CONSTRUCT_SAMPLED = 0;+ var CONSTRUCT_INTERPOLATED = 2;+ var CONSTRUCT_STICHED = 3;+ var CONSTRUCT_POSTSCRIPT = 4;++ return {+ getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,+ str) {+ var length = 1;+ for (var i = 0, ii = size.length; i < ii; i++)+ length *= size[i];+ length *= outputSize;++ var array = [];+ var codeSize = 0;+ var codeBuf = 0;+ // 32 is a valid bps so shifting won't work+ var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);++ var strBytes = str.getBytes((length * bps + 7) / 8);+ var strIdx = 0;+ for (var i = 0; i < length; i++) {+ while (codeSize < bps) {+ codeBuf <<= 8;+ codeBuf |= strBytes[strIdx++];+ codeSize += 8;}- } else {- xrefEntry = parser.getObj();- }- if (!isStream(xrefEntry)) {- this.cache[num] = xrefEntry;+ codeSize -= bps;+ array.push((codeBuf >> codeSize) * sampleMul);+ codeBuf &= (1 << codeSize) - 1;}- return xrefEntry;+ return array;},- fetchCompressed: function XRef_fetchCompressed(xrefEntry,- suppressEncryption) {- var tableOffset = xrefEntry.offset;- var stream = this.fetch(new Ref(tableOffset, 0));- if (!isStream(stream)) {- error('bad ObjStm stream');- }- var first = stream.dict.get('First');- var n = stream.dict.get('N');- if (!isInt(first) || !isInt(n)) {- error('invalid first and n parameters for ObjStm stream');- }- var parser = new Parser(new Lexer(stream), false, this);- parser.allowStreams = true;- var i, entries = [], num, nums = [];- // read the object numbers to populate cache- for (i = 0; i < n; ++i) {- num = parser.getObj();- if (!isInt(num)) {- error('invalid object number in the ObjStm stream: ' + num);- }- nums.push(num);- var offset = parser.getObj();- if (!isInt(offset)) {- error('invalid object offset in the ObjStm stream: ' + offset);- }- }- // read stream objects for cache- for (i = 0; i < n; ++i) {- entries.push(parser.getObj());- num = nums[i];- var entry = this.entries[num];- if (entry && entry.offset === tableOffset && entry.gen === i) {- this.cache[num] = entries[i];+ getIR: function PDFFunction_getIR(xref, fn) {+ var dict = fn.dict;+ if (!dict)+ dict = fn;++ var types = [this.constructSampled,+ null,+ this.constructInterpolated,+ this.constructStiched,+ this.constructPostScript];++ var typeNum = dict.get('FunctionType');+ var typeFn = types[typeNum];+ if (!typeFn)+ error('Unknown type of function');++ return typeFn.call(this, fn, dict, xref);+ },++ fromIR: function PDFFunction_fromIR(IR) {+ var type = IR[0];+ switch (type) {+ case CONSTRUCT_SAMPLED:+ return this.constructSampledFromIR(IR);+ case CONSTRUCT_INTERPOLATED:+ return this.constructInterpolatedFromIR(IR);+ case CONSTRUCT_STICHED:+ return this.constructStichedFromIR(IR);+ //case CONSTRUCT_POSTSCRIPT:+ default:+ return this.constructPostScriptFromIR(IR);+ }+ },++ parse: function PDFFunction_parse(xref, fn) {+ var IR = this.getIR(xref, fn);+ return this.fromIR(IR);+ },++ constructSampled: function PDFFunction_constructSampled(str, dict) {+ function toMultiArray(arr) {+ var inputLength = arr.length;+ var outputLength = arr.length / 2;+ var out = [];+ var index = 0;+ for (var i = 0; i < inputLength; i += 2) {+ out[index] = [arr[i], arr[i + 1]];+ ++index;}+ return out;}- xrefEntry = entries[xrefEntry.gen];- if (xrefEntry === undefined) {- error('bad XRef entry for compressed object');+ var domain = dict.get('Domain');+ var range = dict.get('Range');++ if (!domain || !range)+ error('No domain or range');++ var inputSize = domain.length / 2;+ var outputSize = range.length / 2;++ domain = toMultiArray(domain);+ range = toMultiArray(range);++ var size = dict.get('Size');+ var bps = dict.get('BitsPerSample');+ var order = dict.get('Order') || 1;+ if (order !== 1) {+ // No description how cubic spline interpolation works in PDF32000:2008+ // As in poppler, ignoring order, linear interpolation may work as good+ TODO('No support for cubic spline interpolation: ' + order);}- return xrefEntry;- },- fetchIfRefAsync: function XRef_fetchIfRefAsync(obj) {- if (!isRef(obj)) {- var promise = new LegacyPromise();- promise.resolve(obj);- return promise;+ var encode = dict.get('Encode');+ if (!encode) {+ encode = [];+ for (var i = 0; i < inputSize; ++i) {+ encode.push(0);+ encode.push(size[i] - 1);+ }}- return this.fetchAsync(obj);+ encode = toMultiArray(encode);++ var decode = dict.get('Decode');+ if (!decode)+ decode = range;+ else+ decode = toMultiArray(decode);++ var samples = this.getSampleArray(size, outputSize, bps, str);++ return [+ CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,+ outputSize, Math.pow(2, bps) - 1, range+ ];},- fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {- var promise = new LegacyPromise();- var tryFetch = function (promise) {- try {- promise.resolve(this.fetch(ref, suppressEncryption));- } catch (e) {- if (e instanceof MissingDataException) {- this.stream.manager.requestRange(e.begin, e.end, tryFetch);- return;+ constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {+ // See chapter 3, page 109 of the PDF reference+ function interpolate(x, xmin, xmax, ymin, ymax) {+ return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));+ }++ return function constructSampledFromIRResult(args) {+ // See chapter 3, page 110 of the PDF reference.+ var m = IR[1];+ var domain = IR[2];+ var encode = IR[3];+ var decode = IR[4];+ var samples = IR[5];+ var size = IR[6];+ var n = IR[7];+ var mask = IR[8];+ var range = IR[9];++ if (m != args.length)+ error('Incorrect number of arguments: ' + m + ' != ' ++ args.length);++ var x = args;++ // Building the cube vertices: its part and sample index+ // http://rjwagner49.com/Mathematics/Interpolation.pdf+ var cubeVertices = 1 << m;+ var cubeN = new Float64Array(cubeVertices);+ var cubeVertex = new Uint32Array(cubeVertices);+ for (var j = 0; j < cubeVertices; j++)+ cubeN[j] = 1;++ var k = n, pos = 1;+ // Map x_i to y_j for 0 <= i < m using the sampled function.+ for (var i = 0; i < m; ++i) {+ // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)+ var domain_2i = domain[i][0];+ var domain_2i_1 = domain[i][1];+ var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);++ // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,+ // Encode_2i, Encode_2i+1)+ var e = interpolate(xi, domain_2i, domain_2i_1,+ encode[i][0], encode[i][1]);++ // e_i' = min(max(e_i, 0), Size_i - 1)+ var size_i = size[i];+ e = Math.min(Math.max(e, 0), size_i - 1);++ // Adjusting the cube: N and vertex sample index+ var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;+ var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);+ var n1 = e - e0; // (e - e0) / (e1 - e0);+ var offset0 = e0 * k;+ var offset1 = offset0 + k; // e1 * k+ for (var j = 0; j < cubeVertices; j++) {+ if (j & pos) {+ cubeN[j] *= n1;+ cubeVertex[j] += offset1;+ } else {+ cubeN[j] *= n0;+ cubeVertex[j] += offset0;+ }}- promise.reject(e);++ k *= size_i;+ pos <<= 1;}- }.bind(this, promise);- tryFetch();- return promise;++ var y = new Float64Array(n);+ for (var j = 0; j < n; ++j) {+ // Sum all cube vertices' samples portions+ var rj = 0;+ for (var i = 0; i < cubeVertices; i++)+ rj += samples[cubeVertex[i] + j] * cubeN[i];++ // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,+ // Decode_2j, Decode_2j+1)+ rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);++ // y_j = min(max(r_j, range_2j), range_2j+1)+ y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);+ }++ return y;+ };},- getCatalogObj: function XRef_getCatalogObj() {- return this.root;+ constructInterpolated: function PDFFunction_constructInterpolated(str,+ dict) {+ var c0 = dict.get('C0') || [0];+ var c1 = dict.get('C1') || [1];+ var n = dict.get('N');++ if (!isArray(c0) || !isArray(c1))+ error('Illegal dictionary for interpolated function');++ var length = c0.length;+ var diff = [];+ for (var i = 0; i < length; ++i)+ diff.push(c1[i] - c0[i]);++ return [CONSTRUCT_INTERPOLATED, c0, diff, n];+ },++ constructInterpolatedFromIR:+ function PDFFunction_constructInterpolatedFromIR(IR) {+ var c0 = IR[1];+ var diff = IR[2];+ var n = IR[3];++ var length = diff.length;++ return function constructInterpolatedFromIRResult(args) {+ var x = n == 1 ? args[0] : Math.pow(args[0], n);++ var out = [];+ for (var j = 0; j < length; ++j)+ out.push(c0[j] + (x * diff[j]));++ return out;++ };+ },++ constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {+ var domain = dict.get('Domain');++ if (!domain)+ error('No domain');++ var inputSize = domain.length / 2;+ if (inputSize != 1)+ error('Bad domain for stiched function');++ var fnRefs = dict.get('Functions');+ var fns = [];+ for (var i = 0, ii = fnRefs.length; i < ii; ++i)+ fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));++ var bounds = dict.get('Bounds');+ var encode = dict.get('Encode');++ return [CONSTRUCT_STICHED, domain, bounds, encode, fns];+ },++ constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {+ var domain = IR[1];+ var bounds = IR[2];+ var encode = IR[3];+ var fnsIR = IR[4];+ var fns = [];++ for (var i = 0, ii = fnsIR.length; i < ii; i++) {+ fns.push(PDFFunction.fromIR(fnsIR[i]));+ }++ return function constructStichedFromIRResult(args) {+ var clip = function constructStichedFromIRClip(v, min, max) {+ if (v > max)+ v = max;+ else if (v < min)+ v = min;+ return v;+ };++ // clip to domain+ var v = clip(args[0], domain[0], domain[1]);+ // calulate which bound the value is in+ for (var i = 0, ii = bounds.length; i < ii; ++i) {+ if (v < bounds[i])+ break;+ }++ // encode value into domain of function+ var dmin = domain[0];+ if (i > 0)+ dmin = bounds[i - 1];+ var dmax = domain[1];+ if (i < bounds.length)+ dmax = bounds[i];++ var rmin = encode[2 * i];+ var rmax = encode[2 * i + 1];++ var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);++ // call the appropropriate function+ return fns[i]([v2]);+ };+ },++ constructPostScript: function PDFFunction_constructPostScript(fn, dict,+ xref) {+ var domain = dict.get('Domain');+ var range = dict.get('Range');++ if (!domain)+ error('No domain.');++ if (!range)+ error('No range.');++ var lexer = new PostScriptLexer(fn);+ var parser = new PostScriptParser(lexer);+ var code = parser.parse();++ return [CONSTRUCT_POSTSCRIPT, domain, range, code];+ },++ constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(+ IR) {+ var domain = IR[1];+ var range = IR[2];+ var code = IR[3];+ var numOutputs = range.length / 2;+ var evaluator = new PostScriptEvaluator(code);+ // Cache the values for a big speed up, the cache size is limited though+ // since the number of possible values can be huge from a PS function.+ var cache = new FunctionCache();+ return function constructPostScriptFromIRResult(args) {+ var initialStack = [];+ for (var i = 0, ii = (domain.length / 2); i < ii; ++i) {+ initialStack.push(args[i]);+ }++ var key = initialStack.join('_');+ if (cache.has(key))+ return cache.get(key);++ var stack = evaluator.execute(initialStack);+ var transformed = [];+ for (i = numOutputs - 1; i >= 0; --i) {+ var out = stack.pop();+ var rangeIndex = 2 * i;+ if (out < range[rangeIndex])+ out = range[rangeIndex];+ else if (out > range[rangeIndex + 1])+ out = range[rangeIndex + 1];+ transformed[i] = out;+ }+ cache.set(key, transformed);+ return transformed;+ };}};+})();- return XRef;+var FunctionCache = (function FunctionCacheClosure() {+ // Of 10 PDF's with type4 functions the maxium number of distinct values seen+ // was 256. This still may need some tweaking in the future though.+ var MAX_CACHE_SIZE = 1024;+ function FunctionCache() {+ this.cache = {};+ this.total = 0;+ }+ FunctionCache.prototype = {+ has: function FunctionCache_has(key) {+ return key in this.cache;+ },+ get: function FunctionCache_get(key) {+ return this.cache[key];+ },+ set: function FunctionCache_set(key, value) {+ if (this.total < MAX_CACHE_SIZE) {+ this.cache[key] = value;+ this.total++;+ }+ }+ };+ return FunctionCache;})();-/**- * A NameTree is like a Dict but has some advantageous properties, see the- * spec (7.9.6) for more details.- * TODO: implement all the Dict functions and make this more efficent.- */-var NameTree = (function NameTreeClosure() {- function NameTree(root, xref) {- this.root = root;- this.xref = xref;+var PostScriptStack = (function PostScriptStackClosure() {+ var MAX_STACK_SIZE = 100;+ function PostScriptStack(initialStack) {+ this.stack = initialStack || [];}- NameTree.prototype = {- getAll: function NameTree_getAll() {- var dict = {};- if (!this.root) {- return dict;+ PostScriptStack.prototype = {+ push: function PostScriptStack_push(value) {+ if (this.stack.length >= MAX_STACK_SIZE)+ error('PostScript function stack overflow.');+ this.stack.push(value);+ },+ pop: function PostScriptStack_pop() {+ if (this.stack.length <= 0)+ error('PostScript function stack underflow.');+ return this.stack.pop();+ },+ copy: function PostScriptStack_copy(n) {+ if (this.stack.length + n >= MAX_STACK_SIZE)+ error('PostScript function stack overflow.');+ var stack = this.stack;+ for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++)+ stack.push(stack[i]);+ },+ index: function PostScriptStack_index(n) {+ this.push(this.stack[this.stack.length - n - 1]);+ },+ // rotate the last n stack elements p times+ roll: function PostScriptStack_roll(n, p) {+ var stack = this.stack;+ var l = stack.length - n;+ var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;+ for (i = l, j = r; i < j; i++, j--) {+ t = stack[i]; stack[i] = stack[j]; stack[j] = t;}- var xref = this.xref;- // reading name tree- var processed = new RefSet();- processed.put(this.root);- var queue = [this.root];- while (queue.length > 0) {- var i, n;- var obj = xref.fetchIfRef(queue.shift());- if (!isDict(obj)) {- continue;- }- if (obj.has('Kids')) {- var kids = obj.get('Kids');- for (i = 0, n = kids.length; i < n; i++) {- var kid = kids[i];- if (processed.has(kid)) {- error('invalid destinations');- }- queue.push(kid);- processed.put(kid);- }+ for (i = l, j = c - 1; i < j; i++, j--) {+ t = stack[i]; stack[i] = stack[j]; stack[j] = t;+ }+ for (i = c, j = r; i < j; i++, j--) {+ t = stack[i]; stack[i] = stack[j]; stack[j] = t;+ }+ }+ };+ return PostScriptStack;+})();+var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {+ function PostScriptEvaluator(operators, operands) {+ this.operators = operators;+ this.operands = operands;+ }+ PostScriptEvaluator.prototype = {+ execute: function PostScriptEvaluator_execute(initialStack) {+ var stack = new PostScriptStack(initialStack);+ var counter = 0;+ var operators = this.operators;+ var length = operators.length;+ var operator, a, b;+ while (counter < length) {+ operator = operators[counter++];+ if (typeof operator == 'number') {+ // Operator is really an operand and should be pushed to the stack.+ stack.push(operator);continue;}- var names = obj.get('Names');- if (names) {- for (i = 0, n = names.length; i < n; i += 2) {- dict[names[i]] = xref.fetchIfRef(names[i + 1]);- }+ switch (operator) {+ // non standard ps operators+ case 'jz': // jump if false+ b = stack.pop();+ a = stack.pop();+ if (!a)+ counter = b;+ break;+ case 'j': // jump+ a = stack.pop();+ counter = a;+ break;++ // all ps operators in alphabetical order (excluding if/ifelse)+ case 'abs':+ a = stack.pop();+ stack.push(Math.abs(a));+ break;+ case 'add':+ b = stack.pop();+ a = stack.pop();+ stack.push(a + b);+ break;+ case 'and':+ b = stack.pop();+ a = stack.pop();+ if (isBool(a) && isBool(b))+ stack.push(a && b);+ else+ stack.push(a & b);+ break;+ case 'atan':+ a = stack.pop();+ stack.push(Math.atan(a));+ break;+ case 'bitshift':+ b = stack.pop();+ a = stack.pop();+ if (a > 0)+ stack.push(a << b);+ else+ stack.push(a >> b);+ break;+ case 'ceiling':+ a = stack.pop();+ stack.push(Math.ceil(a));+ break;+ case 'copy':+ a = stack.pop();+ stack.copy(a);+ break;+ case 'cos':+ a = stack.pop();+ stack.push(Math.cos(a));+ break;+ case 'cvi':+ a = stack.pop() | 0;+ stack.push(a);+ break;+ case 'cvr':+ // noop+ break;+ case 'div':+ b = stack.pop();+ a = stack.pop();+ stack.push(a / b);+ break;+ case 'dup':+ stack.copy(1);+ break;+ case 'eq':+ b = stack.pop();+ a = stack.pop();+ stack.push(a == b);+ break;+ case 'exch':+ stack.roll(2, 1);+ break;+ case 'exp':+ b = stack.pop();+ a = stack.pop();+ stack.push(Math.pow(a, b));+ break;+ case 'false':+ stack.push(false);+ break;+ case 'floor':+ a = stack.pop();+ stack.push(Math.floor(a));+ break;+ case 'ge':+ b = stack.pop();+ a = stack.pop();+ stack.push(a >= b);+ break;+ case 'gt':+ b = stack.pop();+ a = stack.pop();+ stack.push(a > b);+ break;+ case 'idiv':+ b = stack.pop();+ a = stack.pop();+ stack.push((a / b) | 0);+ break;+ case 'index':+ a = stack.pop();+ stack.index(a);+ break;+ case 'le':+ b = stack.pop();+ a = stack.pop();+ stack.push(a <= b);+ break;+ case 'ln':+ a = stack.pop();+ stack.push(Math.log(a));+ break;+ case 'log':+ a = stack.pop();+ stack.push(Math.log(a) / Math.LN10);+ break;+ case 'lt':+ b = stack.pop();+ a = stack.pop();+ stack.push(a < b);+ break;+ case 'mod':+ b = stack.pop();+ a = stack.pop();+ stack.push(a % b);+ break;+ case 'mul':+ b = stack.pop();+ a = stack.pop();+ stack.push(a * b);+ break;+ case 'ne':+ b = stack.pop();+ a = stack.pop();+ stack.push(a != b);+ break;+ case 'neg':+ a = stack.pop();+ stack.push(-b);+ break;+ case 'not':+ a = stack.pop();+ if (isBool(a) && isBool(b))+ stack.push(a && b);+ else+ stack.push(a & b);+ break;+ case 'or':+ b = stack.pop();+ a = stack.pop();+ if (isBool(a) && isBool(b))+ stack.push(a || b);+ else+ stack.push(a | b);+ break;+ case 'pop':+ stack.pop();+ break;+ case 'roll':+ b = stack.pop();+ a = stack.pop();+ stack.roll(a, b);+ break;+ case 'round':+ a = stack.pop();+ stack.push(Math.round(a));+ break;+ case 'sin':+ a = stack.pop();+ stack.push(Math.sin(a));+ break;+ case 'sqrt':+ a = stack.pop();+ stack.push(Math.sqrt(a));+ break;+ case 'sub':+ b = stack.pop();+ a = stack.pop();+ stack.push(a - b);+ break;+ case 'true':+ stack.push(true);+ break;+ case 'truncate':+ a = stack.pop();+ a = a < 0 ? Math.ceil(a) : Math.floor(a);+ stack.push(a);+ break;+ case 'xor':+ b = stack.pop();+ a = stack.pop();+ if (isBool(a) && isBool(b))+ stack.push(a != b);+ else+ stack.push(a ^ b);+ break;+ default:+ error('Unknown operator ' + operator);+ break;}}- return dict;+ return stack.stack;}};- return NameTree;+ return PostScriptEvaluator;})();-/**- * A helper for loading missing data in object graphs. It traverses the graph- * depth first and queues up any objects that have missing data. Once it has- * has traversed as many objects that are available it attempts to bundle the- * missing data requests and then resume from the nodes that weren't ready.- *- * NOTE: It provides protection from circular references by keeping track of- * of loaded references. However, you must be careful not to load any graphs- * that have references to the catalog or other pages since that will cause the- * entire PDF document object graph to be traversed.- */-var ObjectLoader = (function() {- function mayHaveChildren(value) {- return isRef(value) || isDict(value) || isArray(value) || isStream(value);+var PostScriptParser = (function PostScriptParserClosure() {+ function PostScriptParser(lexer) {+ this.lexer = lexer;+ this.operators = [];+ this.token = null;+ this.prev = null;}-- function addChildren(node, nodesToVisit) {- var value;- if (isDict(node) || isStream(node)) {- var map;- if (isDict(node)) {- map = node.map;- } else {- map = node.dict.map;+ PostScriptParser.prototype = {+ nextToken: function PostScriptParser_nextToken() {+ this.prev = this.token;+ this.token = this.lexer.getToken();+ },+ accept: function PostScriptParser_accept(type) {+ if (this.token.type == type) {+ this.nextToken();+ return true;}- for (var key in map) {- value = map[key];- if (mayHaveChildren(value)) {- nodesToVisit.push(value);+ return false;+ },+ expect: function PostScriptParser_expect(type) {+ if (this.accept(type))+ return true;+ error('Unexpected symbol: found ' + this.token.type + ' expected ' ++ type + '.');+ },+ parse: function PostScriptParser_parse() {+ this.nextToken();+ this.expect(PostScriptTokenTypes.LBRACE);+ this.parseBlock();+ this.expect(PostScriptTokenTypes.RBRACE);+ return this.operators;+ },+ parseBlock: function PostScriptParser_parseBlock() {+ while (true) {+ if (this.accept(PostScriptTokenTypes.NUMBER)) {+ this.operators.push(this.prev.value);+ } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {+ this.operators.push(this.prev.value);+ } else if (this.accept(PostScriptTokenTypes.LBRACE)) {+ this.parseCondition();+ } else {+ return;}}- } else if (isArray(node)) {- for (var i = 0, ii = node.length; i < ii; i++) {- value = node[i];- if (mayHaveChildren(value)) {- nodesToVisit.push(value);- }+ },+ parseCondition: function PostScriptParser_parseCondition() {+ // Add two place holders that will be updated later+ var conditionLocation = this.operators.length;+ this.operators.push(null, null);++ this.parseBlock();+ this.expect(PostScriptTokenTypes.RBRACE);+ if (this.accept(PostScriptTokenTypes.IF)) {+ // The true block is right after the 'if' so it just falls through on+ // true else it jumps and skips the true block.+ this.operators[conditionLocation] = this.operators.length;+ this.operators[conditionLocation + 1] = 'jz';+ } else if (this.accept(PostScriptTokenTypes.LBRACE)) {+ var jumpLocation = this.operators.length;+ this.operators.push(null, null);+ var endOfTrue = this.operators.length;+ this.parseBlock();+ this.expect(PostScriptTokenTypes.RBRACE);+ this.expect(PostScriptTokenTypes.IFELSE);+ // The jump is added at the end of the true block to skip the false+ // block.+ this.operators[jumpLocation] = this.operators.length;+ this.operators[jumpLocation + 1] = 'j';++ this.operators[conditionLocation] = endOfTrue;+ this.operators[conditionLocation + 1] = 'jz';+ } else {+ error('PS Function: error parsing conditional.');}}- }+ };+ return PostScriptParser;+})();- function ObjectLoader(obj, keys, xref) {- this.obj = obj;- this.keys = keys;- this.xref = xref;- this.refSet = null;+var PostScriptTokenTypes = {+ LBRACE: 0,+ RBRACE: 1,+ NUMBER: 2,+ OPERATOR: 3,+ IF: 4,+ IFELSE: 5+};++var PostScriptToken = (function PostScriptTokenClosure() {+ function PostScriptToken(type, value) {+ this.type = type;+ this.value = value;}- ObjectLoader.prototype = {- load: function ObjectLoader_load() {- var keys = this.keys;- this.promise = new LegacyPromise();- // Don't walk the graph if all the data is already loaded.- if (!(this.xref.stream instanceof ChunkedStream) ||- this.xref.stream.getMissingChunks().length === 0) {- this.promise.resolve();- return this.promise;- }+ var opCache = {};- this.refSet = new RefSet();- // Setup the initial nodes to visit.- var nodesToVisit = [];- for (var i = 0; i < keys.length; i++) {- nodesToVisit.push(this.obj[keys[i]]);- }+ PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {+ var opValue = opCache[op];+ if (opValue)+ return opValue;- this.walk(nodesToVisit);- return this.promise;- },+ return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);+ };- walk: function ObjectLoader_walk(nodesToVisit) {- var nodesToRevisit = [];- var pendingRequests = [];- // DFS walk of the object graph.- while (nodesToVisit.length) {- var currentNode = nodesToVisit.pop();+ PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,+ '{');+ PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,+ '}');+ PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');+ PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,+ 'IFELSE');+ return PostScriptToken;+})();- // Only references or chunked streams can cause missing data exceptions.- if (isRef(currentNode)) {- // Skip nodes that have already been visited.- if (this.refSet.has(currentNode)) {- continue;- }- try {- var ref = currentNode;- this.refSet.put(ref);- currentNode = this.xref.fetch(currentNode);- } catch (e) {- if (!(e instanceof MissingDataException)) {- throw e;- }- nodesToRevisit.push(currentNode);- pendingRequests.push({ begin: e.begin, end: e.end });- }- }- if (currentNode && currentNode.getBaseStreams) {- var baseStreams = currentNode.getBaseStreams();- var foundMissingData = false;- for (var i = 0; i < baseStreams.length; i++) {- var stream = baseStreams[i];- if (stream.getMissingChunks && stream.getMissingChunks().length) {- foundMissingData = true;- pendingRequests.push({- begin: stream.start,- end: stream.end- });- }- }- if (foundMissingData) {- nodesToRevisit.push(currentNode);- }- }+var PostScriptLexer = (function PostScriptLexerClosure() {+ function PostScriptLexer(stream) {+ this.stream = stream;+ }+ PostScriptLexer.prototype = {+ getToken: function PostScriptLexer_getToken() {+ var s = '';+ var ch;+ var comment = false;+ var stream = this.stream;- addChildren(currentNode, nodesToVisit);- }+ // skip comments+ while (true) {+ if (!(ch = stream.getChar()))+ return EOF;- if (pendingRequests.length) {- this.xref.stream.manager.requestRanges(pendingRequests,- function pendingRequestCallback() {- nodesToVisit = nodesToRevisit;- for (var i = 0; i < nodesToRevisit.length; i++) {- var node = nodesToRevisit[i];- // Remove any reference nodes from the currrent refset so they- // aren't skipped when we revist them.- if (isRef(node)) {- this.refSet.remove(node);- }- }- this.walk(nodesToVisit);- }.bind(this));- return;+ if (comment) {+ if (ch == '\x0a' || ch == '\x0d')+ comment = false;+ } else if (ch == '%') {+ comment = true;+ } else if (!Lexer.isSpace(ch)) {+ break;+ }}- // Everything is loaded.- this.refSet = null;- this.promise.resolve();+ switch (ch) {+ case '0': case '1': case '2': case '3': case '4':+ case '5': case '6': case '7': case '8': case '9':+ case '+': case '-': case '.':+ return new PostScriptToken(PostScriptTokenTypes.NUMBER,+ this.getNumber(ch));+ case '{':+ return PostScriptToken.LBRACE;+ case '}':+ return PostScriptToken.RBRACE;+ }+ // operator+ var str = ch.toLowerCase();+ while (true) {+ ch = stream.lookChar();+ if (ch === null)+ break;+ ch = ch.toLowerCase();+ if (ch >= 'a' && ch <= 'z')+ str += ch;+ else+ break;+ stream.skip();+ }+ switch (str) {+ case 'if':+ return PostScriptToken.IF;+ case 'ifelse':+ return PostScriptToken.IFELSE;+ default:+ return PostScriptToken.getOperator(str);+ }+ },+ getNumber: function PostScriptLexer_getNumber(ch) {+ var str = ch;+ var stream = this.stream;+ while (true) {+ ch = stream.lookChar();+ if ((ch >= '0' && ch <= '9') || ch == '-' || ch == '.')+ str += ch;+ else+ break;+ stream.skip();+ }+ var value = parseFloat(str);+ if (isNaN(value))+ error('Invalid floating point number: ' + value);+ return value;}};-- return ObjectLoader;+ return PostScriptLexer;})();+var ISOAdobeCharset = ['.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar','percent', 'ampersand', 'quoteright', 'parenleft', 'parenright',@@ -13799,15 +14883,752 @@ var CIDToUnicodeMaps = {+var ColorSpace = (function ColorSpaceClosure() {+ // Constructor should define this.numComps, this.defaultColor, this.name+ function ColorSpace() {+ error('should not call ColorSpace constructor');+ }++ ColorSpace.prototype = {+ /**+ * Converts the color value to the RGB color. The color components are+ * located in the src array starting from the srcOffset. Returns the array+ * of the rgb components, each value ranging from [0,255].+ */+ getRgb: function ColorSpace_getRgb(src, srcOffset) {+ error('Should not call ColorSpace.getRgb');+ },+ /**+ * Converts the color value to the RGB color, similar to the getRgb method.+ * The result placed into the dest array starting from the destOffset.+ */+ getRgbItem: function ColorSpace_getRgb(src, srcOffset, dest, destOffset) {+ error('Should not call ColorSpace.getRgbItem');+ },+ /**+ * Converts the specified number of the color values to the RGB colors.+ * The colors are located in the src array starting from the srcOffset.+ * The result is placed into the dest array starting from the destOffset.+ * The src array items shall be in [0,2^bits) range, the dest array items+ * will be in [0,255] range.+ */+ getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ error('Should not call ColorSpace.getRgbBuffer');+ },+ /**+ * Determines amount of the bytes is required to store the reslut of the+ * conversion that done by the getRgbBuffer method.+ */+ getOutputLength: function ColorSpace_getOutputLength(inputLength) {+ error('Should not call ColorSpace.getOutputLength');+ },+ /**+ * Returns true if source data will be equal the result/output data.+ */+ isPassthrough: function ColorSpace_isPassthrough(bits) {+ return false;+ },+ /**+ * Creates the output buffer and converts the specified number of the color+ * values to the RGB colors, similar to the getRgbBuffer.+ */+ createRgbBuffer: function ColorSpace_createRgbBuffer(src, srcOffset,+ count, bits) {+ if (this.isPassthrough(bits)) {+ return src.subarray(srcOffset);+ }+ var dest = new Uint8Array(count * 3);+ var numComponentColors = 1 << bits;+ // Optimization: create a color map when there is just one component and+ // we are converting more colors than the size of the color map. We+ // don't build the map if the colorspace is gray or rgb since those+ // methods are faster than building a map. This mainly offers big speed+ // ups for indexed and alternate colorspaces.+ if (this.numComps === 1 && count > numComponentColors &&+ this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {+ // TODO it may be worth while to cache the color map. While running+ // testing I never hit a cache so I will leave that out for now (perhaps+ // we are reparsing colorspaces too much?).+ var allColors = bits <= 8 ? new Uint8Array(numComponentColors) :+ new Uint16Array(numComponentColors);+ for (var i = 0; i < numComponentColors; i++) {+ allColors[i] = i;+ }+ var colorMap = new Uint8Array(numComponentColors * 3);+ this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bits);++ var destOffset = 0;+ for (var i = 0; i < count; ++i) {+ var key = src[srcOffset++] * 3;+ dest[destOffset++] = colorMap[key];+ dest[destOffset++] = colorMap[key + 1];+ dest[destOffset++] = colorMap[key + 2];+ }+ return dest;+ }+ this.getRgbBuffer(src, srcOffset, count, dest, 0, bits);+ return dest;+ },+ /**+ * True if the colorspace has components in the default range of [0, 1].+ * This should be true for all colorspaces except for lab color spaces+ * which are [0,100], [-128, 127], [-128, 127].+ */+ usesZeroToOneRange: true+ };++ ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {+ var IR = ColorSpace.parseToIR(cs, xref, res);+ if (IR instanceof AlternateCS)+ return IR;++ return ColorSpace.fromIR(IR);+ };++ ColorSpace.fromIR = function ColorSpace_fromIR(IR) {+ var name = isArray(IR) ? IR[0] : IR;++ switch (name) {+ case 'DeviceGrayCS':+ return new DeviceGrayCS();+ case 'DeviceRgbCS':+ return new DeviceRgbCS();+ case 'DeviceCmykCS':+ return new DeviceCmykCS();+ case 'PatternCS':+ var basePatternCS = IR[1];+ if (basePatternCS)+ basePatternCS = ColorSpace.fromIR(basePatternCS);+ return new PatternCS(basePatternCS);+ case 'IndexedCS':+ var baseIndexedCS = IR[1];+ var hiVal = IR[2];+ var lookup = IR[3];+ return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);+ case 'AlternateCS':+ var numComps = IR[1];+ var alt = IR[2];+ var tintFnIR = IR[3];++ return new AlternateCS(numComps, ColorSpace.fromIR(alt),+ PDFFunction.fromIR(tintFnIR));+ case 'LabCS':+ var whitePoint = IR[1].WhitePoint;+ var blackPoint = IR[1].BlackPoint;+ var range = IR[1].Range;+ return new LabCS(whitePoint, blackPoint, range);+ default:+ error('Unkown name ' + name);+ }+ return null;+ };++ ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {+ if (isName(cs)) {+ var colorSpaces = res.get('ColorSpace');+ if (isDict(colorSpaces)) {+ var refcs = colorSpaces.get(cs.name);+ if (refcs)+ cs = refcs;+ }+ }++ cs = xref.fetchIfRef(cs);+ var mode;++ if (isName(cs)) {+ mode = cs.name;+ this.mode = mode;++ switch (mode) {+ case 'DeviceGray':+ case 'G':+ return 'DeviceGrayCS';+ case 'DeviceRGB':+ case 'RGB':+ return 'DeviceRgbCS';+ case 'DeviceCMYK':+ case 'CMYK':+ return 'DeviceCmykCS';+ case 'Pattern':+ return ['PatternCS', null];+ default:+ error('unrecognized colorspace ' + mode);+ }+ } else if (isArray(cs)) {+ mode = cs[0].name;+ this.mode = mode;++ switch (mode) {+ case 'DeviceGray':+ case 'G':+ return 'DeviceGrayCS';+ case 'DeviceRGB':+ case 'RGB':+ return 'DeviceRgbCS';+ case 'DeviceCMYK':+ case 'CMYK':+ return 'DeviceCmykCS';+ case 'CalGray':+ return 'DeviceGrayCS';+ case 'CalRGB':+ return 'DeviceRgbCS';+ case 'ICCBased':+ var stream = xref.fetchIfRef(cs[1]);+ var dict = stream.dict;+ var numComps = dict.get('N');+ if (numComps == 1)+ return 'DeviceGrayCS';+ if (numComps == 3)+ return 'DeviceRgbCS';+ if (numComps == 4)+ return 'DeviceCmykCS';+ break;+ case 'Pattern':+ var basePatternCS = cs[1];+ if (basePatternCS)+ basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);+ return ['PatternCS', basePatternCS];+ case 'Indexed':+ case 'I':+ var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);+ var hiVal = cs[2] + 1;+ var lookup = xref.fetchIfRef(cs[3]);+ if (isStream(lookup)) {+ lookup = lookup.getBytes();+ }+ return ['IndexedCS', baseIndexedCS, hiVal, lookup];+ case 'Separation':+ case 'DeviceN':+ var name = cs[1];+ var numComps = 1;+ if (isName(name))+ numComps = 1;+ else if (isArray(name))+ numComps = name.length;+ var alt = ColorSpace.parseToIR(cs[2], xref, res);+ var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));+ return ['AlternateCS', numComps, alt, tintFnIR];+ case 'Lab':+ var params = cs[1].getAll();+ return ['LabCS', params];+ default:+ error('unimplemented color space object "' + mode + '"');+ }+ } else {+ error('unrecognized color space object: "' + cs + '"');+ }+ return null;+ };+ /**+ * Checks if a decode map matches the default decode map for a color space.+ * This handles the general decode maps where there are two values per+ * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.+ * This does not handle Lab, Indexed, or Pattern decode maps since they are+ * slightly different.+ * @param {Array} decode Decode map (usually from an image).+ * @param {Number} n Number of components the color space has.+ */+ ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {+ if (!decode)+ return true;++ if (n * 2 !== decode.length) {+ warn('The decode map is not the correct length');+ return true;+ }+ for (var i = 0, ii = decode.length; i < ii; i += 2) {+ if (decode[i] !== 0 || decode[i + 1] != 1)+ return false;+ }+ return true;+ };++ return ColorSpace;+})();++/**+ * Alternate color space handles both Separation and DeviceN color spaces. A+ * Separation color space is actually just a DeviceN with one color component.+ * Both color spaces use a tinting function to convert colors to a base color+ * space.+ */+var AlternateCS = (function AlternateCSClosure() {+ function AlternateCS(numComps, base, tintFn) {+ this.name = 'Alternate';+ this.numComps = numComps;+ this.defaultColor = new Float32Array(numComps);+ for (var i = 0; i < numComps; ++i) {+ this.defaultColor[i] = 1;+ }+ this.base = base;+ this.tintFn = tintFn;+ }++ AlternateCS.prototype = {+ getRgb: function AlternateCS_getRgb(src, srcOffset) {+ var rgb = new Uint8Array(3);+ this.getRgbItem(src, srcOffset, rgb, 0);+ return rgb;+ },+ getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,+ dest, destOffset) {+ var baseNumComps = this.base.numComps;+ var input = 'subarray' in src ?+ src.subarray(srcOffset, srcOffset + this.numComps) :+ Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps);+ var tinted = this.tintFn(input);+ this.base.getRgbItem(tinted, 0, dest, destOffset);+ },+ getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ var tintFn = this.tintFn;+ var base = this.base;+ var scale = 1 / ((1 << bits) - 1);+ var baseNumComps = base.numComps;+ var usesZeroToOneRange = base.usesZeroToOneRange;+ var isPassthrough = base.isPassthrough(8) || !usesZeroToOneRange;+ var pos = isPassthrough ? destOffset : 0;+ var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);+ var numComps = this.numComps;++ var scaled = new Float32Array(numComps);+ for (var i = 0; i < count; i++) {+ for (var j = 0; j < numComps; j++) {+ scaled[j] = src[srcOffset++] * scale;+ }+ var tinted = tintFn(scaled);+ if (usesZeroToOneRange) {+ for (var j = 0; j < baseNumComps; j++) {+ baseBuf[pos++] = tinted[j] * 255;+ }+ } else {+ base.getRgbItem(tinted, 0, baseBuf, pos);+ pos += baseNumComps;+ }+ }+ if (!isPassthrough) {+ base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8);+ }+ },+ getOutputLength: function AlternateCS_getOutputLength(inputLength) {+ return this.base.getOutputLength(inputLength *+ this.base.numComps / this.numComps);+ },+ isPassthrough: ColorSpace.prototype.isPassthrough,+ createRgbBuffer: ColorSpace.prototype.createRgbBuffer,+ isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {+ return ColorSpace.isDefaultDecode(decodeMap, this.numComps);+ },+ usesZeroToOneRange: true+ };++ return AlternateCS;+})();++var PatternCS = (function PatternCSClosure() {+ function PatternCS(baseCS) {+ this.name = 'Pattern';+ this.base = baseCS;+ }+ PatternCS.prototype = {};++ return PatternCS;+})();++var IndexedCS = (function IndexedCSClosure() {+ function IndexedCS(base, highVal, lookup) {+ this.name = 'Indexed';+ this.numComps = 1;+ this.defaultColor = new Uint8Array([0]);+ this.base = base;+ this.highVal = highVal;++ var baseNumComps = base.numComps;+ var length = baseNumComps * highVal;+ var lookupArray;++ if (isStream(lookup)) {+ lookupArray = new Uint8Array(length);+ var bytes = lookup.getBytes(length);+ lookupArray.set(bytes);+ } else if (isString(lookup)) {+ lookupArray = new Uint8Array(length);+ for (var i = 0; i < length; ++i)+ lookupArray[i] = lookup.charCodeAt(i);+ } else if (lookup instanceof Uint8Array || lookup instanceof Array) {+ lookupArray = lookup;+ } else {+ error('Unrecognized lookup table: ' + lookup);+ }+ this.lookup = lookupArray;+ }++ IndexedCS.prototype = {+ getRgb: function IndexedCS_getRgb(src, srcOffset) {+ var numComps = this.base.numComps;+ var start = src[srcOffset] * numComps;+ return this.base.getRgb(this.lookup, start);+ },+ getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,+ dest, destOffset) {+ var numComps = this.base.numComps;+ var start = src[srcOffset] * numComps;+ this.base.getRgbItem(this.lookup, start, dest, destOffset);+ },+ getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset) {+ var base = this.base;+ var numComps = base.numComps;+ var outputDelta = base.getOutputLength(numComps);+ var lookup = this.lookup;++ for (var i = 0; i < count; ++i) {+ var lookupPos = src[srcOffset++] * numComps;+ base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8);+ destOffset += outputDelta;+ }+ },+ getOutputLength: function IndexedCS_getOutputLength(inputLength) {+ return this.base.getOutputLength(inputLength * this.base.numComps);+ },+ isPassthrough: ColorSpace.prototype.isPassthrough,+ createRgbBuffer: ColorSpace.prototype.createRgbBuffer,+ isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {+ // indexed color maps shouldn't be changed+ return true;+ },+ usesZeroToOneRange: true+ };+ return IndexedCS;+})();++var DeviceGrayCS = (function DeviceGrayCSClosure() {+ function DeviceGrayCS() {+ this.name = 'DeviceGray';+ this.numComps = 1;+ this.defaultColor = new Float32Array([0]);+ }++ DeviceGrayCS.prototype = {+ getRgb: function DeviceGrayCS_getRgb(src, srcOffset) {+ var rgb = new Uint8Array(3);+ this.getRgbItem(src, srcOffset, rgb, 0);+ return rgb;+ },+ getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,+ dest, destOffset) {+ var c = (src[srcOffset] * 255) | 0;+ c = c < 0 ? 0 : c > 255 ? 255 : c;+ dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;+ },+ getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ var scale = 255 / ((1 << bits) - 1);+ var j = srcOffset, q = destOffset;+ for (var i = 0; i < count; ++i) {+ var c = (scale * src[j++]) | 0;+ dest[q++] = c;+ dest[q++] = c;+ dest[q++] = c;+ }+ },+ getOutputLength: function DeviceGrayCS_getOutputLength(inputLength) {+ return inputLength * 3;+ },+ isPassthrough: ColorSpace.prototype.isPassthrough,+ createRgbBuffer: ColorSpace.prototype.createRgbBuffer,+ isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {+ return ColorSpace.isDefaultDecode(decodeMap, this.numComps);+ },+ usesZeroToOneRange: true+ };+ return DeviceGrayCS;+})();++var DeviceRgbCS = (function DeviceRgbCSClosure() {+ function DeviceRgbCS() {+ this.name = 'DeviceRGB';+ this.numComps = 3;+ this.defaultColor = new Float32Array([0, 0, 0]);+ }+ DeviceRgbCS.prototype = {+ getRgb: function DeviceRgbCS_getRgb(src, srcOffset) {+ var rgb = new Uint8Array(3);+ this.getRgbItem(src, srcOffset, rgb, 0);+ return rgb;+ },+ getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,+ dest, destOffset) {+ var r = (src[srcOffset] * 255) | 0;+ var g = (src[srcOffset + 1] * 255) | 0;+ var b = (src[srcOffset + 2] * 255) | 0;+ dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;+ dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;+ dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;+ },+ getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ var length = count * 3;+ if (bits == 8) {+ dest.set(src.subarray(srcOffset, srcOffset + length), destOffset);+ return;+ }+ var scale = 255 / ((1 << bits) - 1);+ var j = srcOffset, q = destOffset;+ for (var i = 0; i < length; ++i) {+ dest[q++] = (scale * src[j++]) | 0;+ }+ },+ getOutputLength: function DeviceRgbCS_getOutputLength(inputLength) {+ return inputLength;+ },+ isPassthrough: function DeviceRgbCS_isPassthrough(bits) {+ return bits == 8;+ },+ createRgbBuffer: ColorSpace.prototype.createRgbBuffer,+ isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {+ return ColorSpace.isDefaultDecode(decodeMap, this.numComps);+ },+ usesZeroToOneRange: true+ };+ return DeviceRgbCS;+})();++var DeviceCmykCS = (function DeviceCmykCSClosure() {+ // The coefficients below was found using numerical analysis: the method of+ // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,+ // where color_value is the tabular value from the table of sampled RGB colors+ // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding+ // CMYK color conversion using the estimation below:+ // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255+ function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {+ var c = src[srcOffset + 0] * srcScale;+ var m = src[srcOffset + 1] * srcScale;+ var y = src[srcOffset + 2] * srcScale;+ var k = src[srcOffset + 3] * srcScale;++ var r =+ c * (-4.387332384609988 * c + 54.48615194189176 * m ++ 18.82290502165302 * y + 212.25662451639585 * k ++ -285.2331026137004) ++ m * (1.7149763477362134 * m - 5.6096736904047315 * y ++ -17.873870861415444 * k - 5.497006427196366) ++ y * (-2.5217340131683033 * y - 21.248923337353073 * k ++ 17.5119270841813) ++ k * (-21.86122147463605 * k - 189.48180835922747) + 255;+ var g =+ c * (8.841041422036149 * c + 60.118027045597366 * m ++ 6.871425592049007 * y + 31.159100130055922 * k ++ -79.2970844816548) ++ m * (-15.310361306967817 * m + 17.575251261109482 * y ++ 131.35250912493976 * k - 190.9453302588951) ++ y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) ++ k * (-20.737325471181034 * k - 187.80453709719578) + 255;+ var b =+ c * (0.8842522430003296 * c + 8.078677503112928 * m ++ 30.89978309703729 * y - 0.23883238689178934 * k ++ -14.183576799673286) ++ m * (10.49593273432072 * m + 63.02378494754052 * y ++ 50.606957656360734 * k - 112.23884253719248) ++ y * (0.03296041114873217 * y + 115.60384449646641 * k ++ -193.58209356861505) ++ k * (-22.33816807309886 * k - 180.12613974708367) + 255;++ dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;+ dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;+ dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;+ }++ function DeviceCmykCS() {+ this.name = 'DeviceCMYK';+ this.numComps = 4;+ this.defaultColor = new Float32Array([0, 0, 0, 1]);+ }+ DeviceCmykCS.prototype = {+ getRgb: function DeviceCmykCS_getRgb(src, srcOffset) {+ var rgb = new Uint8Array(3);+ convertToRgb(src, srcOffset, 1, rgb, 0);+ return rgb;+ },+ getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,+ dest, destOffset) {+ convertToRgb(src, srcOffset, 1, dest, destOffset);+ },+ getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ var scale = 1 / ((1 << bits) - 1);+ for (var i = 0; i < count; i++) {+ convertToRgb(src, srcOffset, scale, dest, destOffset);+ srcOffset += 4;+ destOffset += 3;+ }+ },+ getOutputLength: function DeviceCmykCS_getOutputLength(inputLength) {+ return (inputLength >> 2) * 3;+ },+ isPassthrough: ColorSpace.prototype.isPassthrough,+ createRgbBuffer: ColorSpace.prototype.createRgbBuffer,+ isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {+ return ColorSpace.isDefaultDecode(decodeMap, this.numComps);+ },+ usesZeroToOneRange: true+ };++ return DeviceCmykCS;+})();++//+// LabCS: Based on "PDF Reference, Sixth Ed", p.250+//+var LabCS = (function LabCSClosure() {+ function LabCS(whitePoint, blackPoint, range) {+ this.name = 'Lab';+ this.numComps = 3;+ this.defaultColor = new Float32Array([0, 0, 0]);++ if (!whitePoint)+ error('WhitePoint missing - required for color space Lab');+ blackPoint = blackPoint || [0, 0, 0];+ range = range || [-100, 100, -100, 100];++ // Translate args to spec variables+ this.XW = whitePoint[0];+ this.YW = whitePoint[1];+ this.ZW = whitePoint[2];+ this.amin = range[0];+ this.amax = range[1];+ this.bmin = range[2];+ this.bmax = range[3];++ // These are here just for completeness - the spec doesn't offer any+ // formulas that use BlackPoint in Lab+ this.XB = blackPoint[0];+ this.YB = blackPoint[1];+ this.ZB = blackPoint[2];++ // Validate vars as per spec+ if (this.XW < 0 || this.ZW < 0 || this.YW !== 1)+ error('Invalid WhitePoint components, no fallback available');++ if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {+ info('Invalid BlackPoint, falling back to default');+ this.XB = this.YB = this.ZB = 0;+ }++ if (this.amin > this.amax || this.bmin > this.bmax) {+ info('Invalid Range, falling back to defaults');+ this.amin = -100;+ this.amax = 100;+ this.bmin = -100;+ this.bmax = 100;+ }+ }++ // Function g(x) from spec+ function fn_g(x) {+ if (x >= 6 / 29)+ return x * x * x;+ else+ return (108 / 841) * (x - 4 / 29);+ }++ function decode(value, high1, low2, high2) {+ return low2 + (value) * (high2 - low2) / (high1);+ }++ // If decoding is needed maxVal should be 2^bits per component - 1.+ function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {+ // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]+ // not the usual [0, 1]. If a command like setFillColor is used the src+ // values will already be within the correct range. However, if we are+ // converting an image we have to map the values to the correct range given+ // above.+ // Ls,as,bs <---> L*,a*,b* in the spec+ var Ls = src[srcOffset];+ var as = src[srcOffset + 1];+ var bs = src[srcOffset + 2];+ if (maxVal !== false) {+ Ls = decode(Ls, maxVal, 0, 100);+ as = decode(as, maxVal, cs.amin, cs.amax);+ bs = decode(bs, maxVal, cs.bmin, cs.bmax);+ }++ // Adjust limits of 'as' and 'bs'+ as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;+ bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;++ // Computes intermediate variables X,Y,Z as per spec+ var M = (Ls + 16) / 116;+ var L = M + (as / 500);+ var N = M - (bs / 200);++ var X = cs.XW * fn_g(L);+ var Y = cs.YW * fn_g(M);+ var Z = cs.ZW * fn_g(N);++ var r, g, b;+ // Using different conversions for D50 and D65 white points,+ // per http://www.color.org/srgb.pdf+ if (cs.ZW < 1) {+ // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)+ r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;+ g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;+ b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;+ } else {+ // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)+ r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;+ g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;+ b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;+ }+ // clamp color values to [0,1] range then convert to [0,255] range.+ dest[destOffset] = Math.sqrt(r < 0 ? 0 : r > 1 ? 1 : r) * 255;+ dest[destOffset + 1] = Math.sqrt(g < 0 ? 0 : g > 1 ? 1 : g) * 255;+ dest[destOffset + 2] = Math.sqrt(b < 0 ? 0 : b > 1 ? 1 : b) * 255;+ }++ LabCS.prototype = {+ getRgb: function LabCS_getRgb(src, srcOffset) {+ var rgb = new Uint8Array(3);+ convertToRgb(this, src, srcOffset, false, rgb, 0);+ return rgb;+ },+ getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {+ convertToRgb(this, src, srcOffset, false, dest, destOffset);+ },+ getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,+ dest, destOffset, bits) {+ var maxVal = (1 << bits) - 1;+ for (var i = 0; i < count; i++) {+ convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);+ srcOffset += 3;+ destOffset += 3;+ }+ },+ getOutputLength: function LabCS_getOutputLength(inputLength) {+ return inputLength;+ },+ isPassthrough: ColorSpace.prototype.isPassthrough,+ isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {+ // XXX: Decoding is handled with the lab conversion because of the strange+ // ranges that are used.+ return true;+ },+ usesZeroToOneRange: false+ };+ return LabCS;+})();++var ARCFourCipher = (function ARCFourCipherClosure() {function ARCFourCipher(key) {this.a = 0;this.b = 0;var s = new Uint8Array(256);var i, j = 0, tmp, keyLength = key.length;- for (i = 0; i < 256; ++i) {+ for (i = 0; i < 256; ++i)s[i] = i;- }for (i = 0; i < 256; ++i) {tmp = s[i];j = (j + tmp + key[i % keyLength]) & 0xFF;@@ -13867,14 +15688,12 @@ var calculateMD5 = (function calculateMD5Closure() {var paddedLength = (length + 72) & ~63; // data + 9 extra bytesvar padded = new Uint8Array(paddedLength);var i, j, n;- for (i = 0; i < length; ++i) {+ for (i = 0; i < length; ++i)padded[i] = data[offset++];- }padded[i++] = 0x80;n = paddedLength - 8;- while (i < n) {+ while (i < n)padded[i++] = 0;- }padded[i++] = (length << 3) & 0xFF;padded[i++] = (length >> 5) & 0xFF;padded[i++] = (length >> 13) & 0xFF;@@ -13918,17 +15737,18 @@ var calculateMD5 = (function calculateMD5Closure() {h3 = (h3 + d) | 0;}return new Uint8Array([- h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,- h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,- h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,- h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF+ h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >>> 24) & 0xFF,+ h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >>> 24) & 0xFF,+ h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >>> 24) & 0xFF,+ h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >>> 24) & 0xFF]);}return hash;})();var NullCipher = (function NullCipherClosure() {- function NullCipher() {}+ function NullCipher() {+ }NullCipher.prototype = {decryptBlock: function NullCipher_decryptBlock(data) {@@ -14084,9 +15904,8 @@ var AES128Cipher = (function AES128CipherClosure() {var i, j, k;var t, u, v;// AddRoundKey- for (j = 0, k = 160; j < 16; ++j, ++k) {+ for (j = 0, k = 160; j < 16; ++j, ++k)state[j] ^= key[k];- }for (i = 9; i >= 1; --i) {// InvShiftRowst = state[13]; state[13] = state[9]; state[9] = state[5];@@ -14096,13 +15915,11 @@ var AES128Cipher = (function AES128CipherClosure() {t = state[15]; u = state[11]; v = state[7]; state[15] = state[3];state[11] = t; state[7] = u; state[3] = v;// InvSubBytes- for (j = 0; j < 16; ++j) {+ for (j = 0; j < 16; ++j)state[j] = inv_s[state[j]];- }// AddRoundKey- for (j = 0, k = i * 16; j < 16; ++j, ++k) {+ for (j = 0, k = i * 16; j < 16; ++j, ++k)state[j] ^= key[k];- }// InvMixColumnsfor (j = 0; j < 16; j += 4) {var s0 = mix[state[j]], s1 = mix[state[j + 1]],@@ -14144,15 +15961,13 @@ var AES128Cipher = (function AES128CipherClosure() {for (i = 0; i < sourceLength; ++i) {buffer[bufferLength] = data[i];++bufferLength;- if (bufferLength < 16) {+ if (bufferLength < 16)continue;- }// buffer is full, decryptingvar plain = decrypt128(buffer, this.key);// xor-ing the IV vector to get plain text- for (j = 0; j < 16; ++j) {+ for (j = 0; j < 16; ++j)plain[j] ^= iv[j];- }iv = buffer;result.push(plain);buffer = new Uint8Array(16);@@ -14174,9 +15989,8 @@ var AES128Cipher = (function AES128CipherClosure() {result[result.length - 1] = lastBlock.subarray(0, 16 - lastBlock[15]);}var output = new Uint8Array(outputLength);- for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16) {+ for (i = 0, j = 0, ii = result.length; i < ii; ++i, j += 16)output.set(result[i], j);- }return output;}@@ -14185,9 +15999,8 @@ var AES128Cipher = (function AES128CipherClosure() {var i, sourceLength = data.length;var buffer = this.buffer, bufferLength = this.bufferPosition;// waiting for IV values -- they are at the start of the stream- for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength) {+ for (i = 0; bufferLength < 16 && i < sourceLength; ++i, ++bufferLength)buffer[bufferLength] = data[i];- }if (bufferLength < 16) {// need more datathis.bufferLength = bufferLength;@@ -14211,9 +16024,9 @@ var CipherTransform = (function CipherTransformClosure() {this.streamCipherConstructor = streamCipherConstructor;}CipherTransform.prototype = {- createStream: function CipherTransform_createStream(stream, length) {+ createStream: function CipherTransform_createStream(stream) {var cipher = new this.streamCipherConstructor();- return new DecryptStream(stream, length,+ return new DecryptStream(stream,function cipherTransformDecryptStream(data, finalize) {return cipher.decryptBlock(data, finalize);}@@ -14238,29 +16051,25 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {function prepareKeyData(fileId, password, ownerPassword, userPassword,flags, revision, keyLength, encryptMetadata) {- var hashDataSize = 40 + ownerPassword.length + fileId.length;- var hashData = new Uint8Array(hashDataSize), i = 0, j, n;+ var hashData = new Uint8Array(100), i = 0, j, n;if (password) {n = Math.min(32, password.length);- for (; i < n; ++i) {+ for (; i < n; ++i)hashData[i] = password[i];- }}j = 0;while (i < 32) {hashData[i++] = defaultPasswordBytes[j++];}// as now the padded password in the hashData[0..i]- for (j = 0, n = ownerPassword.length; j < n; ++j) {+ for (j = 0, n = ownerPassword.length; j < n; ++j)hashData[i++] = ownerPassword[j];- }hashData[i++] = flags & 0xFF;hashData[i++] = (flags >> 8) & 0xFF;hashData[i++] = (flags >> 16) & 0xFF;hashData[i++] = (flags >>> 24) & 0xFF;- for (j = 0, n = fileId.length; j < n; ++j) {+ for (j = 0, n = fileId.length; j < n; ++j)hashData[i++] = fileId[j];- }if (revision >= 4 && !encryptMetadata) {hashData[i++] = 0xFF;hashData[i++] = 0xFF;@@ -14271,1099 +16080,350 @@ var CipherTransformFactory = (function CipherTransformFactoryClosure() {var keyLengthInBytes = keyLength >> 3;if (revision >= 3) {for (j = 0; j < 50; ++j) {- hash = calculateMD5(hash, 0, keyLengthInBytes);+ hash = calculateMD5(hash, 0, keyLengthInBytes);}}var encryptionKey = hash.subarray(0, keyLengthInBytes);var cipher, checkData;if (revision >= 3) {- for (i = 0; i < 32; ++i) {+ for (i = 0; i < 32; ++i)hashData[i] = defaultPasswordBytes[i];- }- for (j = 0, n = fileId.length; j < n; ++j) {+ for (j = 0, n = fileId.length; j < n; ++j)hashData[i++] = fileId[j];- }cipher = new ARCFourCipher(encryptionKey);- checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));+ var checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));n = encryptionKey.length;var derivedKey = new Uint8Array(n), k;for (j = 1; j <= 19; ++j) {- for (k = 0; k < n; ++k) {+ for (k = 0; k < n; ++k)derivedKey[k] = encryptionKey[k] ^ j;- }cipher = new ARCFourCipher(derivedKey);checkData = cipher.encryptBlock(checkData);}for (j = 0, n = checkData.length; j < n; ++j) {- if (userPassword[j] != checkData[j]) {+ if (userPassword[j] != checkData[j])return null;- }}} else {cipher = new ARCFourCipher(encryptionKey);- checkData = cipher.encryptBlock(defaultPasswordBytes);- for (j = 0, n = checkData.length; j < n; ++j) {- if (userPassword[j] != checkData[j]) {- return null;- }- }- }- return encryptionKey;- }-- function decodeUserPassword(password, ownerPassword, revision, keyLength) {- var hashData = new Uint8Array(32), i = 0, j, n;- n = Math.min(32, password.length);- for (; i < n; ++i) {- hashData[i] = password[i];- }- j = 0;- while (i < 32) {- hashData[i++] = defaultPasswordBytes[j++];- }- var hash = calculateMD5(hashData, 0, i);- var keyLengthInBytes = keyLength >> 3;- if (revision >= 3) {- for (j = 0; j < 50; ++j) {- hash = calculateMD5(hash, 0, hash.length);- }- }-- var cipher, userPassword;- if (revision >= 3) {- userPassword = ownerPassword;- var derivedKey = new Uint8Array(keyLengthInBytes), k;- for (j = 19; j >= 0; j--) {- for (k = 0; k < keyLengthInBytes; ++k) {- derivedKey[k] = hash[k] ^ j;- }- cipher = new ARCFourCipher(derivedKey);- userPassword = cipher.encryptBlock(userPassword);- }- } else {- cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));- userPassword = cipher.encryptBlock(ownerPassword);- }- return userPassword;- }-- var identityName = Name.get('Identity');-- function CipherTransformFactory(dict, fileId, password) {- var filter = dict.get('Filter');- if (!isName(filter) || filter.name != 'Standard') {- error('unknown encryption method');- }- this.dict = dict;- var algorithm = dict.get('V');- if (!isInt(algorithm) ||- (algorithm != 1 && algorithm != 2 && algorithm != 4)) {- error('unsupported encryption algorithm');- }- this.algorithm = algorithm;- var keyLength = dict.get('Length') || 40;- if (!isInt(keyLength) ||- keyLength < 40 || (keyLength % 8) !== 0) {- error('invalid key length');- }-- // prepare keys- var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);- var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);- var flags = dict.get('P');- var revision = dict.get('R');- var encryptMetadata = (algorithm == 4 && // meaningful when V is 4- dict.get('EncryptMetadata') !== false); // makes true as default value- this.encryptMetadata = encryptMetadata;-- var fileIdBytes = stringToBytes(fileId);- var passwordBytes;- if (password) {- passwordBytes = stringToBytes(password);- }-- var encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,- ownerPassword, userPassword, flags,- revision, keyLength, encryptMetadata);- if (!encryptionKey && !password) {- throw new PasswordException('No password given',- PasswordResponses.NEED_PASSWORD);- } else if (!encryptionKey && password) {- // Attempting use the password as an owner password- var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,- revision, keyLength);- encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,- ownerPassword, userPassword, flags,- revision, keyLength, encryptMetadata);- }-- if (!encryptionKey) {- throw new PasswordException('Incorrect Password',- PasswordResponses.INCORRECT_PASSWORD);- }-- this.encryptionKey = encryptionKey;-- if (algorithm == 4) {- this.cf = dict.get('CF');- this.stmf = dict.get('StmF') || identityName;- this.strf = dict.get('StrF') || identityName;- this.eff = dict.get('EFF') || this.strf;- }- }-- function buildObjectKey(num, gen, encryptionKey, isAes) {- var key = new Uint8Array(encryptionKey.length + 9), i, n;- for (i = 0, n = encryptionKey.length; i < n; ++i) {- key[i] = encryptionKey[i];- }- key[i++] = num & 0xFF;- key[i++] = (num >> 8) & 0xFF;- key[i++] = (num >> 16) & 0xFF;- key[i++] = gen & 0xFF;- key[i++] = (gen >> 8) & 0xFF;- if (isAes) {- key[i++] = 0x73;- key[i++] = 0x41;- key[i++] = 0x6C;- key[i++] = 0x54;- }- var hash = calculateMD5(key, 0, i);- return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));- }-- function buildCipherConstructor(cf, name, num, gen, key) {- var cryptFilter = cf.get(name.name);- var cfm;- if (cryptFilter !== null && cryptFilter !== undefined) {- cfm = cryptFilter.get('CFM');- }- if (!cfm || cfm.name == 'None') {- return function cipherTransformFactoryBuildCipherConstructorNone() {- return new NullCipher();- };- }- if ('V2' == cfm.name) {- return function cipherTransformFactoryBuildCipherConstructorV2() {- return new ARCFourCipher(buildObjectKey(num, gen, key, false));- };- }- if ('AESV2' == cfm.name) {- return function cipherTransformFactoryBuildCipherConstructorAESV2() {- return new AES128Cipher(buildObjectKey(num, gen, key, true));- };- }- error('Unknown crypto method');- }-- CipherTransformFactory.prototype = {- createCipherTransform:- function CipherTransformFactory_createCipherTransform(num, gen) {- if (this.algorithm == 4) {- return new CipherTransform(- buildCipherConstructor(this.cf, this.stmf,- num, gen, this.encryptionKey),- buildCipherConstructor(this.cf, this.strf,- num, gen, this.encryptionKey));- }- // algorithms 1 and 2- var key = buildObjectKey(num, gen, this.encryptionKey, false);- var cipherConstructor = function buildCipherCipherConstructor() {- return new ARCFourCipher(key);- };- return new CipherTransform(cipherConstructor, cipherConstructor);- }- };-- return CipherTransformFactory;-})();----var PatternType = {- FUNCTION_BASED: 1,- AXIAL: 2,- RADIAL: 3,- FREE_FORM_MESH: 4,- LATTICE_FORM_MESH: 5,- COONS_PATCH_MESH: 6,- TENSOR_PATCH_MESH: 7-};--var Pattern = (function PatternClosure() {- // Constructor should define this.getPattern- function Pattern() {- error('should not call Pattern constructor');- }-- Pattern.prototype = {- // Input: current Canvas context- // Output: the appropriate fillStyle or strokeStyle- getPattern: function Pattern_getPattern(ctx) {- error('Should not call Pattern.getStyle: ' + ctx);- }- };-- Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,- res) {-- var dict = isStream(shading) ? shading.dict : shading;- var type = dict.get('ShadingType');-- switch (type) {- case PatternType.AXIAL:- case PatternType.RADIAL:- // Both radial and axial shadings are handled by RadialAxial shading.- return new Shadings.RadialAxial(dict, matrix, xref, res);- case PatternType.FREE_FORM_MESH:- case PatternType.LATTICE_FORM_MESH:- case PatternType.COONS_PATCH_MESH:- case PatternType.TENSOR_PATCH_MESH:- return new Shadings.Mesh(shading, matrix, xref, res);- default:- UnsupportedManager.notify(UNSUPPORTED_FEATURES.shadingPattern);- return new Shadings.Dummy();- }- };- return Pattern;-})();--var Shadings = {};--// A small number to offset the first/last color stops so we can insert ones to-// support extend. Number.MIN_VALUE appears to be too small and breaks the-// extend. 1e-7 works in FF but chrome seems to use an even smaller sized number-// internally so we have to go bigger.-Shadings.SMALL_NUMBER = 1e-2;--// Radial and axial shading have very similar implementations-// If needed, the implementations can be broken into two classes-Shadings.RadialAxial = (function RadialAxialClosure() {- function RadialAxial(dict, matrix, xref, res) {- this.matrix = matrix;- this.coordsArr = dict.get('Coords');- this.shadingType = dict.get('ShadingType');- this.type = 'Pattern';- var cs = dict.get('ColorSpace', 'CS');- cs = ColorSpace.parse(cs, xref, res);- this.cs = cs;-- var t0 = 0.0, t1 = 1.0;- if (dict.has('Domain')) {- var domainArr = dict.get('Domain');- t0 = domainArr[0];- t1 = domainArr[1];- }-- var extendStart = false, extendEnd = false;- if (dict.has('Extend')) {- var extendArr = dict.get('Extend');- extendStart = extendArr[0];- extendEnd = extendArr[1];- }-- if (this.shadingType === PatternType.RADIAL &&- (!extendStart || !extendEnd)) {- // Radial gradient only currently works if either circle is fully within- // the other circle.- var x1 = this.coordsArr[0];- var y1 = this.coordsArr[1];- var r1 = this.coordsArr[2];- var x2 = this.coordsArr[3];- var y2 = this.coordsArr[4];- var r2 = this.coordsArr[5];- var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));- if (r1 <= r2 + distance &&- r2 <= r1 + distance) {- warn('Unsupported radial gradient.');- }- }-- this.extendStart = extendStart;- this.extendEnd = extendEnd;-- var fnObj = dict.get('Function');- var fn;- if (isArray(fnObj)) {- var fnArray = [];- for (var j = 0, jj = fnObj.length; j < jj; j++) {- var obj = xref.fetchIfRef(fnObj[j]);- if (!isPDFFunction(obj)) {- error('Invalid function');- }- fnArray.push(PDFFunction.parse(xref, obj));- }- fn = function radialAxialColorFunction(arg) {- var out = [];- for (var i = 0, ii = fnArray.length; i < ii; i++) {- out.push(fnArray[i](arg)[0]);- }- return out;- };- } else {- if (!isPDFFunction(fnObj)) {- error('Invalid function');- }- fn = PDFFunction.parse(xref, fnObj);- }-- // 10 samples seems good enough for now, but probably won't work- // if there are sharp color changes. Ideally, we would implement- // the spec faithfully and add lossless optimizations.- var diff = t1 - t0;- var step = diff / 10;-- var colorStops = this.colorStops = [];-- // Protect against bad domains so we don't end up in an infinte loop below.- if (t0 >= t1 || step <= 0) {- // Acrobat doesn't seem to handle these cases so we'll ignore for- // now.- info('Bad shading domain.');- return;- }-- var rgbColor;- for (var i = t0; i <= t1; i += step) {- rgbColor = cs.getRgb(fn([i]), 0);- var cssColor = Util.makeCssRgb(rgbColor);- colorStops.push([(i - t0) / diff, cssColor]);- }-- var background = 'transparent';- if (dict.has('Background')) {- rgbColor = cs.getRgb(dict.get('Background'), 0);- background = Util.makeCssRgb(rgbColor);- }-- if (!extendStart) {- // Insert a color stop at the front and offset the first real color stop- // so it doesn't conflict with the one we insert.- colorStops.unshift([0, background]);- colorStops[1][0] += Shadings.SMALL_NUMBER;- }- if (!extendEnd) {- // Same idea as above in extendStart but for the end.- colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;- colorStops.push([1, background]);- }-- this.colorStops = colorStops;- }-- RadialAxial.prototype = {- getIR: function RadialAxial_getIR() {- var coordsArr = this.coordsArr;- var shadingType = this.shadingType;- var type, p0, p1, r0, r1;- if (shadingType == PatternType.AXIAL) {- p0 = [coordsArr[0], coordsArr[1]];- p1 = [coordsArr[2], coordsArr[3]];- r0 = null;- r1 = null;- type = 'axial';- } else if (shadingType == PatternType.RADIAL) {- p0 = [coordsArr[0], coordsArr[1]];- p1 = [coordsArr[3], coordsArr[4]];- r0 = coordsArr[2];- r1 = coordsArr[5];- type = 'radial';- } else {- error('getPattern type unknown: ' + shadingType);- }-- var matrix = this.matrix;- if (matrix) {- p0 = Util.applyTransform(p0, matrix);- p1 = Util.applyTransform(p1, matrix);- }-- return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];- }- };-- return RadialAxial;-})();--// All mesh shading. For now, they will be presented as set of the triangles-// to be drawn on the canvas and rgb color for each vertex.-Shadings.Mesh = (function MeshClosure() {- function MeshStreamReader(stream, context) {- this.stream = stream;- this.context = context;- this.buffer = 0;- this.bufferLength = 0;- }- MeshStreamReader.prototype = {- get hasData() {- if (this.stream.end) {- return this.stream.pos < this.stream.end;- }- if (this.bufferLength > 0) {- return true;- }- var nextByte = this.stream.getByte();- if (nextByte < 0) {- return false;- }- this.buffer = nextByte;- this.bufferLength = 8;- return true;- },- readBits: function MeshStreamReader_readBits(n) {- var buffer = this.buffer;- var bufferLength = this.bufferLength;- if (n === 32) {- if (bufferLength === 0) {- return ((this.stream.getByte() << 24) |- (this.stream.getByte() << 16) | (this.stream.getByte() << 8) |- this.stream.getByte()) >>> 0;- }- buffer = (buffer << 24) | (this.stream.getByte() << 16) |- (this.stream.getByte() << 8) | this.stream.getByte();- var nextByte = this.stream.getByte();- this.buffer = nextByte & ((1 << bufferLength) - 1);- return ((buffer << (8 - bufferLength)) |- ((nextByte & 0xFF) >> bufferLength)) >>> 0;- }- if (n === 8 && bufferLength === 0) {- return this.stream.getByte();- }- while (bufferLength < n) {- buffer = (buffer << 8) | this.stream.getByte();- bufferLength += 8;- }- bufferLength -= n;- this.bufferLength = bufferLength;- this.buffer = buffer & ((1 << bufferLength) - 1);- return buffer >> bufferLength;- },- align: function MeshStreamReader_align() {- this.buffer = 0;- this.bufferLength = 0;- },- readFlag: function MeshStreamReader_readFlag() {- return this.readBits(this.context.bitsPerFlag);- },- readCoordinate: function MeshStreamReader_readCoordinate() {- var bitsPerCoordinate = this.context.bitsPerCoordinate;- var xi = this.readBits(bitsPerCoordinate);- var yi = this.readBits(bitsPerCoordinate);- var decode = this.context.decode;- var scale = bitsPerCoordinate < 32 ? 1 / ((1 << bitsPerCoordinate) - 1) :- 2.3283064365386963e-10; // 2 ^ -32- return [- xi * scale * (decode[1] - decode[0]) + decode[0],- yi * scale * (decode[3] - decode[2]) + decode[2]- ];- },- readComponents: function MeshStreamReader_readComponents() {- var numComps = this.context.numComps;- var bitsPerComponent = this.context.bitsPerComponent;- var scale = bitsPerComponent < 32 ? 1 / ((1 << bitsPerComponent) - 1) :- 2.3283064365386963e-10; // 2 ^ -32- var decode = this.context.decode;- var components = [];- for (var i = 0, j = 4; i < numComps; i++, j += 2) {- var ci = this.readBits(bitsPerComponent);- components.push(ci * scale * (decode[j + 1] - decode[j]) + decode[j]);- }- if (this.context.colorFn) {- components = this.context.colorFn(components);- }- return this.context.colorSpace.getRgb(components, 0);- }- };-- function decodeType4Shading(mesh, reader) {- var coords = mesh.coords;- var colors = mesh.colors;- var operators = [];- var ps = []; // not maintaining cs since that will match ps- var verticesLeft = 0; // assuming we have all data to start a new triangle- while (reader.hasData) {- var f = reader.readFlag();- var coord = reader.readCoordinate();- var color = reader.readComponents();- if (verticesLeft === 0) { // ignoring flags if we started a triangle- assert(0 <= f && f <= 2, 'Unknown type4 flag');- switch (f) {- case 0:- verticesLeft = 3;- break;- case 1:- ps.push(ps[ps.length - 2], ps[ps.length - 1]);- verticesLeft = 1;- break;- case 2:- ps.push(ps[ps.length - 3], ps[ps.length - 1]);- verticesLeft = 1;- break;- }- operators.push(f);+ checkData = cipher.encryptBlock(defaultPasswordBytes);+ for (j = 0, n = checkData.length; j < n; ++j) {+ if (userPassword[j] != checkData[j])+ return null;}- ps.push(coords.length);- coords.push(coord);- colors.push(color);- verticesLeft--;-- reader.align();}-- var psPacked = new Int32Array(ps);-- mesh.figures.push({- type: 'triangles',- coords: psPacked,- colors: psPacked- });- }-- function decodeType5Shading(mesh, reader, verticesPerRow) {- var coords = mesh.coords;- var colors = mesh.colors;- var operators = [];- var ps = []; // not maintaining cs since that will match ps- while (reader.hasData) {- var coord = reader.readCoordinate();- var color = reader.readComponents();- ps.push(coords.length);- coords.push(coord);- colors.push(color);- }-- var psPacked = new Int32Array(ps);-- mesh.figures.push({- type: 'lattice',- coords: psPacked,- colors: psPacked,- verticesPerRow: verticesPerRow- });+ return encryptionKey;}-- var MIN_SPLIT_PATCH_CHUNKS_AMOUNT = 3;- var MAX_SPLIT_PATCH_CHUNKS_AMOUNT = 20;-- var TRIANGLE_DENSITY = 20; // count of triangles per entire mesh bounds-- var getB = (function getBClosure() {- function buildB(count) {- var lut = [];- for (var i = 0; i <= count; i++) {- var t = i / count, t_ = 1 - t;- lut.push(new Float32Array([t_ * t_ * t_, 3 * t * t_ * t_,- 3 * t * t * t_, t * t * t]));- }- return lut;+ function decodeUserPassword(password, ownerPassword, revision, keyLength) {+ var hashData = new Uint8Array(32), i = 0, j, n;+ n = Math.min(32, password.length);+ for (; i < n; ++i)+ hashData[i] = password[i];+ j = 0;+ while (i < 32) {+ hashData[i++] = defaultPasswordBytes[j++];}- var cache = [];- return function getB(count) {- if (!cache[count]) {- cache[count] = buildB(count);- }- return cache[count];- };- })();-- function buildFigureFromPatch(mesh, index) {- var figure = mesh.figures[index];- assert(figure.type === 'patch', 'Unexpected patch mesh figure');-- var coords = mesh.coords, colors = mesh.colors;- var pi = figure.coords;- var ci = figure.colors;-- var figureMinX = Math.min(coords[pi[0]][0], coords[pi[3]][0],- coords[pi[12]][0], coords[pi[15]][0]);- var figureMinY = Math.min(coords[pi[0]][1], coords[pi[3]][1],- coords[pi[12]][1], coords[pi[15]][1]);- var figureMaxX = Math.max(coords[pi[0]][0], coords[pi[3]][0],- coords[pi[12]][0], coords[pi[15]][0]);- var figureMaxY = Math.max(coords[pi[0]][1], coords[pi[3]][1],- coords[pi[12]][1], coords[pi[15]][1]);- var splitXBy = Math.ceil((figureMaxX - figureMinX) * TRIANGLE_DENSITY /- (mesh.bounds[2] - mesh.bounds[0]));- splitXBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,- Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitXBy));- var splitYBy = Math.ceil((figureMaxY - figureMinY) * TRIANGLE_DENSITY /- (mesh.bounds[3] - mesh.bounds[1]));- splitYBy = Math.max(MIN_SPLIT_PATCH_CHUNKS_AMOUNT,- Math.min(MAX_SPLIT_PATCH_CHUNKS_AMOUNT, splitYBy));-- var verticesPerRow = splitXBy + 1;- var figureCoords = new Int32Array((splitYBy + 1) * verticesPerRow);- var figureColors = new Int32Array((splitYBy + 1) * verticesPerRow);- var k = 0;- var cl = new Uint8Array(3), cr = new Uint8Array(3);- var c0 = colors[ci[0]], c1 = colors[ci[1]],- c2 = colors[ci[2]], c3 = colors[ci[3]];- var bRow = getB(splitYBy), bCol = getB(splitXBy);- for (var row = 0; row <= splitYBy; row++) {- cl[0] = ((c0[0] * (splitYBy - row) + c2[0] * row) / splitYBy) | 0;- cl[1] = ((c0[1] * (splitYBy - row) + c2[1] * row) / splitYBy) | 0;- cl[2] = ((c0[2] * (splitYBy - row) + c2[2] * row) / splitYBy) | 0;-- cr[0] = ((c1[0] * (splitYBy - row) + c3[0] * row) / splitYBy) | 0;- cr[1] = ((c1[1] * (splitYBy - row) + c3[1] * row) / splitYBy) | 0;- cr[2] = ((c1[2] * (splitYBy - row) + c3[2] * row) / splitYBy) | 0;-- for (var col = 0; col <= splitXBy; col++, k++) {- if ((row === 0 || row === splitYBy) &&- (col === 0 || col === splitXBy)) {- continue;- }- var x = 0, y = 0;- var q = 0;- for (var i = 0; i <= 3; i++) {- for (var j = 0; j <= 3; j++, q++) {- var m = bRow[row][i] * bCol[col][j];- x += coords[pi[q]][0] * m;- y += coords[pi[q]][1] * m;- }- }- figureCoords[k] = coords.length;- coords.push([x, y]);- figureColors[k] = colors.length;- var newColor = new Uint8Array(3);- newColor[0] = ((cl[0] * (splitXBy - col) + cr[0] * col) / splitXBy) | 0;- newColor[1] = ((cl[1] * (splitXBy - col) + cr[1] * col) / splitXBy) | 0;- newColor[2] = ((cl[2] * (splitXBy - col) + cr[2] * col) / splitXBy) | 0;- colors.push(newColor);- }- }- figureCoords[0] = pi[0];- figureColors[0] = ci[0];- figureCoords[splitXBy] = pi[3];- figureColors[splitXBy] = ci[1];- figureCoords[verticesPerRow * splitYBy] = pi[12];- figureColors[verticesPerRow * splitYBy] = ci[2];- figureCoords[verticesPerRow * splitYBy + splitXBy] = pi[15];- figureColors[verticesPerRow * splitYBy + splitXBy] = ci[3];-- mesh.figures[index] = {- type: 'lattice',- coords: figureCoords,- colors: figureColors,- verticesPerRow: verticesPerRow- };- }-- function decodeType6Shading(mesh, reader) {- // A special case of Type 7. The p11, p12, p21, p22 automatically filled- var coords = mesh.coords;- var colors = mesh.colors;- var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33- var cs = new Int32Array(4); // c00, c30, c03, c33- while (reader.hasData) {- var f = reader.readFlag();- assert(0 <= f && f <= 3, 'Unknown type6 flag');- var i, ii;- var pi = coords.length;- for (i = 0, ii = (f !== 0 ? 8 : 12); i < ii; i++) {- coords.push(reader.readCoordinate());- }- var ci = colors.length;- for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {- colors.push(reader.readComponents());- }- var tmp1, tmp2, tmp3, tmp4;- switch (f) {- case 0:- ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;- ps[ 8] = pi + 2; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;- ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 8;- ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;- cs[2] = ci + 1; cs[3] = ci + 2;- cs[0] = ci; cs[1] = ci + 3;- break;- case 1:- tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];- ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;- ps[ 8] = pi + 6; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 1;- ps[ 4] = pi + 7; /* calculated below */ ps[ 7] = pi;- ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;- tmp1 = cs[2]; tmp2 = cs[3];- cs[2] = ci + 1; cs[3] = ci;- cs[0] = tmp1; cs[1] = tmp2;- break;- case 2:- ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;- ps[ 8] = ps[11]; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 4;- ps[ 4] = ps[7]; /* calculated below */ ps[ 7] = pi + 3;- ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;- cs[2] = cs[3]; cs[3] = ci + 1;- cs[0] = cs[1]; cs[1] = ci;- break;- case 3:- ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];- ps[ 8] = pi; /* values for 5, 6, 9, 10 are */ ps[11] = pi + 7;- ps[ 4] = pi + 1; /* calculated below */ ps[ 7] = pi + 6;- ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;- cs[2] = cs[0]; cs[3] = cs[1];- cs[0] = ci; cs[1] = ci + 1;- break;+ var hash = calculateMD5(hashData, 0, i);+ var keyLengthInBytes = keyLength >> 3;+ if (revision >= 3) {+ for (j = 0; j < 50; ++j) {+ hash = calculateMD5(hash, 0, hash.length);}- // set p11, p12, p21, p22- ps[5] = coords.length;- coords.push([- (-4 * coords[ps[0]][0] - coords[ps[15]][0] +- 6 * (coords[ps[4]][0] + coords[ps[1]][0]) -- 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +- 3 * (coords[ps[13]][0] + coords[ps[7]][0])) / 9,- (-4 * coords[ps[0]][1] - coords[ps[15]][1] +- 6 * (coords[ps[4]][1] + coords[ps[1]][1]) -- 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +- 3 * (coords[ps[13]][1] + coords[ps[7]][1])) / 9- ]);- ps[6] = coords.length;- coords.push([- (-4 * coords[ps[3]][0] - coords[ps[12]][0] +- 6 * (coords[ps[2]][0] + coords[ps[7]][0]) -- 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +- 3 * (coords[ps[4]][0] + coords[ps[14]][0])) / 9,- (-4 * coords[ps[3]][1] - coords[ps[12]][1] +- 6 * (coords[ps[2]][1] + coords[ps[7]][1]) -- 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +- 3 * (coords[ps[4]][1] + coords[ps[14]][1])) / 9- ]);- ps[9] = coords.length;- coords.push([- (-4 * coords[ps[12]][0] - coords[ps[3]][0] +- 6 * (coords[ps[8]][0] + coords[ps[13]][0]) -- 2 * (coords[ps[0]][0] + coords[ps[15]][0]) +- 3 * (coords[ps[11]][0] + coords[ps[1]][0])) / 9,- (-4 * coords[ps[12]][1] - coords[ps[3]][1] +- 6 * (coords[ps[8]][1] + coords[ps[13]][1]) -- 2 * (coords[ps[0]][1] + coords[ps[15]][1]) +- 3 * (coords[ps[11]][1] + coords[ps[1]][1])) / 9- ]);- ps[10] = coords.length;- coords.push([- (-4 * coords[ps[15]][0] - coords[ps[0]][0] +- 6 * (coords[ps[11]][0] + coords[ps[14]][0]) -- 2 * (coords[ps[12]][0] + coords[ps[3]][0]) +- 3 * (coords[ps[2]][0] + coords[ps[8]][0])) / 9,- (-4 * coords[ps[15]][1] - coords[ps[0]][1] +- 6 * (coords[ps[11]][1] + coords[ps[14]][1]) -- 2 * (coords[ps[12]][1] + coords[ps[3]][1]) +- 3 * (coords[ps[2]][1] + coords[ps[8]][1])) / 9- ]);- mesh.figures.push({- type: 'patch',- coords: new Int32Array(ps), // making copies of ps and cs- colors: new Int32Array(cs)- });}- }- function decodeType7Shading(mesh, reader) {- var coords = mesh.coords;- var colors = mesh.colors;- var ps = new Int32Array(16); // p00, p10, ..., p30, p01, ..., p33- var cs = new Int32Array(4); // c00, c30, c03, c33- while (reader.hasData) {- var f = reader.readFlag();- assert(0 <= f && f <= 3, 'Unknown type7 flag');- var i, ii;- var pi = coords.length;- for (i = 0, ii = (f !== 0 ? 12 : 16); i < ii; i++) {- coords.push(reader.readCoordinate());- }- var ci = colors.length;- for (i = 0, ii = (f !== 0 ? 2 : 4); i < ii; i++) {- colors.push(reader.readComponents());- }- var tmp1, tmp2, tmp3, tmp4;- switch (f) {- case 0:- ps[12] = pi + 3; ps[13] = pi + 4; ps[14] = pi + 5; ps[15] = pi + 6;- ps[ 8] = pi + 2; ps[ 9] = pi + 13; ps[10] = pi + 14; ps[11] = pi + 7;- ps[ 4] = pi + 1; ps[ 5] = pi + 12; ps[ 6] = pi + 15; ps[ 7] = pi + 8;- ps[ 0] = pi; ps[ 1] = pi + 11; ps[ 2] = pi + 10; ps[ 3] = pi + 9;- cs[2] = ci + 1; cs[3] = ci + 2;- cs[0] = ci; cs[1] = ci + 3;- break;- case 1:- tmp1 = ps[12]; tmp2 = ps[13]; tmp3 = ps[14]; tmp4 = ps[15];- ps[12] = pi + 5; ps[13] = pi + 4; ps[14] = pi + 3; ps[15] = pi + 2;- ps[ 8] = pi + 6; ps[ 9] = pi + 11; ps[10] = pi + 10; ps[11] = pi + 1;- ps[ 4] = pi + 7; ps[ 5] = pi + 8; ps[ 6] = pi + 9; ps[ 7] = pi;- ps[ 0] = tmp1; ps[ 1] = tmp2; ps[ 2] = tmp3; ps[ 3] = tmp4;- tmp1 = cs[2]; tmp2 = cs[3];- cs[2] = ci + 1; cs[3] = ci;- cs[0] = tmp1; cs[1] = tmp2;- break;- case 2:- ps[12] = ps[15]; ps[13] = pi + 7; ps[14] = pi + 6; ps[15] = pi + 5;- ps[ 8] = ps[11]; ps[ 9] = pi + 8; ps[10] = pi + 11; ps[11] = pi + 4;- ps[ 4] = ps[7]; ps[ 5] = pi + 9; ps[ 6] = pi + 10; ps[ 7] = pi + 3;- ps[ 0] = ps[3]; ps[ 1] = pi; ps[ 2] = pi + 1; ps[ 3] = pi + 2;- cs[2] = cs[3]; cs[3] = ci + 1;- cs[0] = cs[1]; cs[1] = ci;- break;- case 3:- ps[12] = ps[0]; ps[13] = ps[1]; ps[14] = ps[2]; ps[15] = ps[3];- ps[ 8] = pi; ps[ 9] = pi + 9; ps[10] = pi + 8; ps[11] = pi + 7;- ps[ 4] = pi + 1; ps[ 5] = pi + 10; ps[ 6] = pi + 11; ps[ 7] = pi + 6;- ps[ 0] = pi + 2; ps[ 1] = pi + 3; ps[ 2] = pi + 4; ps[ 3] = pi + 5;- cs[2] = cs[0]; cs[3] = cs[1];- cs[0] = ci; cs[1] = ci + 1;- break;+ var cipher, userPassword;+ if (revision >= 3) {+ userPassword = ownerPassword;+ var derivedKey = new Uint8Array(keyLengthInBytes), k;+ for (j = 19; j >= 0; j--) {+ for (k = 0; k < keyLengthInBytes; ++k)+ derivedKey[k] = hash[k] ^ j;+ cipher = new ARCFourCipher(derivedKey);+ userPassword = cipher.encryptBlock(userPassword);}- mesh.figures.push({- type: 'patch',- coords: new Int32Array(ps), // making copies of ps and cs- colors: new Int32Array(cs)- });+ } else {+ cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));+ userPassword = cipher.encryptBlock(ownerPassword);}+ return userPassword;}- function updateBounds(mesh) {- var minX = mesh.coords[0][0], minY = mesh.coords[0][1],- maxX = minX, maxY = minY;- for (var i = 1, ii = mesh.coords.length; i < ii; i++) {- var x = mesh.coords[i][0], y = mesh.coords[i][1];- minX = minX > x ? x : minX;- minY = minY > y ? y : minY;- maxX = maxX < x ? x : maxX;- maxY = maxY < y ? y : maxY;- }- mesh.bounds = [minX, minY, maxX, maxY];- }+ var identityName = new Name('Identity');- function packData(mesh) {- var i, ii, j, jj;+ function CipherTransformFactory(dict, fileId, password) {+ var filter = dict.get('Filter');+ if (!isName(filter) || filter.name != 'Standard')+ error('unknown encryption method');+ this.dict = dict;+ var algorithm = dict.get('V');+ if (!isInt(algorithm) ||+ (algorithm != 1 && algorithm != 2 && algorithm != 4))+ error('unsupported encryption algorithm');+ this.algorithm = algorithm;+ var keyLength = dict.get('Length') || 40;+ if (!isInt(keyLength) ||+ keyLength < 40 || (keyLength % 8) !== 0)+ error('invalid key length');+ // prepare keys+ var ownerPassword = stringToBytes(dict.get('O'));+ var userPassword = stringToBytes(dict.get('U'));+ var flags = dict.get('P');+ var revision = dict.get('R');+ var encryptMetadata = algorithm == 4 && // meaningful when V is 4+ dict.get('EncryptMetadata') !== false; // makes true as default value+ this.encryptMetadata = encryptMetadata;- var coords = mesh.coords;- var coordsPacked = new Float32Array(coords.length * 2);- for (i = 0, j = 0, ii = coords.length; i < ii; i++) {- var xy = coords[i];- coordsPacked[j++] = xy[0];- coordsPacked[j++] = xy[1];- }- mesh.coords = coordsPacked;+ var fileIdBytes = stringToBytes(fileId);+ var passwordBytes;+ if (password)+ passwordBytes = stringToBytes(password);- var colors = mesh.colors;- var colorsPacked = new Uint8Array(colors.length * 3);- for (i = 0, j = 0, ii = colors.length; i < ii; i++) {- var c = colors[i];- colorsPacked[j++] = c[0];- colorsPacked[j++] = c[1];- colorsPacked[j++] = c[2];+ var encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,+ ownerPassword, userPassword, flags,+ revision, keyLength, encryptMetadata);+ if (!encryptionKey && !password) {+ throw new PasswordException('No password given',+ PasswordResponses.NEED_PASSWORD);+ } else if (!encryptionKey && password) {+ // Attempting use the password as an owner password+ var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,+ revision, keyLength);+ encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,+ ownerPassword, userPassword, flags,+ revision, keyLength, encryptMetadata);}- mesh.colors = colorsPacked;- var figures = mesh.figures;- for (i = 0, ii = figures.length; i < ii; i++) {- var figure = figures[i], ps = figure.coords, cs = figure.colors;- for (j = 0, jj = ps.length; j < jj; j++) {- ps[j] *= 2;- cs[j] *= 3;- }+ if (!encryptionKey)+ throw new PasswordException('Incorrect Password',+ PasswordResponses.INCORRECT_PASSWORD);++ this.encryptionKey = encryptionKey;++ if (algorithm == 4) {+ this.cf = dict.get('CF');+ this.stmf = dict.get('StmF') || identityName;+ this.strf = dict.get('StrF') || identityName;+ this.eff = dict.get('EFF') || this.strf;}}- function Mesh(stream, matrix, xref, res) {- assert(isStream(stream), 'Mesh data is not a stream');- var dict = stream.dict;- this.matrix = matrix;- this.shadingType = dict.get('ShadingType');- this.type = 'Pattern';- this.bbox = dict.get('BBox');- var cs = dict.get('ColorSpace', 'CS');- cs = ColorSpace.parse(cs, xref, res);- this.cs = cs;- this.background = dict.has('Background') ?- cs.getRgb(dict.get('Background'), 0) : null;+ function buildObjectKey(num, gen, encryptionKey, isAes) {+ var key = new Uint8Array(encryptionKey.length + 9), i, n;+ for (i = 0, n = encryptionKey.length; i < n; ++i)+ key[i] = encryptionKey[i];+ key[i++] = num & 0xFF;+ key[i++] = (num >> 8) & 0xFF;+ key[i++] = (num >> 16) & 0xFF;+ key[i++] = gen & 0xFF;+ key[i++] = (gen >> 8) & 0xFF;+ if (isAes) {+ key[i++] = 0x73;+ key[i++] = 0x41;+ key[i++] = 0x6C;+ key[i++] = 0x54;+ }+ var hash = calculateMD5(key, 0, i);+ return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));+ }- var fnObj = dict.get('Function');- var fn;- if (!fnObj) {- fn = null;- } else if (isArray(fnObj)) {- var fnArray = [];- for (var j = 0, jj = fnObj.length; j < jj; j++) {- var obj = xref.fetchIfRef(fnObj[j]);- if (!isPDFFunction(obj)) {- error('Invalid function');- }- fnArray.push(PDFFunction.parse(xref, obj));- }- fn = function radialAxialColorFunction(arg) {- var out = [];- for (var i = 0, ii = fnArray.length; i < ii; i++) {- out.push(fnArray[i](arg)[0]);- }- return out;+ function buildCipherConstructor(cf, name, num, gen, key) {+ var cryptFilter = cf.get(name.name);+ var cfm;+ if (cryptFilter !== null && cryptFilter !== undefined)+ cfm = cryptFilter.get('CFM');+ if (!cfm || cfm.name == 'None') {+ return function cipherTransformFactoryBuildCipherConstructorNone() {+ return new NullCipher();};- } else {- if (!isPDFFunction(fnObj)) {- error('Invalid function');- }- fn = PDFFunction.parse(xref, fnObj);}-- this.coords = [];- this.colors = [];- this.figures = [];-- var decodeContext = {- bitsPerCoordinate: dict.get('BitsPerCoordinate'),- bitsPerComponent: dict.get('BitsPerComponent'),- bitsPerFlag: dict.get('BitsPerFlag'),- decode: dict.get('Decode'),- colorFn: fn,- colorSpace: cs,- numComps: fn ? 1 : cs.numComps- };- var reader = new MeshStreamReader(stream, decodeContext);-- var patchMesh = false;- switch (this.shadingType) {- case PatternType.FREE_FORM_MESH:- decodeType4Shading(this, reader);- break;- case PatternType.LATTICE_FORM_MESH:- var verticesPerRow = dict.get('VerticesPerRow') | 0;- assert(verticesPerRow >= 2, 'Invalid VerticesPerRow');- decodeType5Shading(this, reader, verticesPerRow);- break;- case PatternType.COONS_PATCH_MESH:- decodeType6Shading(this, reader);- patchMesh = true;- break;- case PatternType.TENSOR_PATCH_MESH:- decodeType7Shading(this, reader);- patchMesh = true;- break;- default:- error('Unsupported mesh type.');- break;+ if ('V2' == cfm.name) {+ return function cipherTransformFactoryBuildCipherConstructorV2() {+ return new ARCFourCipher(+ buildObjectKey(num, gen, key, false));+ };}-- if (patchMesh) {- // dirty bounds calculation for determining, how dense shall be triangles- updateBounds(this);- for (var i = 0, ii = this.figures.length; i < ii; i++) {- buildFigureFromPatch(this, i);- }+ if ('AESV2' == cfm.name) {+ return function cipherTransformFactoryBuildCipherConstructorAESV2() {+ return new AES128Cipher(+ buildObjectKey(num, gen, key, true));+ };}- // calculate bounds- updateBounds(this);-- packData(this);+ error('Unknown crypto method');}- Mesh.prototype = {- getIR: function Mesh_getIR() {- return ['Mesh', this.shadingType, this.coords, this.colors, this.figures,- this.bounds, this.matrix, this.bbox, this.background];+ CipherTransformFactory.prototype = {+ createCipherTransform:+ function CipherTransformFactory_createCipherTransform(num, gen) {+ if (this.algorithm == 4) {+ return new CipherTransform(+ buildCipherConstructor(this.cf, this.stmf,+ num, gen, this.encryptionKey),+ buildCipherConstructor(this.cf, this.strf,+ num, gen, this.encryptionKey));+ }+ // algorithms 1 and 2+ var key = buildObjectKey(num, gen, this.encryptionKey, false);+ var cipherConstructor = function buildCipherCipherConstructor() {+ return new ARCFourCipher(key);+ };+ return new CipherTransform(cipherConstructor, cipherConstructor);}};- return Mesh;-})();--Shadings.Dummy = (function DummyClosure() {- function Dummy() {- this.type = 'Pattern';- }-- Dummy.prototype = {- getIR: function Dummy_getIR() {- return ['Dummy'];- }- };- return Dummy;+ return CipherTransformFactory;})();-function getTilingPatternIR(operatorList, dict, args) {- var matrix = dict.get('Matrix');- var bbox = dict.get('BBox');- var xstep = dict.get('XStep');- var ystep = dict.get('YStep');- var paintType = dict.get('PaintType');- var tilingType = dict.get('TilingType');-- return [- 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,- paintType, tilingType- ];-}var PartialEvaluator = (function PartialEvaluatorClosure() {function PartialEvaluator(pdfManager, xref, handler, pageIndex,- uniquePrefix, idCounters, fontCache) {+ uniquePrefix, idCounters) {+ this.state = new EvalState();+ this.stateStack = [];+this.pdfManager = pdfManager;this.xref = xref;this.handler = handler;this.pageIndex = pageIndex;this.uniquePrefix = uniquePrefix;this.idCounters = idCounters;- this.fontCache = fontCache;+ this.fontCache = new RefSetCache();}+ // Specifies properties for each command+ //+ // If variableArgs === true: [0, `numArgs`] expected+ // If variableArgs === false: exactly `numArgs` expected+ var OP_MAP = {+ // Graphic state+ w: { fnName: 'setLineWidth', numArgs: 1, variableArgs: false },+ J: { fnName: 'setLineCap', numArgs: 1, variableArgs: false },+ j: { fnName: 'setLineJoin', numArgs: 1, variableArgs: false },+ M: { fnName: 'setMiterLimit', numArgs: 1, variableArgs: false },+ d: { fnName: 'setDash', numArgs: 2, variableArgs: false },+ ri: { fnName: 'setRenderingIntent', numArgs: 1, variableArgs: false },+ i: { fnName: 'setFlatness', numArgs: 1, variableArgs: false },+ gs: { fnName: 'setGState', numArgs: 1, variableArgs: false },+ q: { fnName: 'save', numArgs: 0, variableArgs: false },+ Q: { fnName: 'restore', numArgs: 0, variableArgs: false },+ cm: { fnName: 'transform', numArgs: 6, variableArgs: false },++ // Path+ m: { fnName: 'moveTo', numArgs: 2, variableArgs: false },+ l: { fnName: 'lineTo', numArgs: 2, variableArgs: false },+ c: { fnName: 'curveTo', numArgs: 6, variableArgs: false },+ v: { fnName: 'curveTo2', numArgs: 4, variableArgs: false },+ y: { fnName: 'curveTo3', numArgs: 4, variableArgs: false },+ h: { fnName: 'closePath', numArgs: 0, variableArgs: false },+ re: { fnName: 'rectangle', numArgs: 4, variableArgs: false },+ S: { fnName: 'stroke', numArgs: 0, variableArgs: false },+ s: { fnName: 'closeStroke', numArgs: 0, variableArgs: false },+ f: { fnName: 'fill', numArgs: 0, variableArgs: false },+ F: { fnName: 'fill', numArgs: 0, variableArgs: false },+ 'f*': { fnName: 'eoFill', numArgs: 0, variableArgs: false },+ B: { fnName: 'fillStroke', numArgs: 0, variableArgs: false },+ 'B*': { fnName: 'eoFillStroke', numArgs: 0, variableArgs: false },+ b: { fnName: 'closeFillStroke', numArgs: 0, variableArgs: false },+ 'b*': { fnName: 'closeEOFillStroke', numArgs: 0, variableArgs: false },+ n: { fnName: 'endPath', numArgs: 0, variableArgs: false },++ // Clipping+ W: { fnName: 'clip', numArgs: 0, variableArgs: false },+ 'W*': { fnName: 'eoClip', numArgs: 0, variableArgs: false },++ // Text+ BT: { fnName: 'beginText', numArgs: 0, variableArgs: false },+ ET: { fnName: 'endText', numArgs: 0, variableArgs: false },+ Tc: { fnName: 'setCharSpacing', numArgs: 1, variableArgs: false },+ Tw: { fnName: 'setWordSpacing', numArgs: 1, variableArgs: false },+ Tz: { fnName: 'setHScale', numArgs: 1, variableArgs: false },+ TL: { fnName: 'setLeading', numArgs: 1, variableArgs: false },+ Tf: { fnName: 'setFont', numArgs: 2, variableArgs: false },+ Tr: { fnName: 'setTextRenderingMode', numArgs: 1, variableArgs: false },+ Ts: { fnName: 'setTextRise', numArgs: 1, variableArgs: false },+ Td: { fnName: 'moveText', numArgs: 2, variableArgs: false },+ TD: { fnName: 'setLeadingMoveText', numArgs: 2, variableArgs: false },+ Tm: { fnName: 'setTextMatrix', numArgs: 6, variableArgs: false },+ 'T*': { fnName: 'nextLine', numArgs: 0, variableArgs: false },+ Tj: { fnName: 'showText', numArgs: 1, variableArgs: false },+ TJ: { fnName: 'showSpacedText', numArgs: 1, variableArgs: false },+ '\'': { fnName: 'nextLineShowText', numArgs: 1, variableArgs: false },+ '"': { fnName: 'nextLineSetSpacingShowText', numArgs: 3,+ variableArgs: false },++ // Type3 fonts+ d0: { fnName: 'setCharWidth', numArgs: 2, variableArgs: false },+ d1: { fnName: 'setCharWidthAndBounds', numArgs: 6, variableArgs: false },++ // Color+ CS: { fnName: 'setStrokeColorSpace', numArgs: 1, variableArgs: false },+ cs: { fnName: 'setFillColorSpace', numArgs: 1, variableArgs: false },+ SC: { fnName: 'setStrokeColor', numArgs: 4, variableArgs: true },+ SCN: { fnName: 'setStrokeColorN', numArgs: 33, variableArgs: true },+ sc: { fnName: 'setFillColor', numArgs: 4, variableArgs: true },+ scn: { fnName: 'setFillColorN', numArgs: 33, variableArgs: true },+ G: { fnName: 'setStrokeGray', numArgs: 1, variableArgs: false },+ g: { fnName: 'setFillGray', numArgs: 1, variableArgs: false },+ RG: { fnName: 'setStrokeRGBColor', numArgs: 3, variableArgs: false },+ rg: { fnName: 'setFillRGBColor', numArgs: 3, variableArgs: false },+ K: { fnName: 'setStrokeCMYKColor', numArgs: 4, variableArgs: false },+ k: { fnName: 'setFillCMYKColor', numArgs: 4, variableArgs: false },++ // Shading+ sh: { fnName: 'shadingFill', numArgs: 1, variableArgs: false },++ // Images+ BI: { fnName: 'beginInlineImage', numArgs: 0, variableArgs: false },+ ID: { fnName: 'beginImageData', numArgs: 0, variableArgs: false },+ EI: { fnName: 'endInlineImage', numArgs: 1, variableArgs: false },++ // XObjects+ Do: { fnName: 'paintXObject', numArgs: 1, variableArgs: false },+ MP: { fnName: 'markPoint', numArgs: 1, variableArgs: false },+ DP: { fnName: 'markPointProps', numArgs: 2, variableArgs: false },+ BMC: { fnName: 'beginMarkedContent', numArgs: 1, variableArgs: false },+ BDC: { fnName: 'beginMarkedContentProps', numArgs: 2, variableArgs: false },+ EMC: { fnName: 'endMarkedContent', numArgs: 0, variableArgs: false },++ // Compatibility+ BX: { fnName: 'beginCompat', numArgs: 0, variableArgs: false },+ EX: { fnName: 'endCompat', numArgs: 0, variableArgs: false },++ // (reserved partial commands for the lexer)+ BM: null,+ BD: null,+ 'true': null,+ fa: null,+ fal: null,+ fals: null,+ 'false': null,+ nu: null,+ nul: null,+ 'null': null+ };+var TILING_PATTERN = 1, SHADING_PATTERN = 2;- PartialEvaluator.prototype = {- hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {- if (!isDict(resources)) {- return false;- }+ function createOperatorList(fnArray, argsArray, dependencies) {+ return {+ queue: {+ fnArray: fnArray || [],+ argsArray: argsArray || []+ },+ dependencies: dependencies || {}+ };+ }- var processed = Object.create(null);- if (resources.objId) {- processed[resources.objId] = true;- }-- var nodes = [resources];- while (nodes.length) {- var key;- var node = nodes.shift();- // First check the current resources for blend modes.- var graphicStates = node.get('ExtGState');- if (isDict(graphicStates)) {- graphicStates = graphicStates.getAll();- for (key in graphicStates) {- var graphicState = graphicStates[key];- var bm = graphicState['BM'];- if (isName(bm) && bm.name !== 'Normal') {- return true;- }- }- }- // Descend into the XObjects to look for more resources and blend modes.- var xObjects = node.get('XObject');- if (!isDict(xObjects)) {- continue;- }- xObjects = xObjects.getAll();- for (key in xObjects) {- var xObject = xObjects[key];- if (!isStream(xObject)) {- continue;- }- var xResources = xObject.dict.get('Resources');- // Checking objId to detect an infinite loop.- if (isDict(xResources) &&- (!xResources.objId || !processed[xResources.objId])) {- nodes.push(xResources);- if (xResources.objId) {- processed[xResources.objId] = true;- }- }- }- }- return false;- },+ PartialEvaluator.prototype = {buildFormXObject: function PartialEvaluator_buildFormXObject(resources,- xobj, smask,- operatorList,- initialState) {+ xobj, smask) {+ var self = this;+ var promise = new Promise();+ var fnArray = [];+ var argsArray = [];+var matrix = xobj.dict.get('Matrix');var bbox = xobj.dict.get('BBox');var group = xobj.dict.get('Group');@@ -15371,55 +16431,69 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var groupOptions = {matrix: matrix,bbox: bbox,- smask: smask,+ smask: !!smask,isolated: false,knockout: false};var groupSubtype = group.get('S');if (isName(groupSubtype) && groupSubtype.name === 'Transparency') {- groupOptions.isolated = (group.get('I') || false);- groupOptions.knockout = (group.get('K') || false);- var colorSpace = group.get('CS');- groupOptions.colorSpace = (colorSpace ?- ColorSpace.parseToIR(colorSpace, this.xref, resources) : null);+ groupOptions.isolated = group.get('I') || false;+ groupOptions.knockout = group.get('K') || false;+ // There is also a group colorspace, but since we put everything in+ // RGB I'm not sure we need it.}- operatorList.addOp(OPS.beginGroup, [groupOptions]);+ fnArray.push('beginGroup');+ argsArray.push([groupOptions]);}- operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);+ fnArray.push('paintFormXObjectBegin');+ argsArray.push([matrix, bbox]);- this.getOperatorList(xobj, (xobj.dict.get('Resources') || resources),- operatorList, initialState);- operatorList.addOp(OPS.paintFormXObjectEnd, []);+ // Pass in the current `queue` object. That means the `fnArray`+ // and the `argsArray` in this scope is reused and new commands+ // are added to them.+ var opListPromise = this.getOperatorList(xobj,+ xobj.dict.get('Resources') || resources);+ opListPromise.then(function(data) {+ var queue = data.queue;+ var dependencies = data.dependencies;+ Util.prependToArray(queue.fnArray, fnArray);+ Util.prependToArray(queue.argsArray, argsArray);+ self.insertDependencies(queue, dependencies);- if (group) {- operatorList.addOp(OPS.endGroup, [groupOptions]);- }+ queue.fnArray.push('paintFormXObjectEnd');+ queue.argsArray.push([]);++ if (group) {+ queue.fnArray.push('endGroup');+ queue.argsArray.push([groupOptions]);+ }++ promise.resolve({+ queue: queue,+ dependencies: dependencies+ });+ });++ return promise;},- buildPaintImageXObject:- function PartialEvaluator_buildPaintImageXObject(resources, image,- inline, operatorList,- cacheKey, cache) {+ buildPaintImageXObject: function PartialEvaluator_buildPaintImageXObject(+ resources, image, inline) {var self = this;var dict = image.dict;var w = dict.get('Width', 'W');var h = dict.get('Height', 'H');- if (!(w && isNum(w)) || !(h && isNum(h))) {- warn('Image dimensions are missing, or not numbers.');- return;- }- if (PDFJS.maxImageSize !== -1 && w * h > PDFJS.maxImageSize) {- warn('Image exceeded maximum allowed size and was removed.');- return;- }+ var dependencies = {};+ var retData = {+ dependencies: dependencies+ };- var imageMask = (dict.get('ImageMask', 'IM') || false);- var imgData, args;+ var imageMask = dict.get('ImageMask', 'IM') || false;if (imageMask) {- // This depends on a tmpCanvas being filled with the+ // This depends on a tmpCanvas beeing filled with the// current fillStyle, such that processing the pixel// data can't be done here. Instead of creating a// complete PDFImage, only read the information needed@@ -15430,103 +16504,83 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var bitStrideLength = (width + 7) >> 3;var imgArray = image.getBytes(bitStrideLength * height);var decode = dict.get('Decode', 'D');- var canTransfer = image instanceof DecodeStream;- var inverseDecode = (!!decode && decode[0] > 0);-- imgData = PDFImage.createMask(imgArray, width, height,- canTransfer, inverseDecode);- imgData.cached = true;- args = [imgData];- operatorList.addOp(OPS.paintImageMaskXObject, args);- if (cacheKey) {- cache.key = cacheKey;- cache.fn = OPS.paintImageMaskXObject;- cache.args = args;- }- return;+ var inverseDecode = !!decode && decode[0] > 0;++ retData.fn = 'paintImageMaskXObject';+ retData.args = [PDFImage.createMask(imgArray, width, height,+ inverseDecode)];+ return retData;}- var softMask = (dict.get('SMask', 'SM') || false);- var mask = (dict.get('Mask') || false);+ var softMask = dict.get('SMask', 'SM') || false;+ var mask = dict.get('Mask') || false;var SMALL_IMAGE_DIMENSIONS = 200;// Inlining small images into the queue as RGB data- if (inline && !softMask && !mask && !(image instanceof JpegStream) &&+ if (inline && !softMask && !mask &&+ !(image instanceof JpegStream) &&(w + h) < SMALL_IMAGE_DIMENSIONS) {var imageObj = new PDFImage(this.xref, resources, image,inline, null, null);- // We force the use of RGBA_32BPP images here, because we can't handle- // any other kind.- imgData = imageObj.createImageData(/* forceRGBA = */ true);- operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);- return;+ var imgData = imageObj.getImageData();+ retData.fn = 'paintInlineImageXObject';+ retData.args = [imgData];+ return retData;}// If there is no imageMask, create the PDFImage and a lot// of image processing can be done here.- var uniquePrefix = (this.uniquePrefix || '');+ var uniquePrefix = this.uniquePrefix || '';var objId = 'img_' + uniquePrefix + (++this.idCounters.obj);- operatorList.addDependency(objId);- args = [objId, w, h];+ dependencies[objId] = true;+ retData.args = [objId, w, h];if (!softMask && !mask && image instanceof JpegStream &&image.isNativelySupported(this.xref, resources)) {// These JPEGs don't need any more processing so we can just send it.- operatorList.addOp(OPS.paintJpegXObject, args);- this.handler.send('obj',- [objId, this.pageIndex, 'JpegStream', image.getIR()]);- return;+ retData.fn = 'paintJpegXObject';+ this.handler.send(+ 'obj', [objId, this.pageIndex, 'JpegStream', image.getIR()]);+ return retData;}- PDFImage.buildImage(self.handler, self.xref, resources, image, inline).- then(function(imageObj) {- var imgData = imageObj.createImageData(/* forceRGBA = */ false);- self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData],- null, [imgData.data.buffer]);- }).then(null, function (reason) {- warn('Unable to decode image: ' + reason);- self.handler.send('obj', [objId, self.pageIndex, 'Image', null]);- });+ retData.fn = 'paintImageXObject';- operatorList.addOp(OPS.paintImageXObject, args);- if (cacheKey) {- cache.key = cacheKey;- cache.fn = OPS.paintImageXObject;- cache.args = args;- }- },+ PDFImage.buildImage(function(imageObj) {+ var imgData = imageObj.getImageData();+ self.handler.send('obj', [objId, self.pageIndex, 'Image', imgData]);+ }, self.handler, self.xref, resources, image, inline);- handleSMask: function PartialEvaluator_handleSmask(smask, resources,- operatorList,- stateManager) {- var smaskContent = smask.get('G');- var smaskOptions = {- subtype: smask.get('S').name,- backdrop: smask.get('BC')- };- this.buildFormXObject(resources, smaskContent, smaskOptions,- operatorList, stateManager.state.clone());+ return retData;},- handleTilingType:- function PartialEvaluator_handleTilingType(fn, args, resources,- pattern, patternDict,- operatorList) {+ handleTilingType: function PartialEvaluator_handleTilingType(+ fn, args, resources, pattern, patternDict) {+ var self = this;// Create an IR of the pattern code.- var tilingOpList = this.getOperatorList(pattern,- (patternDict.get('Resources') || resources));- // Add the dependencies to the parent operator list so they are resolved- // before sub operator list is executed synchronously.- operatorList.addDependencies(tilingOpList.dependencies);- operatorList.addOp(fn, getTilingPatternIR({- fnArray: tilingOpList.fnArray,- argsArray: tilingOpList.argsArray- }, patternDict, args));- },-- handleSetFont:- function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,- operatorList, state) {+ var promise = new Promise();+ var opListPromise = this.getOperatorList(pattern,+ patternDict.get('Resources') || resources);+ opListPromise.then(function(data) {+ var opListData = createOperatorList([], [], data.dependencies);+ var queue = opListData.queue;++ // Add the dependencies that are required to execute the+ // operatorList.+ self.insertDependencies(queue, data.dependencies);+ queue.fnArray.push(fn);+ queue.argsArray.push(+ TilingPattern.getIR(data.queue, patternDict, args));+ promise.resolve(opListData);+ });++ return promise;+ },++ handleSetFont: function PartialEvaluator_handleSetFont(+ resources, fontArgs, font) {++ var promise = new Promise();// TODO(mack): Not needed?var fontName;if (fontArgs) {@@ -15534,54 +16588,69 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {fontName = fontArgs[0].name;}var self = this;- var font = this.loadFont(fontName, fontRef, this.xref, resources,- operatorList);- state.font = font;- var loadedName = font.loadedName;- if (!font.sent) {- var fontData = font.translated.exportData();-- self.handler.send('commonobj', [- loadedName,- 'Font',- fontData- ]);- font.sent = true;- }-- return loadedName;- },-- handleText: function PartialEvaluator_handleText(chars, state) {- var font = state.font.translated;- var glyphs = font.charsToGlyphs(chars);- var isAddToPathSet = !!(state.textRenderingMode &- TextRenderingMode.ADD_TO_PATH_FLAG);- if (font.data && (isAddToPathSet || PDFJS.disableFontFace)) {- for (var i = 0; i < glyphs.length; i++) {- if (glyphs[i] === null) {- continue;- }- var fontChar = glyphs[i].fontChar;- if (!font.renderer.hasBuiltPath(fontChar)) {- var path = font.renderer.getPathJs(fontChar);- this.handler.send('commonobj', [- font.loadedName + '_path_' + fontChar,- 'FontPath',- path- ]);- }- }- }+ var fontPromise = this.loadFont(fontName, font, this.xref, resources);+ fontPromise.then(function(data) {+ var font = data.font;+ var loadedName = font.loadedName;+ if (!font.sent) {+ var fontData = font.translated.exportData();++ self.handler.send('commonobj', [+ loadedName,+ 'Font',+ fontData+ ]);+ font.sent = true;+ }++ // Ensure the font is ready before the font is set+ // and later on used for drawing.+ // OPTIMIZE: This should get insert to the operatorList only once per+ // page.+ var fnArray = [];+ var argsArray = [];+ var queue = {+ fnArray: fnArray,+ argsArray: argsArray+ };+ var dependencies = data.dependencies;+ dependencies[loadedName] = true;+ self.insertDependencies(queue, dependencies);+ if (fontArgs) {+ fontArgs[0] = loadedName;+ fnArray.push('setFont');+ argsArray.push(fontArgs);+ }+ promise.resolve({+ loadedName: loadedName,+ queue: queue,+ dependencies: dependencies+ });+ });+ return promise;+ },++ insertDependencies: function PartialEvaluator_insertDependencies(+ queue, dependencies) {- return glyphs;+ var fnArray = queue.fnArray;+ var argsArray = queue.argsArray;+ var depList = Object.keys(dependencies);+ if (depList.length) {+ fnArray.push('dependency');+ argsArray.push(depList);+ }},- setGState: function PartialEvaluator_setGState(resources, gState,- operatorList, xref,- stateManager) {+ setGState: function PartialEvaluator_setGState(resources, gState) {var self = this;+ var opListData = createOperatorList();+ var queue = opListData.queue;+ var fnArray = queue.fnArray;+ var argsArray = queue.argsArray;+ var dependencies = opListData.dependencies;+// TODO(mack): This should be rewritten so that this function returns// what should be added to the queue during each iterationfunction setGStateForKey(gStateObj, key, value) {@@ -15600,28 +16669,27 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {gStateObj.push([key, value]);break;case 'Font':- var loadedName = self.handleSetFont(resources, null, value[0],- operatorList,- stateManager.state);- operatorList.addDependency(loadedName);- gStateObj.push([key, [loadedName, value[1]]]);+ var promise = new Promise();+ self.handleSetFont(resources, null, value[0]).then(function(data) {+ var gState = ['Font', data.loadedName, value[1]];+ promise.resolve({+ gState: gState,+ queue: data.queue,+ dependencies: data.dependencies+ });+ });+ gStateObj.push(['promise', promise]);break;case 'BM':+ if (!isName(value) || value.name !== 'Normal') {+ queue.transparency = true;+ }gStateObj.push([key, value]);break;case 'SMask':- if (isName(value) && value.name === 'None') {- gStateObj.push([key, false]);- break;- }- var dict = xref.fetchIfRef(value);- if (isDict(dict)) {- self.handleSMask(dict, resources, operatorList, stateManager);- gStateObj.push([key, true]);- } else {- warn('Unsupported SMask type');- }-+ // We support the default so don't trigger the TODO.+ if (!isName(value) || value.name != 'None')+ TODO('graphic state operator ' + key);break;// Only generate info log messages for the following since// they are unlikey to have a big impact on the rendering.@@ -15656,18 +16724,47 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {setGStateForKey(gStateObj, key, value);}- operatorList.addOp(OPS.setGState, [gStateObj]);+ var promises = [];+ var indices = [];+ for (var i = 0, n = gStateObj.length; i < n; ++i) {+ var value = gStateObj[i];+ if (value[0] === 'promise') {+ promises.push(value[1]);+ indices.push(i);+ }+ }++ var promise = new Promise();+ Promise.all(promises).then(function(datas) {+ for (var i = 0, n = datas.length; i < n; ++i) {+ var data = datas[i];+ var index = indices[i];+ gStateObj[index] = data.gState;+ var subQueue = data.queue;+ Util.concatenateToArray(fnArray, subQueue.fnArray);+ Util.concatenateToArray(argsArray, subQueue.argsArray);+ queue.transparency = subQueue.transparency || queue.transparency;+ Util.extendObj(dependencies, data.dependencies);+ }+ fnArray.push('setGState');+ argsArray.push([gStateObj]);+ promise.resolve(opListData);+ });++ return promise;},loadFont: function PartialEvaluator_loadFont(fontName, font, xref,- resources,- parentOperatorList) {-- function errorFont() {- return {- translated: new ErrorFont('Font ' + fontName + ' is not available'),- loadedName: 'g_font_error'- };+ resources) {+ function errorFont(promise) {+ promise.resolve({+ font: {+ translated: new ErrorFont('Font ' + fontName + ' is not available'),+ loadedName: 'g_font_error'+ },+ dependencies: {}+ });+ return promise;}var fontRef;@@ -15680,68 +16777,30 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {fontRef = fontRes.getRaw(fontName);} else {warn('fontRes not available');- return errorFont();+ return errorFont(new Promise());}}if (this.fontCache.has(fontRef)) {return this.fontCache.get(fontRef);}+ var promise = new Promise();+ this.fontCache.put(fontRef, promise);+font = xref.fetchIfRef(fontRef);if (!isDict(font)) {- return errorFont();- }-- var preEvaluatedFont = this.preEvaluateFont(font, xref);- var descriptor = preEvaluatedFont.descriptor;- var fontID = fontRef.num + '_' + fontRef.gen;- if (isDict(descriptor)) {- if (!descriptor.fontAliases) {- descriptor.fontAliases = Object.create(null);- }-- var fontAliases = descriptor.fontAliases;- var hash = preEvaluatedFont.hash;- if (fontAliases[hash]) {- var aliasFontRef = fontAliases[hash].aliasRef;- if (aliasFontRef && this.fontCache.has(aliasFontRef)) {- this.fontCache.putAlias(fontRef, aliasFontRef);- var cachedFont = this.fontCache.get(fontRef);- return cachedFont;- }- }-- if (!fontAliases[hash]) {- fontAliases[hash] = {- fontID: Font.getFontID()- };- }-- fontAliases[hash].aliasRef = fontRef;- fontID = fontAliases[hash].fontID;- }-- // Workaround for bad PDF generators that don't reference fonts- // properly, i.e. by not using an object identifier.- // Check if the fontRef is a Dict (as opposed to a standard object),- // in which case we don't cache the font and instead reference it by- // fontName in font.loadedName below.- var fontRefIsDict = isDict(fontRef);- if (!fontRefIsDict) {- this.fontCache.put(fontRef, font);+ return errorFont(promise);}- // Keep track of each font we translated so the caller can- // load them asynchronously before calling display on a page.- font.loadedName = 'g_font_' + (fontRefIsDict ?- fontName.replace(/\W/g, '') : fontID);+ // keep track of each font we translated so the caller can+ // load them asynchronously before calling display on a page+ font.loadedName = 'g_font_' + fontRef.num + '_' + fontRef.gen;if (!font.translated) {var translated;try {- translated = this.translateFont(preEvaluatedFont, xref);+ translated = this.translateFont(font, xref);} catch (e) {- UnsupportedManager.notify(UNSUPPORTED_FEATURES.font);translated = new ErrorFont(e instanceof Error ? e.message : e);}font.translated = translated;@@ -15749,535 +16808,459 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {if (font.translated.loadCharProcs) {var charProcs = font.get('CharProcs').getAll();- var fontResources = (font.get('Resources') || resources);+ var fontResources = font.get('Resources') || resources;+ var opListPromises = [];var charProcKeys = Object.keys(charProcs);- var charProcOperatorList = {};for (var i = 0, n = charProcKeys.length; i < n; ++i) {var key = charProcKeys[i];var glyphStream = charProcs[key];- var operatorList = this.getOperatorList(glyphStream, fontResources);- charProcOperatorList[key] = operatorList.getIR();- if (!parentOperatorList) {- continue;- }- // Add the dependencies to the parent operator list so they are- // resolved before sub operator list is executed synchronously.- parentOperatorList.addDependencies(charProcOperatorList.dependencies);- }- font.translated.charProcOperatorList = charProcOperatorList;+ opListPromises.push(+ this.getOperatorList(glyphStream, fontResources));+ }+ Promise.all(opListPromises).then(function(datas) {+ var charProcOperatorList = {};+ var dependencies = {};+ for (var i = 0, n = charProcKeys.length; i < n; ++i) {+ var key = charProcKeys[i];+ var data = datas[i];+ charProcOperatorList[key] = data.queue;+ Util.extendObj(dependencies, data.dependencies);+ }+ font.translated.charProcOperatorList = charProcOperatorList;+ font.loaded = true;+ promise.resolve({+ font: font,+ dependencies: dependencies+ });+ }.bind(this));+ } else {+ font.loaded = true;+ promise.resolve({+ font: font,+ dependencies: {}+ });}- font.loaded = true;- return font;+ return promise;},getOperatorList: function PartialEvaluator_getOperatorList(stream,- resources,- operatorList,- initialState) {+ resources) {var self = this;var xref = this.xref;var handler = this.handler;- var imageCache = {};-- operatorList = (operatorList || new OperatorList());-- resources = (resources || Dict.empty);- var xobjs = (resources.get('XObject') || Dict.empty);- var patterns = (resources.get('Pattern') || Dict.empty);- var stateManager = new StateManager(initialState || new EvalState());- var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);-- var promise = new LegacyPromise();- var operation, i, ii;- while ((operation = preprocessor.read())) {- var args = operation.args;- var fn = operation.fn;- var shading;-- switch (fn) {- case OPS.setStrokeColorN:- case OPS.setFillColorN:- if (args[args.length - 1].code) {- break;++ var fnArray = [];+ var argsArray = [];+ var queue = {+ transparency: false,+ fnArray: fnArray,+ argsArray: argsArray+ };+ var dependencies = {};++ resources = resources || new Dict();+ var xobjs = resources.get('XObject') || new Dict();+ var patterns = resources.get('Pattern') || new Dict();+ // TODO(mduan): pass array of knownCommands rather than OP_MAP+ // dictionary+ var parser = new Parser(new Lexer(stream, OP_MAP), false, xref);++ var promise = new Promise();+ var args = [];+ while (true) {++ var obj = parser.getObj();++ if (isEOF(obj)) {+ break;+ }++ if (isCmd(obj)) {+ var cmd = obj.cmd;++ // Check that the command is valid+ var opSpec = OP_MAP[cmd];+ if (!opSpec) {+ warn('Unknown command "' + cmd + '"');+ continue;+ }++ var fn = opSpec.fnName;++ // Validate the number of arguments for the command+ if (opSpec.variableArgs) {+ if (args.length > opSpec.numArgs) {+ info('Command ' + fn + ': expected [0,' + opSpec.numArgs ++ '] args, but received ' + args.length + ' args');+ }+ } else {+ if (args.length < opSpec.numArgs) {+ // If we receive too few args, it's not possible to possible+ // to execute the command, so skip the command+ info('Command ' + fn + ': because expected ' ++ opSpec.numArgs + ' args, but received ' + args.length ++ ' args; skipping');+ args = [];+ continue;+ } else if (args.length > opSpec.numArgs) {+ info('Command ' + fn + ': expected ' + opSpec.numArgs ++ ' args, but received ' + args.length + ' args');}+ }++ // TODO figure out how to type-check vararg functions++ if ((cmd == 'SCN' || cmd == 'scn') &&+ !args[args.length - 1].code) {// compile tiling patternsvar patternName = args[args.length - 1];// SCN/scn applies patterns along with normal colorsvar pattern;if (isName(patternName) &&(pattern = patterns.get(patternName.name))) {- var dict = (isStream(pattern) ? pattern.dict : pattern);++ var dict = isStream(pattern) ? pattern.dict : pattern;var typeNum = dict.get('PatternType');if (typeNum == TILING_PATTERN) {- self.handleTilingType(fn, args, resources, pattern, dict,- operatorList);- args = [];- continue;+ var patternPromise = self.handleTilingType(+ fn, args, resources, pattern, dict);+ fn = 'promise';+ args = [patternPromise];} else if (typeNum == SHADING_PATTERN) {- shading = dict.get('Shading');+ var shading = dict.get('Shading');var matrix = dict.get('Matrix');- pattern = Pattern.parseShading(shading, matrix, xref,- resources);+ var pattern = Pattern.parseShading(shading, matrix, xref,+ resources);args = pattern.getIR();} else {error('Unkown PatternType ' + typeNum);}}- break;- case OPS.paintXObject:- if (args[0].code) {- break;- }+ } else if (cmd == 'Do' && !args[0].code) {// eagerly compile XForm objectsvar name = args[0].name;- if (imageCache.key === name) {- operatorList.addOp(imageCache.fn, imageCache.args);- args = [];- continue;- }-var xobj = xobjs.get(name);if (xobj) {- assert(isStream(xobj), 'XObject should be a stream');+ assertWellFormed(+ isStream(xobj), 'XObject should be a stream');var type = xobj.dict.get('Subtype');- assert(isName(type),- 'XObject should have a Name subtype');+ assertWellFormed(+ isName(type),+ 'XObject should have a Name subtype'+ );if ('Form' == type.name) {- stateManager.save();- self.buildFormXObject(resources, xobj, null, operatorList,- stateManager.state.clone());- args = [];- stateManager.restore();- continue;+ fn = 'promise';+ args = [self.buildFormXObject(resources, xobj)];} else if ('Image' == type.name) {- self.buildPaintImageXObject(resources, xobj, false,- operatorList, name, imageCache);- args = [];- continue;+ var data = self.buildPaintImageXObject(+ resources, xobj, false);+ Util.extendObj(dependencies, data.dependencies);+ self.insertDependencies(queue, data.dependencies);+ fn = data.fn;+ args = data.args;} else {error('Unhandled XObject subtype ' + type.name);}}- break;- case OPS.setFont:- // eagerly collect all fonts- var loadedName = self.handleSetFont(resources, args, null,- operatorList,- stateManager.state);- operatorList.addDependency(loadedName);- args[0] = loadedName;- break;- case OPS.endInlineImage:- var cacheKey = args[0].cacheKey;- if (cacheKey && imageCache.key === cacheKey) {- operatorList.addOp(imageCache.fn, imageCache.args);- args = [];- continue;- }- self.buildPaintImageXObject(resources, args[0], true,- operatorList, cacheKey, imageCache);- args = [];- continue;- case OPS.showText:- args[0] = this.handleText(args[0], stateManager.state);- break;- case OPS.showSpacedText:- var arr = args[0];- var arrLength = arr.length;- for (i = 0; i < arrLength; ++i) {- if (isString(arr[i])) {- arr[i] = this.handleText(arr[i], stateManager.state);- }- }- break;- case OPS.nextLineShowText:- args[0] = this.handleText(args[0], stateManager.state);- break;- case OPS.nextLineSetSpacingShowText:- args[2] = this.handleText(args[2], stateManager.state);- break;- case OPS.setTextRenderingMode:- stateManager.state.textRenderingMode = args[0];- break;- // Parse the ColorSpace data to a raw format.- case OPS.setFillColorSpace:- case OPS.setStrokeColorSpace:- args = [ColorSpace.parseToIR(args[0], xref, resources)];- break;- case OPS.shadingFill:- var shadingRes = resources.get('Shading');- if (!shadingRes) {- error('No shading resource found');- }-- shading = shadingRes.get(args[0].name);- if (!shading) {- error('No shading object found');- }+ } else if (cmd == 'Tf') { // eagerly collect all fonts+ fn = 'promise';+ args = [self.handleSetFont(resources, args)];+ } else if (cmd == 'EI') {+ var data = self.buildPaintImageXObject(+ resources, args[0], true);+ Util.extendObj(dependencies, data.dependencies);+ self.insertDependencies(queue, data.dependencies);+ fn = data.fn;+ args = data.args;+ }++ switch (fn) {+ // Parse the ColorSpace data to a raw format.+ case 'setFillColorSpace':+ case 'setStrokeColorSpace':+ args = [ColorSpace.parseToIR(args[0], xref, resources)];+ break;+ case 'shadingFill':+ var shadingRes = resources.get('Shading');+ if (!shadingRes)+ error('No shading resource found');++ var shading = shadingRes.get(args[0].name);+ if (!shading)+ error('No shading object found');++ var shadingFill = Pattern.parseShading(+ shading, null, xref, resources);+ var patternIR = shadingFill.getIR();+ args = [patternIR];+ fn = 'shadingFill';+ break;+ case 'setGState':+ var dictName = args[0];+ var extGState = resources.get('ExtGState');- var shadingFill = Pattern.parseShading(shading, null, xref,- resources);- var patternIR = shadingFill.getIR();- args = [patternIR];- fn = OPS.shadingFill;- break;- case OPS.setGState:- var dictName = args[0];- var extGState = resources.get('ExtGState');+ if (!isDict(extGState) || !extGState.has(dictName.name))+ break;- if (!isDict(extGState) || !extGState.has(dictName.name)) {- break;+ var gState = extGState.get(dictName.name);+ fn = 'promise';+ args = [self.setGState(resources, gState)];+ } // switch++ fnArray.push(fn);+ argsArray.push(args);+ args = [];+ parser.saveState();+ } else if (obj !== null && obj !== undefined) {+ args.push(obj instanceof Dict ? obj.getAll() : obj);+ assertWellFormed(args.length <= 33, 'Too many arguments');+ }+ }++ var subQueuePromises = [];+ for (var i = 0; i < fnArray.length; ++i) {+ if (fnArray[i] === 'promise') {+ subQueuePromises.push(argsArray[i][0]);+ }+ }+ Promise.all(subQueuePromises).then(function(datas) {+ // TODO(mack): Optimize by using repositioning elements+ // in original queue rather than creating new queue++ for (var i = 0, n = datas.length; i < n; ++i) {+ var data = datas[i];+ var subQueue = data.queue;+ queue.transparency = subQueue.transparency || queue.transparency;+ Util.extendObj(dependencies, data.dependencies);+ }++ var newFnArray = [];+ var newArgsArray = [];+ var currOffset = 0;+ var subQueueIdx = 0;+ for (var i = 0, n = fnArray.length; i < n; ++i) {+ var offset = i + currOffset;+ if (fnArray[i] === 'promise') {+ var data = datas[subQueueIdx++];+ var subQueue = data.queue;+ var subQueueFnArray = subQueue.fnArray;+ var subQueueArgsArray = subQueue.argsArray;+ for (var j = 0, nn = subQueueFnArray.length; j < nn; ++j) {+ newFnArray[offset + j] = subQueueFnArray[j];+ newArgsArray[offset + j] = subQueueArgsArray[j];}-- var gState = extGState.get(dictName.name);- self.setGState(resources, gState, operatorList, xref,- stateManager);- args = [];- continue;+ currOffset += subQueueFnArray.length - 1;+ } else {+ newFnArray[offset] = fnArray[i];+ newArgsArray[offset] = argsArray[i];+ }}- operatorList.addOp(fn, args);- }- // Some PDFs don't close all restores inside object/form.- // Closing those for them.- for (i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {- operatorList.addOp(OPS.restore, []);- }+ promise.resolve({+ queue: {+ fnArray: newFnArray,+ argsArray: newArgsArray,+ transparency: queue.transparency+ },+ dependencies: dependencies+ });+ });- return operatorList;+ return promise;},- getTextContent: function PartialEvaluator_getTextContent(stream, resources,- stateManager) {-- stateManager = (stateManager || new StateManager(new TextState()));+ getTextContent: function PartialEvaluator_getTextContent(+ stream, resources) {- var textContent = {- items: [],- styles: Object.create(null)- };- var bidiTexts = textContent.items;var SPACE_FACTOR = 0.35;var MULTI_SPACE_FACTOR = 1.5;-var self = this;- var xref = this.xref;- resources = (xref.fetchIfRef(resources) || Dict.empty);+ var statePromise = new Promise();- // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.- var xobjs = null;- var xobjsCache = {};-- var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);- var res = resources;-- var operation;- var textState;-- function newTextChunk() {- var font = textState.font;- if (!(font.loadedName in textContent.styles)) {- textContent.styles[font.loadedName] = {- fontFamily: font.fallbackName,- ascent: font.ascent,- descent: font.descent,- vertical: font.vertical- };- }- return {- str: '',- dir: null,- width: 0,- height: 0,- transform: null,- fontName: font.loadedName- };+ function handleSetFont(fontName, fontRef, resources) {+ var promise = new Promise();+ self.loadFont(fontName, fontRef, self.xref, resources).then(+ function(data) {+ promise.resolve(data.font.translated);+ }+ );+ return promise;}- function runBidi(textChunk) {- var bidiResult = PDFJS.bidi(textChunk.str, -1, textState.font.vertical);- textChunk.str = bidiResult.str;- textChunk.dir = bidiResult.dir;- return textChunk;- }-- function handleSetFont(fontName, fontRef) {- var font = textState.font = self.loadFont(fontName, fontRef, xref,- resources, null).translated;- textState.fontMatrix = font.fontMatrix ? font.fontMatrix :- FONT_IDENTITY_MATRIX;- }-- function buildTextGeometry(chars, textChunk) {- var font = textState.font;- textChunk = textChunk || newTextChunk();- if (!textChunk.transform) {- // 9.4.4 Text Space Details- var tsm = [textState.fontSize * textState.textHScale, 0,- 0, textState.fontSize,- 0, textState.textRise];- var trm = textChunk.transform = Util.transform(textState.ctm,- Util.transform(textState.textMatrix, tsm));- if (!font.vertical) {- textChunk.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);- } else {- textChunk.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);- }+ function getBidiText(str, startLevel, vertical) {+ if (str) {+ return PDFJS.bidi(str, -1, vertical);}- var width = 0;- var height = 0;- var glyphs = font.charsToGlyphs(chars);- var defaultVMetrics = font.defaultVMetrics;- for (var i = 0; i < glyphs.length; i++) {- var glyph = glyphs[i];- if (!glyph) { // Previous glyph was a space.- continue;- }- var vMetricX = null;- var vMetricY = null;- var glyphWidth = null;- if (font.vertical) {- if (glyph.vmetric) {- glyphWidth = glyph.vmetric[0];- vMetricX = glyph.vmetric[1];- vMetricY = glyph.vmetric[2];- } else {- glyphWidth = glyph.width;- vMetricX = glyph.width * 0.5;- vMetricY = defaultVMetrics[2];- }- } else {- glyphWidth = glyph.width;- }+ }- var glyphUnicode = glyph.unicode;- if (glyphUnicode in NormalizedUnicodes) {- glyphUnicode = NormalizedUnicodes[glyphUnicode];- }- glyphUnicode = reverseIfRtl(glyphUnicode);-- // The following will calculate the x and y of the individual glyphs.- // if (font.vertical) {- // tsm[4] -= vMetricX * Math.abs(textState.fontSize) *- // textState.fontMatrix[0];- // tsm[5] -= vMetricY * textState.fontSize *- // textState.fontMatrix[0];- // }- // var trm = Util.transform(textState.textMatrix, tsm);- // var pt = Util.applyTransform([trm[4], trm[5]], textState.ctm);- // var x = pt[0];- // var y = pt[1];-- var tx = 0;- var ty = 0;- if (!font.vertical) {- var w0 = glyphWidth * textState.fontMatrix[0];- tx = (w0 * textState.fontSize + textState.charSpacing) *- textState.textHScale;- width += tx;- } else {- var w1 = glyphWidth * textState.fontMatrix[0];- ty = w1 * textState.fontSize + textState.charSpacing;- height += ty;- }- textState.translateTextMatrix(tx, ty);+ resources = this.xref.fetchIfRef(resources) || new Dict();+ // The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.+ var xobjs = null;- textChunk.str += glyphUnicode;- }+ var parser = new Parser(new Lexer(stream), false);- var a = textState.textLineMatrix[0];- var b = textState.textLineMatrix[1];- var scaleLineX = Math.sqrt(a * a + b * b);- a = textState.ctm[0];- b = textState.ctm[1];- var scaleCtmX = Math.sqrt(a * a + b * b);- if (!font.vertical) {- textChunk.width += width * scaleCtmX * scaleLineX;- } else {- textChunk.height += Math.abs(height * scaleCtmX * scaleLineX);+ var chunkPromises = [];+ var fontPromise;+ var args = [];++ while (true) {+ var obj = parser.getObj();+ if (isEOF(obj)) {+ break;}- return textChunk;- }- while ((operation = preprocessor.read())) {- textState = stateManager.state;- var fn = operation.fn;- var args = operation.args;- switch (fn) {- case OPS.setFont:- handleSetFont(args[0].name);- textState.fontSize = args[1];- break;- case OPS.setTextRise:- textState.textRise = args[0];- break;- case OPS.setHScale:- textState.textHScale = args[0] / 100;- break;- case OPS.setLeading:- textState.leading = args[0];- break;- case OPS.moveText:- textState.translateTextLineMatrix(args[0], args[1]);- textState.textMatrix = textState.textLineMatrix.slice();- break;- case OPS.setLeadingMoveText:- textState.leading = -args[1];- textState.translateTextLineMatrix(args[0], args[1]);- textState.textMatrix = textState.textLineMatrix.slice();- break;- case OPS.nextLine:- textState.carriageReturn();- break;- case OPS.setTextMatrix:- textState.setTextMatrix(args[0], args[1], args[2], args[3],- args[4], args[5]);- textState.setTextLineMatrix(args[0], args[1], args[2], args[3],- args[4], args[5]);- break;- case OPS.setCharSpacing:- textState.charSpace = args[0];- break;- case OPS.setWordSpacing:- textState.wordSpace = args[0];- break;- case OPS.beginText:- textState.textMatrix = IDENTITY_MATRIX.slice();- textState.textLineMatrix = IDENTITY_MATRIX.slice();- break;- case OPS.showSpacedText:- var items = args[0];- var textChunk = newTextChunk();- var offset;- for (var j = 0, jj = items.length; j < jj; j++) {- if (typeof items[j] === 'string') {- buildTextGeometry(items[j], textChunk);- } else {- var val = items[j] / 1000;- if (!textState.font.vertical) {- offset = -val * textState.fontSize * textState.textHScale;- textState.translateTextMatrix(offset, 0);- textChunk.width += offset;- } else {- offset = -val * textState.fontSize;- textState.translateTextMatrix(0, offset);- textChunk.height += offset;- }- if (items[j] < 0 && textState.font.spaceWidth > 0) {- var fakeSpaces = -items[j] / textState.font.spaceWidth;- if (fakeSpaces > MULTI_SPACE_FACTOR) {- fakeSpaces = Math.round(fakeSpaces);- while (fakeSpaces--) {- textChunk.str += ' ';+ if (isCmd(obj)) {+ var cmd = obj.cmd;+ switch (cmd) {+ // TODO: Add support for SAVE/RESTORE and XFORM here.+ case 'Tf':+ fontPromise = handleSetFont(args[0].name, null, resources);+ //.translated;+ break;+ case 'TJ':+ var chunkPromise = new Promise();+ chunkPromises.push(chunkPromise);+ fontPromise.then(function(items, chunkPromise, font) {+ var chunk = '';+ for (var j = 0, jj = items.length; j < jj; j++) {+ if (typeof items[j] === 'string') {+ chunk += fontCharsToUnicode(items[j], font);+ } else if (items[j] < 0 && font.spaceWidth > 0) {+ var fakeSpaces = -items[j] / font.spaceWidth;+ if (fakeSpaces > MULTI_SPACE_FACTOR) {+ fakeSpaces = Math.round(fakeSpaces);+ while (fakeSpaces--) {+ chunk += ' ';+ }+ } else if (fakeSpaces > SPACE_FACTOR) {+ chunk += ' ';}- } else if (fakeSpaces > SPACE_FACTOR) {- textChunk.str += ' ';}}- }- }- bidiTexts.push(runBidi(textChunk));- break;- case OPS.showText:- bidiTexts.push(runBidi(buildTextGeometry(args[0])));- break;- case OPS.nextLineShowText:- textState.carriageReturn();- bidiTexts.push(runBidi(buildTextGeometry(args[0])));- break;- case OPS.nextLineSetSpacingShowText:- textState.wordSpacing = args[0];- textState.charSpacing = args[1];- textState.carriageReturn();- bidiTexts.push(runBidi(buildTextGeometry(args[2])));- break;- case OPS.paintXObject:- if (args[0].code) {+ chunkPromise.resolve(+ getBidiText(chunk, -1, font.vertical));+ }.bind(null, args[0], chunkPromise));break;- }-- if (!xobjs) {- xobjs = (resources.get('XObject') || Dict.empty);- }+ case 'Tj':+ var chunkPromise = new Promise();+ chunkPromises.push(chunkPromise);+ fontPromise.then(function(charCodes, chunkPromise, font) {+ var chunk = fontCharsToUnicode(charCodes, font);+ chunkPromise.resolve(+ getBidiText(chunk, -1, font.vertical));+ }.bind(null, args[0], chunkPromise));+ break;+ case '\'':+ // For search, adding a extra white space for line breaks+ // would be better here, but that causes too much spaces in+ // the text-selection divs.+ var chunkPromise = new Promise();+ chunkPromises.push(chunkPromise);+ fontPromise.then(function(charCodes, chunkPromise, font) {+ var chunk = fontCharsToUnicode(charCodes, font);+ chunkPromise.resolve(+ getBidiText(chunk, -1, font.vertical));+ }.bind(null, args[0], chunkPromise));+ break;+ case '"':+ // Note comment in "'"+ var chunkPromise = new Promise();+ chunkPromises.push(chunkPromise);+ fontPromise.then(function(charCodes, chunkPromise, font) {+ var chunk = fontCharsToUnicode(charCodes, font);+ chunkPromise.resolve(+ getBidiText(chunk, -1, font.vertical));+ }.bind(null, args[2], chunkPromise));+ break;+ case 'Do':+ if (args[0].code) {+ break;+ }- var name = args[0].name;- if (xobjsCache.key === name) {- if (xobjsCache.texts) {- Util.concatenateToArray(bidiTexts, xobjsCache.texts.items);- Util.extendObj(textContent.styles, xobjsCache.texts.styles);+ if (!xobjs) {+ xobjs = resources.get('XObject') || new Dict();}- break;- }- var xobj = xobjs.get(name);- if (!xobj) {- break;- }- assert(isStream(xobj), 'XObject should be a stream');+ var name = args[0].name;+ var xobj = xobjs.get(name);+ if (!xobj)+ break;+ assertWellFormed(isStream(xobj),+ 'XObject should be a stream');- var type = xobj.dict.get('Subtype');- assert(isName(type),- 'XObject should have a Name subtype');+ var type = xobj.dict.get('Subtype');+ assertWellFormed(+ isName(type),+ 'XObject should have a Name subtype'+ );++ if ('Form' !== type.name)+ break;- if ('Form' !== type.name) {- xobjsCache.key = name;- xobjsCache.texts = null;+ var chunkPromise = self.getTextContent(+ xobj,+ xobj.dict.get('Resources') || resources+ );+ chunkPromises.push(chunkPromise);break;- }+ case 'gs':+ var dictName = args[0];+ var extGState = resources.get('ExtGState');- stateManager.save();- var matrix = xobj.dict.get('Matrix');- if (isArray(matrix) && matrix.length === 6) {- stateManager.transform(matrix);- }+ if (!isDict(extGState) || !extGState.has(dictName.name))+ break;- var formTextContent = this.getTextContent(- xobj,- xobj.dict.get('Resources') || resources,- stateManager- );- Util.concatenateToArray(bidiTexts, formTextContent.items);- Util.extendObj(textContent.styles, formTextContent.styles);- stateManager.restore();-- xobjsCache.key = name;- xobjsCache.texts = formTextContent;- break;- case OPS.setGState:- var dictName = args[0];- var extGState = resources.get('ExtGState');+ var gsState = extGState.get(dictName.name);- if (!isDict(extGState) || !extGState.has(dictName.name)) {+ for (var i = 0; i < gsState.length; i++) {+ if (gsState[i] === 'Font') {+ fontPromise = handleSetFont(+ args[0].name, null, resources);+ }+ }break;- }+ } // switch- var gsState = extGState.get(dictName.name);-- for (var i = 0; i < gsState.length; i++) {- if (gsState[i] === 'Font') {- handleSetFont(args[0].name);- }- }- break;- } // switch+ args = [];+ parser.saveState();+ } else if (obj !== null && obj !== undefined) {+ assertWellFormed(args.length <= 33, 'Too many arguments');+ args.push(obj);+ }} // while- return textContent;+ Promise.all(chunkPromises).then(function(datas) {+ var bidiTexts = [];+ for (var i = 0, n = datas.length; i < n; ++i) {+ var bidiText = datas[i];+ if (!bidiText) {+ continue;+ } else if (isArray(bidiText)) {+ Util.concatenateToArray(bidiTexts, bidiText);+ } else {+ bidiTexts.push(bidiText);+ }+ }+ statePromise.resolve(bidiTexts);+ });++ return statePromise;},extractDataStructures: functionpartialEvaluatorExtractDataStructures(dict, baseDict,xref, properties) {// 9.10.2- var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));- if (toUnicode) {+ var toUnicode = dict.get('ToUnicode') ||+ baseDict.get('ToUnicode');+ if (toUnicode)properties.toUnicode = this.readToUnicode(toUnicode, xref, properties);- }+if (properties.composite) {// CIDSystemInfo helps to match CID to glyphsvar cidSystemInfo = dict.get('CIDSystemInfo');@@ -16290,102 +17273,195 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {}var cidToGidMap = dict.get('CIDToGIDMap');- if (isStream(cidToGidMap)) {+ if (isStream(cidToGidMap))properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);- }}// Based on 9.6.6 of the spec the encoding can come from multiple places- // and depends on the font type. The base encoding and differences are- // read here, but the encoding that is actually used is chosen during- // glyph mapping in the font.- // TODO: Loading the built in encoding in the font would allow the- // differences to be merged in here not require us to hold on to it.+ // but should be prioritized in the following order:+ // 1. Encoding dictionary+ // 2. Encoding within font file (Type1 or Type1C)+ // 3. Default (depends on font type)+ // Differences applied to the above.+ // Note: we don't fill in the encoding from the font file(2) here but use+ // the flag overridableEncoding to signal that the font can override the+ // encoding if it has one built in.+ var overridableEncoding = true;+ var hasEncoding = false;+ var flags = properties.flags;var differences = [];- var baseEncodingName = null;- var encoding;+ var baseEncoding = properties.type === 'TrueType' ?+ Encodings.WinAnsiEncoding :+ Encodings.StandardEncoding;+ // The Symbolic attribute can be misused for regular fonts+ // Heuristic: we have to check if the font is a standard one also+ if (!!(flags & FontFlags.Symbolic)) {+ baseEncoding = !properties.file ? Encodings.symbolsEncoding :+ Encodings.MacRomanEncoding;+ }if (dict.has('Encoding')) {- encoding = dict.get('Encoding');+ var encoding = dict.get('Encoding');if (isDict(encoding)) {- baseEncodingName = encoding.get('BaseEncoding');- baseEncodingName = (isName(baseEncodingName) ?- baseEncodingName.name : null);+ var baseName = encoding.get('BaseEncoding');+ if (baseName) {+ overridableEncoding = false;+ hasEncoding = true;+ baseEncoding = Encodings[baseName.name];+ }+// Load the differences between the base and originalif (encoding.has('Differences')) {+ hasEncoding = true;var diffEncoding = encoding.get('Differences');var index = 0;for (var j = 0, jj = diffEncoding.length; j < jj; j++) {var data = diffEncoding[j];- if (isNum(data)) {+ if (isNum(data))index = data;- } else {+ elsedifferences[index++] = data.name;- }}}} else if (isName(encoding)) {- baseEncodingName = encoding.name;+ overridableEncoding = false;+ hasEncoding = true;+ baseEncoding = Encodings[encoding.name];} else {error('Encoding is not a Name nor a Dict');}- // According to table 114 if the encoding is a named encoding it must be- // one of these predefined encodings.- if ((baseEncodingName !== 'MacRomanEncoding' &&- baseEncodingName !== 'MacExpertEncoding' &&- baseEncodingName !== 'WinAnsiEncoding')) {- baseEncodingName = null;- }- }-- if (baseEncodingName) {- properties.defaultEncoding = Encodings[baseEncodingName].slice();- } else {- encoding = (properties.type === 'TrueType' ?- Encodings.WinAnsiEncoding : Encodings.StandardEncoding);- // The Symbolic attribute can be misused for regular fonts- // Heuristic: we have to check if the font is a standard one also- if (!!(properties.flags & FontFlags.Symbolic)) {- encoding = (!properties.file && /Symbol/i.test(properties.name) ?- Encodings.SymbolSetEncoding :- Encodings.MacRomanEncoding);- }- properties.defaultEncoding = encoding;}properties.differences = differences;- properties.baseEncodingName = baseEncodingName;- properties.dict = dict;+ properties.baseEncoding = baseEncoding;+ properties.hasEncoding = hasEncoding;+ properties.overridableEncoding = overridableEncoding;},- readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {+ readToUnicode: function PartialEvaluator_readToUnicode(toUnicode, xref,+ properties) {var cmapObj = toUnicode;var charToUnicode = [];if (isName(cmapObj)) {- return CMapFactory.create(cmapObj).map;+ var isIdentityMap = cmapObj.name.substr(0, 9) == 'Identity-';+ if (!isIdentityMap)+ error('ToUnicode file cmap translation not implemented');} else if (isStream(cmapObj)) {- var cmap = CMapFactory.create(cmapObj).map;- // Convert UTF-16BE- // NOTE: cmap can be a sparse array, so use forEach instead of for(;;)- // to iterate over all keys.- cmap.forEach(function(token, i) {- var str = [];- for (var k = 0; k < token.length; k += 2) {- var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);- if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF- str.push(w1);- continue;+ var tokens = [];+ var token = '';+ var beginArrayToken = {};++ var cmap = cmapObj.getBytes(cmapObj.length);+ for (var i = 0, ii = cmap.length; i < ii; i++) {+ var octet = cmap[i];+ if (octet == 0x20 || octet == 0x0D || octet == 0x0A ||+ octet == 0x3C || octet == 0x5B || octet == 0x5D) {+ switch (token) {+ case 'usecmap':+ error('usecmap is not implemented');+ break;++ case 'beginbfchar':+ case 'beginbfrange':+ case 'begincidchar':+ case 'begincidrange':+ token = '';+ tokens = [];+ break;++ case 'endcidrange':+ case 'endbfrange':+ for (var j = 0, jj = tokens.length; j < jj; j += 3) {+ var startRange = tokens[j];+ var endRange = tokens[j + 1];+ var code = tokens[j + 2];+ if (code == 0xFFFF) {+ // CMap is broken, assuming code == startRange+ code = startRange;+ }+ if (isArray(code)) {+ var codeindex = 0;+ while (startRange <= endRange) {+ charToUnicode[startRange] = code[codeindex++];+ ++startRange;+ }+ } else {+ while (startRange <= endRange) {+ charToUnicode[startRange] = code++;+ ++startRange;+ }+ }+ }+ break;++ case 'endcidchar':+ case 'endbfchar':+ for (var j = 0, jj = tokens.length; j < jj; j += 2) {+ var index = tokens[j];+ var code = tokens[j + 1];+ charToUnicode[index] = code;+ }+ break;++ case '':+ break;++ default:+ if (token[0] >= '0' && token[0] <= '9')+ token = parseInt(token, 10); // a number+ tokens.push(token);+ token = '';+ }+ switch (octet) {+ case 0x5B:+ // begin list parsing+ tokens.push(beginArrayToken);+ break;+ case 0x5D:+ // collect array items+ var items = [], item;+ while (tokens.length &&+ (item = tokens.pop()) != beginArrayToken)+ items.unshift(item);+ tokens.push(items);+ break;+ }+ } else if (octet == 0x3E) {+ if (token.length) {+ // Heuristic: guessing chars size by checking numbers sizes+ // in the CMap entries.+ if (token.length == 2 && properties.composite)+ properties.wideChars = false;++ if (token.length <= 4) {+ // parsing hex number+ tokens.push(parseInt(token, 16));+ token = '';+ } else {+ // parsing hex UTF-16BE numbers+ var str = [];+ for (var k = 0, kk = token.length; k < kk; k += 4) {+ var b = parseInt(token.substr(k, 4), 16);+ if (b <= 0x10) {+ k += 4;+ b = (b << 16) | parseInt(token.substr(k, 4), 16);+ b -= 0x10000;+ str.push(0xD800 | (b >> 10));+ str.push(0xDC00 | (b & 0x3FF));+ break;+ }+ str.push(b);+ }+ tokens.push(String.fromCharCode.apply(String, str));+ token = '';+ }}- k += 2;- var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);- str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);+ } else {+ token += String.fromCharCode(octet);}- cmap[i] = String.fromCharCode.apply(String, str);- });- return cmap;+ }}- return null;+ return charToUnicode;},-readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {// Extract the encoding from the CIDToGIDMapvar glyphsData = cidToGidStream.getBytes();@@ -16394,1940 +17470,443 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {var result = [];for (var j = 0, jj = glyphsData.length; j < jj; j++) {var glyphID = (glyphsData[j++] << 8) | glyphsData[j];- if (glyphID === 0) {+ if (glyphID === 0)continue;- }+var code = j >> 1;result[code] = glyphID;}return result;},- extractWidths: function PartialEvaluator_extractWidths(dict, xref,- descriptor,- properties) {+ extractWidths: function PartialEvaluator_extractWidths(dict,+ xref,+ descriptor,+ properties) {var glyphsWidths = [];var defaultWidth = 0;var glyphsVMetrics = [];var defaultVMetrics;- var i, ii, j, jj, start, code, widths;if (properties.composite) {defaultWidth = dict.get('DW') || 1000;- widths = dict.get('W');+ var widths = dict.get('W');if (widths) {- for (i = 0, ii = widths.length; i < ii; i++) {- start = widths[i++];- code = xref.fetchIfRef(widths[i]);+ for (var i = 0, ii = widths.length; i < ii; i++) {+ var start = widths[i++];+ var code = xref.fetchIfRef(widths[i]);if (isArray(code)) {- for (j = 0, jj = code.length; j < jj; j++) {+ for (var j = 0, jj = code.length; j < jj; j++)glyphsWidths[start++] = code[j];- }} else {var width = widths[++i];- for (j = start; j <= code; j++) {+ for (var j = start; j <= code; j++)glyphsWidths[j] = width;- }}}}if (properties.vertical) {- var vmetrics = (dict.get('DW2') || [880, -1000]);+ var vmetrics = dict.get('DW2') || [880, -1000];defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];vmetrics = dict.get('W2');if (vmetrics) {- for (i = 0, ii = vmetrics.length; i < ii; i++) {- start = vmetrics[i++];- code = xref.fetchIfRef(vmetrics[i]);+ for (var i = 0, ii = vmetrics.length; i < ii; i++) {+ var start = vmetrics[i++];+ var code = xref.fetchIfRef(vmetrics[i]);if (isArray(code)) {- for (j = 0, jj = code.length; j < jj; j++) {+ for (var j = 0, jj = code.length; j < jj; j++)glyphsVMetrics[start++] = [code[j++], code[j++], code[j]];- }} else {var vmetric = [vmetrics[++i], vmetrics[++i], vmetrics[++i]];- for (j = start; j <= code; j++) {+ for (var j = start; j <= code; j++)glyphsVMetrics[j] = vmetric;- }}}}}} else {var firstChar = properties.firstChar;- widths = dict.get('Widths');+ var widths = dict.get('Widths');if (widths) {- j = firstChar;- for (i = 0, ii = widths.length; i < ii; i++) {+ var j = firstChar;+ for (var i = 0, ii = widths.length; i < ii; i++)glyphsWidths[j++] = widths[i];- }- defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);+ defaultWidth = parseFloat(descriptor.get('MissingWidth')) || 0;} else {// Trying get the BaseFont metrics (see comment above).var baseFontName = dict.get('BaseFont');if (isName(baseFontName)) {var metrics = this.getBaseFontMetrics(baseFontName.name);- glyphsWidths = this.buildCharCodeToWidth(metrics.widths,- properties);+ glyphsWidths = metrics.widths;defaultWidth = metrics.defaultWidth;}}}- // Heuristic: detection of monospace font by checking all non-zero widths- var isMonospace = true;- var firstWidth = defaultWidth;- for (var glyph in glyphsWidths) {- var glyphWidth = glyphsWidths[glyph];- if (!glyphWidth) {- continue;- }- if (!firstWidth) {- firstWidth = glyphWidth;- continue;- }- if (firstWidth != glyphWidth) {- isMonospace = false;- break;- }- }- if (isMonospace) {- properties.flags |= FontFlags.FixedPitch;- }-- properties.defaultWidth = defaultWidth;- properties.widths = glyphsWidths;- properties.defaultVMetrics = defaultVMetrics;- properties.vmetrics = glyphsVMetrics;- },-- isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {- // Simulating descriptor flags attribute- var fontNameWoStyle = baseFontName.split('-')[0];- return (fontNameWoStyle in serifFonts) ||- (fontNameWoStyle.search(/serif/gi) !== -1);- },-- getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {- var defaultWidth = 0;- var widths = [];- var monospace = false;- var lookupName = (stdFontMap[name] || name);-- if (!(lookupName in Metrics)) {- // Use default fonts for looking up font metrics if the passed- // font is not a base font- if (this.isSerifFont(name)) {- lookupName = 'Times-Roman';- } else {- lookupName = 'Helvetica';- }- }- var glyphWidths = Metrics[lookupName];-- if (isNum(glyphWidths)) {- defaultWidth = glyphWidths;- monospace = true;- } else {- widths = glyphWidths;- }-- return {- defaultWidth: defaultWidth,- monospace: monospace,- widths: widths- };- },-- buildCharCodeToWidth:- function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,- properties) {- var widths = Object.create(null);- var differences = properties.differences;- var encoding = properties.defaultEncoding;- for (var charCode = 0; charCode < 256; charCode++) {- if (charCode in differences &&- widthsByGlyphName[differences[charCode]]) {- widths[charCode] = widthsByGlyphName[differences[charCode]];- continue;- }- if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {- widths[charCode] = widthsByGlyphName[encoding[charCode]];- continue;- }- }- return widths;- },-- preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict, xref) {- var baseDict = dict;- var type = dict.get('Subtype');- assert(isName(type), 'invalid font Subtype');-- var composite = false;- var uint8array;- if (type.name == 'Type0') {- // If font is a composite- // - get the descendant font- // - set the type according to the descendant font- // - get the FontDescriptor from the descendant font- var df = dict.get('DescendantFonts');- if (!df) {- error('Descendant fonts are not specified');- }- dict = (isArray(df) ? xref.fetchIfRef(df[0]) : df);-- type = dict.get('Subtype');- assert(isName(type), 'invalid font Subtype');- composite = true;- }-- var descriptor = dict.get('FontDescriptor');- if (descriptor) {- var hash = new MurmurHash3_64();- var encoding = baseDict.getRaw('Encoding');- if (isName(encoding)) {- hash.update(encoding.name);- } else if (isRef(encoding)) {- hash.update(encoding.num + '_' + encoding.gen);- }-- var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');- if (isStream(toUnicode)) {- var stream = toUnicode.str || toUnicode;- uint8array = stream.buffer ?- new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :- new Uint8Array(stream.bytes.buffer,- stream.start, stream.end - stream.start);- hash.update(uint8array);-- } else if (isName(toUnicode)) {- hash.update(toUnicode.name);- }-- var widths = dict.get('Widths') || baseDict.get('Widths');- if (widths) {- uint8array = new Uint8Array(new Uint32Array(widths).buffer);- hash.update(uint8array);- }- }-- return {- descriptor: descriptor,- dict: dict,- baseDict: baseDict,- composite: composite,- hash: hash ? hash.hexdigest() : ''- };- },-- translateFont: function PartialEvaluator_translateFont(preEvaluatedFont,- xref) {- var baseDict = preEvaluatedFont.baseDict;- var dict = preEvaluatedFont.dict;- var composite = preEvaluatedFont.composite;- var descriptor = preEvaluatedFont.descriptor;- var type = dict.get('Subtype');- var maxCharIndex = (composite ? 0xFFFF : 0xFF);- var properties;-- if (!descriptor) {- if (type.name == 'Type3') {- // FontDescriptor is only required for Type3 fonts when the document- // is a tagged pdf. Create a barbebones one to get by.- descriptor = new Dict(null);- descriptor.set('FontName', Name.get(type.name));- } else {- // Before PDF 1.5 if the font was one of the base 14 fonts, having a- // FontDescriptor was not required.- // This case is here for compatibility.- var baseFontName = dict.get('BaseFont');- if (!isName(baseFontName)) {- error('Base font is not specified');- }-- // Using base font name as a font name.- baseFontName = baseFontName.name.replace(/[,_]/g, '-');- var metrics = this.getBaseFontMetrics(baseFontName);-- // Simulating descriptor flags attribute- var fontNameWoStyle = baseFontName.split('-')[0];- var flags =- (this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |- (metrics.monospace ? FontFlags.FixedPitch : 0) |- (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :- FontFlags.Nonsymbolic);-- properties = {- type: type.name,- name: baseFontName,- widths: metrics.widths,- defaultWidth: metrics.defaultWidth,- flags: flags,- firstChar: 0,- lastChar: maxCharIndex- };- this.extractDataStructures(dict, dict, xref, properties);- properties.widths = this.buildCharCodeToWidth(metrics.widths,- properties);- return new Font(baseFontName, null, properties);- }- }-- // According to the spec if 'FontDescriptor' is declared, 'FirstChar',- // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem- // to ignore this rule when a variant of a standart font is used.- // TODO Fill the width array depending on which of the base font this is- // a variant.- var firstChar = (dict.get('FirstChar') || 0);- var lastChar = (dict.get('LastChar') || maxCharIndex);-- var fontName = descriptor.get('FontName');- var baseFont = dict.get('BaseFont');- // Some bad PDFs have a string as the font name.- if (isString(fontName)) {- fontName = Name.get(fontName);- }- if (isString(baseFont)) {- baseFont = Name.get(baseFont);- }-- if (type.name !== 'Type3') {- var fontNameStr = fontName && fontName.name;- var baseFontStr = baseFont && baseFont.name;- if (fontNameStr !== baseFontStr) {- info('The FontDescriptor\'s FontName is "' + fontNameStr +- '" but should be the same as the Font\'s BaseFont "' +- baseFontStr + '"');- // Workaround for cases where e.g. fontNameStr = 'Arial' and- // baseFontStr = 'Arial,Bold' (needed when no font file is embedded).- if (fontNameStr && baseFontStr &&- baseFontStr.search(fontNameStr) === 0) {- fontName = baseFont;- }- }- }- fontName = (fontName || baseFont);-- assert(isName(fontName), 'invalid font name');-- var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');- if (fontFile) {- if (fontFile.dict) {- var subtype = fontFile.dict.get('Subtype');- if (subtype) {- subtype = subtype.name;- }- var length1 = fontFile.dict.get('Length1');- var length2 = fontFile.dict.get('Length2');- }- }-- properties = {- type: type.name,- name: fontName.name,- subtype: subtype,- file: fontFile,- length1: length1,- length2: length2,- loadedName: baseDict.loadedName,- composite: composite,- wideChars: composite,- fixedPitch: false,- fontMatrix: (dict.get('FontMatrix') || FONT_IDENTITY_MATRIX),- firstChar: firstChar || 0,- lastChar: (lastChar || maxCharIndex),- bbox: descriptor.get('FontBBox'),- ascent: descriptor.get('Ascent'),- descent: descriptor.get('Descent'),- xHeight: descriptor.get('XHeight'),- capHeight: descriptor.get('CapHeight'),- flags: descriptor.get('Flags'),- italicAngle: descriptor.get('ItalicAngle'),- coded: false- };-- if (composite) {- var cidEncoding = baseDict.get('Encoding');- if (isName(cidEncoding)) {- properties.cidEncoding = cidEncoding.name;- }- properties.cMap = CMapFactory.create(cidEncoding,- { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);- properties.vertical = properties.cMap.vertical;- }- this.extractDataStructures(dict, baseDict, xref, properties);- this.extractWidths(dict, xref, descriptor, properties);-- if (type.name === 'Type3') {- properties.coded = true;- }-- return new Font(fontName.name, fontFile, properties);- }- };-- return PartialEvaluator;-})();--var OperatorList = (function OperatorListClosure() {- var CHUNK_SIZE = 1000;- var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size-- function getTransfers(queue) {- var transfers = [];- var fnArray = queue.fnArray, argsArray = queue.argsArray;- for (var i = 0, ii = queue.length; i < ii; i++) {- switch (fnArray[i]) {- case OPS.paintInlineImageXObject:- case OPS.paintInlineImageXObjectGroup:- case OPS.paintImageMaskXObject:- var arg = argsArray[i][0]; // first param in imgData- if (!arg.cached) {- transfers.push(arg.data.buffer);- }- break;- }- }- return transfers;- }-- function OperatorList(intent, messageHandler, pageIndex) {- this.messageHandler = messageHandler;- this.fnArray = [];- this.argsArray = [];- this.dependencies = {};- this.pageIndex = pageIndex;- this.intent = intent;- }-- OperatorList.prototype = {- get length() {- return this.argsArray.length;- },-- addOp: function(fn, args) {- this.fnArray.push(fn);- this.argsArray.push(args);- if (this.messageHandler) {- if (this.fnArray.length >= CHUNK_SIZE) {- this.flush();- } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&- (fn === OPS.restore || fn === OPS.endText)) {- // heuristic to flush on boundary of restore or endText- this.flush();- }- }- },-- addDependency: function(dependency) {- if (dependency in this.dependencies) {- return;- }- this.dependencies[dependency] = true;- this.addOp(OPS.dependency, [dependency]);- },-- addDependencies: function(dependencies) {- for (var key in dependencies) {- this.addDependency(key);- }- },-- addOpList: function(opList) {- Util.extendObj(this.dependencies, opList.dependencies);- for (var i = 0, ii = opList.length; i < ii; i++) {- this.addOp(opList.fnArray[i], opList.argsArray[i]);- }- },-- getIR: function() {- return {- fnArray: this.fnArray,- argsArray: this.argsArray,- length: this.length- };- },-- flush: function(lastChunk) {- new QueueOptimizer().optimize(this);- var transfers = getTransfers(this);- this.messageHandler.send('RenderPageChunk', {- operatorList: {- fnArray: this.fnArray,- argsArray: this.argsArray,- lastChunk: lastChunk,- length: this.length- },- pageIndex: this.pageIndex,- intent: this.intent- }, null, transfers);- this.dependencies = {};- this.fnArray.length = 0;- this.argsArray.length = 0;- }- };-- return OperatorList;-})();--var StateManager = (function StateManagerClosure() {- function StateManager(initialState) {- this.state = initialState;- this.stateStack = [];- }- StateManager.prototype = {- save: function () {- var old = this.state;- this.stateStack.push(this.state);- this.state = old.clone();- },- restore: function () {- var prev = this.stateStack.pop();- if (prev) {- this.state = prev;- }- },- transform: function (args) {- this.state.ctm = Util.transform(this.state.ctm, args);- }- };- return StateManager;-})();--var TextState = (function TextStateClosure() {- function TextState() {- this.ctm = new Float32Array(IDENTITY_MATRIX);- this.fontSize = 0;- this.font = null;- this.fontMatrix = FONT_IDENTITY_MATRIX;- this.textMatrix = IDENTITY_MATRIX.slice();- this.textLineMatrix = IDENTITY_MATRIX.slice();- this.charSpacing = 0;- this.wordSpacing = 0;- this.leading = 0;- this.textHScale = 1;- this.textRise = 0;- }-- TextState.prototype = {- setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {- var m = this.textMatrix;- m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;- },- setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {- var m = this.textLineMatrix;- m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;- },- translateTextMatrix: function TextState_translateTextMatrix(x, y) {- var m = this.textMatrix;- m[4] = m[0] * x + m[2] * y + m[4];- m[5] = m[1] * x + m[3] * y + m[5];- },- translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {- var m = this.textLineMatrix;- m[4] = m[0] * x + m[2] * y + m[4];- m[5] = m[1] * x + m[3] * y + m[5];- },- calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {- // 9.4.4 Text Space Details- var tsm = [this.fontSize * this.textHScale, 0,- 0, this.fontSize,- 0, this.textRise];- return Util.transform(ctm, Util.transform(this.textMatrix, tsm));- },- carriageReturn: function TextState_carriageReturn() {- this.translateTextLineMatrix(0, -this.leading);- this.textMatrix = this.textLineMatrix.slice();- },- clone: function TextState_clone() {- var clone = Object.create(this);- clone.textMatrix = this.textMatrix.slice();- clone.textLineMatrix = this.textLineMatrix.slice();- clone.fontMatrix = this.fontMatrix.slice();- return clone;- }- };- return TextState;-})();--var EvalState = (function EvalStateClosure() {- function EvalState() {- this.ctm = new Float32Array(IDENTITY_MATRIX);- this.font = null;- this.textRenderingMode = TextRenderingMode.FILL;- }- EvalState.prototype = {- clone: function CanvasExtraState_clone() {- return Object.create(this);- },- };- return EvalState;-})();--var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {- // Specifies properties for each command- //- // If variableArgs === true: [0, `numArgs`] expected- // If variableArgs === false: exactly `numArgs` expected- var OP_MAP = {- // Graphic state- w: { id: OPS.setLineWidth, numArgs: 1, variableArgs: false },- J: { id: OPS.setLineCap, numArgs: 1, variableArgs: false },- j: { id: OPS.setLineJoin, numArgs: 1, variableArgs: false },- M: { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false },- d: { id: OPS.setDash, numArgs: 2, variableArgs: false },- ri: { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false },- i: { id: OPS.setFlatness, numArgs: 1, variableArgs: false },- gs: { id: OPS.setGState, numArgs: 1, variableArgs: false },- q: { id: OPS.save, numArgs: 0, variableArgs: false },- Q: { id: OPS.restore, numArgs: 0, variableArgs: false },- cm: { id: OPS.transform, numArgs: 6, variableArgs: false },-- // Path- m: { id: OPS.moveTo, numArgs: 2, variableArgs: false },- l: { id: OPS.lineTo, numArgs: 2, variableArgs: false },- c: { id: OPS.curveTo, numArgs: 6, variableArgs: false },- v: { id: OPS.curveTo2, numArgs: 4, variableArgs: false },- y: { id: OPS.curveTo3, numArgs: 4, variableArgs: false },- h: { id: OPS.closePath, numArgs: 0, variableArgs: false },- re: { id: OPS.rectangle, numArgs: 4, variableArgs: false },- S: { id: OPS.stroke, numArgs: 0, variableArgs: false },- s: { id: OPS.closeStroke, numArgs: 0, variableArgs: false },- f: { id: OPS.fill, numArgs: 0, variableArgs: false },- F: { id: OPS.fill, numArgs: 0, variableArgs: false },- 'f*': { id: OPS.eoFill, numArgs: 0, variableArgs: false },- B: { id: OPS.fillStroke, numArgs: 0, variableArgs: false },- 'B*': { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false },- b: { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false },- 'b*': { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false },- n: { id: OPS.endPath, numArgs: 0, variableArgs: false },-- // Clipping- W: { id: OPS.clip, numArgs: 0, variableArgs: false },- 'W*': { id: OPS.eoClip, numArgs: 0, variableArgs: false },-- // Text- BT: { id: OPS.beginText, numArgs: 0, variableArgs: false },- ET: { id: OPS.endText, numArgs: 0, variableArgs: false },- Tc: { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false },- Tw: { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false },- Tz: { id: OPS.setHScale, numArgs: 1, variableArgs: false },- TL: { id: OPS.setLeading, numArgs: 1, variableArgs: false },- Tf: { id: OPS.setFont, numArgs: 2, variableArgs: false },- Tr: { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false },- Ts: { id: OPS.setTextRise, numArgs: 1, variableArgs: false },- Td: { id: OPS.moveText, numArgs: 2, variableArgs: false },- TD: { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false },- Tm: { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false },- 'T*': { id: OPS.nextLine, numArgs: 0, variableArgs: false },- Tj: { id: OPS.showText, numArgs: 1, variableArgs: false },- TJ: { id: OPS.showSpacedText, numArgs: 1, variableArgs: false },- '\'': { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false },- '"': { id: OPS.nextLineSetSpacingShowText, numArgs: 3,- variableArgs: false },-- // Type3 fonts- d0: { id: OPS.setCharWidth, numArgs: 2, variableArgs: false },- d1: { id: OPS.setCharWidthAndBounds, numArgs: 6, variableArgs: false },-- // Color- CS: { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false },- cs: { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false },- SC: { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true },- SCN: { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true },- sc: { id: OPS.setFillColor, numArgs: 4, variableArgs: true },- scn: { id: OPS.setFillColorN, numArgs: 33, variableArgs: true },- G: { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false },- g: { id: OPS.setFillGray, numArgs: 1, variableArgs: false },- RG: { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false },- rg: { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false },- K: { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false },- k: { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false },-- // Shading- sh: { id: OPS.shadingFill, numArgs: 1, variableArgs: false },-- // Images- BI: { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false },- ID: { id: OPS.beginImageData, numArgs: 0, variableArgs: false },- EI: { id: OPS.endInlineImage, numArgs: 1, variableArgs: false },-- // XObjects- Do: { id: OPS.paintXObject, numArgs: 1, variableArgs: false },- MP: { id: OPS.markPoint, numArgs: 1, variableArgs: false },- DP: { id: OPS.markPointProps, numArgs: 2, variableArgs: false },- BMC: { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false },- BDC: { id: OPS.beginMarkedContentProps, numArgs: 2,- variableArgs: false },- EMC: { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false },-- // Compatibility- BX: { id: OPS.beginCompat, numArgs: 0, variableArgs: false },- EX: { id: OPS.endCompat, numArgs: 0, variableArgs: false },-- // (reserved partial commands for the lexer)- BM: null,- BD: null,- 'true': null,- fa: null,- fal: null,- fals: null,- 'false': null,- nu: null,- nul: null,- 'null': null- };-- function EvaluatorPreprocessor(stream, xref, stateManager) {- // TODO(mduan): pass array of knownCommands rather than OP_MAP- // dictionary- this.parser = new Parser(new Lexer(stream, OP_MAP), false, xref);- this.stateManager = stateManager;- }-- EvaluatorPreprocessor.prototype = {- get savedStatesDepth() {- return this.stateManager.stateStack.length;- },-- read: function EvaluatorPreprocessor_read() {- var args = [];- while (true) {- var obj = this.parser.getObj();- if (isEOF(obj)) {- return null; // no more commands- }- if (!isCmd(obj)) {- // argument- if (obj !== null && obj !== undefined) {- args.push((obj instanceof Dict ? obj.getAll() : obj));- assert(args.length <= 33, 'Too many arguments');- }- continue;- }-- var cmd = obj.cmd;- // Check that the command is valid- var opSpec = OP_MAP[cmd];- if (!opSpec) {- warn('Unknown command "' + cmd + '"');- continue;- }-- var fn = opSpec.id;-- // Validate the number of arguments for the command- if (opSpec.variableArgs) {- if (args.length > opSpec.numArgs) {- info('Command ' + fn + ': expected [0,' + opSpec.numArgs +- '] args, but received ' + args.length + ' args');- }- } else {- if (args.length < opSpec.numArgs) {- // If we receive too few args, it's not possible to possible- // to execute the command, so skip the command- info('Command ' + fn + ': because expected ' +- opSpec.numArgs + ' args, but received ' + args.length +- ' args; skipping');- args = [];- continue;- } else if (args.length > opSpec.numArgs) {- info('Command ' + fn + ': expected ' + opSpec.numArgs +- ' args, but received ' + args.length + ' args');- }- }-- // TODO figure out how to type-check vararg functions- this.preprocessCommand(fn, args);-- return { fn: fn, args: args };- }- },-- preprocessCommand:- function EvaluatorPreprocessor_preprocessCommand(fn, args) {- switch (fn | 0) {- case OPS.save:- this.stateManager.save();- break;- case OPS.restore:- this.stateManager.restore();- break;- case OPS.transform:- this.stateManager.transform(args);- break;- }- }- };- return EvaluatorPreprocessor;-})();--var QueueOptimizer = (function QueueOptimizerClosure() {- function addState(parentState, pattern, fn) {- var state = parentState;- for (var i = 0, ii = pattern.length - 1; i < ii; i++) {- var item = pattern[i];- state = (state[item] || (state[item] = []));- }- state[pattern[pattern.length - 1]] = fn;- }-- function handlePaintSolidColorImageMask(index, count, fnArray, argsArray) {- // Handles special case of mainly LaTeX documents which- // use image masks to draw lines with the current fill style.- // 'count' groups of (save, transform, paintImageMaskXObject, restore)+- // have been found at index.- for (var i = 0; i < count; i++) {- var arg = argsArray[index + 4 * i + 2];- var imageMask = arg.length == 1 && arg[0];- if (imageMask && imageMask.width == 1 && imageMask.height == 1 &&- (!imageMask.data.length || (imageMask.data.length == 1 &&- imageMask.data[0] === 0))) {- fnArray[index + 4 * i + 2] = OPS.paintSolidColorImageMask;- continue;- }- break;- }- return count - i;- }-- var InitialState = [];-- addState(InitialState,- [OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],- function foundInlineImageGroup(context) {- // grouping paintInlineImageXObject's into paintInlineImageXObjectGroup- // searching for (save, transform, paintInlineImageXObject, restore)+- var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;- var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;- var MAX_WIDTH = 1000;- var IMAGE_PADDING = 1;-- var fnArray = context.fnArray, argsArray = context.argsArray;- var j = context.currentOperation - 3, i = j + 4;- var ii = fnArray.length;-- for (; i < ii && fnArray[i - 4] === fnArray[i]; i++) {}- var count = Math.min((i - j) >> 2, MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);- if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {- context.currentOperation = i - 1;- return;- }- // assuming that heights of those image is too small (~1 pixel)- // packing as much as possible by lines- var maxX = 0;- var map = [], maxLineHeight = 0;- var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;- var q;- for (q = 0; q < count; q++) {- var transform = argsArray[j + (q << 2) + 1];- var img = argsArray[j + (q << 2) + 2][0];- if (currentX + img.width > MAX_WIDTH) {- // starting new line- maxX = Math.max(maxX, currentX);- currentY += maxLineHeight + 2 * IMAGE_PADDING;- currentX = 0;- maxLineHeight = 0;- }- map.push({- transform: transform,- x: currentX, y: currentY,- w: img.width, h: img.height- });- currentX += img.width + 2 * IMAGE_PADDING;- maxLineHeight = Math.max(maxLineHeight, img.height);- }- var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;- var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;- var imgData = new Uint8Array(imgWidth * imgHeight * 4);- var imgRowSize = imgWidth << 2;- for (q = 0; q < count; q++) {- var data = argsArray[j + (q << 2) + 2][0].data;- // copy image by lines and extends pixels into padding- var rowSize = map[q].w << 2;- var dataOffset = 0;- var offset = (map[q].x + map[q].y * imgWidth) << 2;- imgData.set(data.subarray(0, rowSize), offset - imgRowSize);- for (var k = 0, kk = map[q].h; k < kk; k++) {- imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);- dataOffset += rowSize;- offset += imgRowSize;- }- imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);- while (offset >= 0) {- data[offset - 4] = data[offset];- data[offset - 3] = data[offset + 1];- data[offset - 2] = data[offset + 2];- data[offset - 1] = data[offset + 3];- data[offset + rowSize] = data[offset + rowSize - 4];- data[offset + rowSize + 1] = data[offset + rowSize - 3];- data[offset + rowSize + 2] = data[offset + rowSize - 2];- data[offset + rowSize + 3] = data[offset + rowSize - 1];- offset -= imgRowSize;- }- }- // replacing queue items- fnArray.splice(j, count * 4, OPS.paintInlineImageXObjectGroup);- argsArray.splice(j, count * 4,- [{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,- data: imgData }, map]);- context.currentOperation = j;- });-- addState(InitialState,- [OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],- function foundImageMaskGroup(context) {- // grouping paintImageMaskXObject's into paintImageMaskXObjectGroup- // searching for (save, transform, paintImageMaskXObject, restore)+- var MIN_IMAGES_IN_MASKS_BLOCK = 10;- var MAX_IMAGES_IN_MASKS_BLOCK = 100;- var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;-- var fnArray = context.fnArray, argsArray = context.argsArray;- var j = context.currentOperation - 3, i = j + 4;- var ii = fnArray.length, q;-- for (; i < ii && fnArray[i - 4] === fnArray[i]; i++) {}- var count = (i - j) >> 2;- count = handlePaintSolidColorImageMask(j, count, fnArray, argsArray);- if (count < MIN_IMAGES_IN_MASKS_BLOCK) {- context.currentOperation = i - 1;- return;- }-- var isSameImage = false;- var transformArgs;- if (argsArray[j + 1][1] === 0 && argsArray[j + 1][2] === 0) {- i = j + 4;- isSameImage = true;- for (q = 1; q < count; q++, i += 4) {- var prevTransformArgs = argsArray[i - 3];- transformArgs = argsArray[i + 1];- if (argsArray[i - 2][0] !== argsArray[i + 2][0] ||- prevTransformArgs[0] !== transformArgs[0] ||- prevTransformArgs[1] !== transformArgs[1] ||- prevTransformArgs[2] !== transformArgs[2] ||- prevTransformArgs[3] !== transformArgs[3]) {- if (q < MIN_IMAGES_IN_MASKS_BLOCK) {- isSameImage = false;- } else {- count = q;- }- break; // different image or transform- }- }- }-- if (isSameImage) {- count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);- var positions = new Float32Array(count * 2);- i = j + 1;- for (q = 0; q < count; q++) {- transformArgs = argsArray[i];- positions[(q << 1)] = transformArgs[4];- positions[(q << 1) + 1] = transformArgs[5];- i += 4;- }-- // replacing queue items- fnArray.splice(j, count * 4, OPS.paintImageMaskXObjectRepeat);- argsArray.splice(j, count * 4, [argsArray[j + 2][0],- argsArray[j + 1][0], argsArray[j + 1][3], positions]);-- context.currentOperation = j;- } else {- count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);- var images = [];- for (q = 0; q < count; q++) {- transformArgs = argsArray[j + (q << 2) + 1];- var maskParams = argsArray[j + (q << 2) + 2][0];- images.push({ data: maskParams.data, width: maskParams.width,- height: maskParams.height,- transform: transformArgs });- }-- // replacing queue items- fnArray.splice(j, count * 4, OPS.paintImageMaskXObjectGroup);- argsArray.splice(j, count * 4, [images]);-- context.currentOperation = j;- }- });-- addState(InitialState,- [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],- function (context) {- var MIN_IMAGES_IN_BLOCK = 3;- var MAX_IMAGES_IN_BLOCK = 1000;-- var fnArray = context.fnArray, argsArray = context.argsArray;- var j = context.currentOperation - 3, i = j + 4;- if (argsArray[j + 1][1] !== 0 || argsArray[j + 1][2] !== 0) {- return;- }- var ii = fnArray.length;- var transformArgs;- for (; i + 3 < ii && fnArray[i - 4] === fnArray[i]; i += 4) {- if (fnArray[i - 3] !== fnArray[i + 1] ||- fnArray[i - 2] !== fnArray[i + 2] ||- fnArray[i - 1] !== fnArray[i + 3]) {- break;- }- if (argsArray[i - 2][0] !== argsArray[i + 2][0]) {- break; // different image- }- var prevTransformArgs = argsArray[i - 3];- transformArgs = argsArray[i + 1];- if (prevTransformArgs[0] !== transformArgs[0] ||- prevTransformArgs[1] !== transformArgs[1] ||- prevTransformArgs[2] !== transformArgs[2] ||- prevTransformArgs[3] !== transformArgs[3]) {- break; // different transform- }- }- var count = Math.min((i - j) >> 2, MAX_IMAGES_IN_BLOCK);- if (count < MIN_IMAGES_IN_BLOCK) {- context.currentOperation = i - 1;- return;- }-- var positions = new Float32Array(count * 2);- i = j + 1;- for (var q = 0; q < count; q++) {- transformArgs = argsArray[i];- positions[(q << 1)] = transformArgs[4];- positions[(q << 1) + 1] = transformArgs[5];- i += 4;- }- var args = [argsArray[j + 2][0], argsArray[j + 1][0],- argsArray[j + 1][3], positions];- // replacing queue items- fnArray.splice(j, count * 4, OPS.paintImageXObjectRepeat);- argsArray.splice(j, count * 4, args);-- context.currentOperation = j;- });-- addState(InitialState,- [OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],- function (context) {- // moving single chars with same font into beginText/endText groups- // searching for (beginText, setFont, setTextMatrix, showText, endText)+- var MIN_CHARS_IN_BLOCK = 3;- var MAX_CHARS_IN_BLOCK = 1000;-- var fnArray = context.fnArray, argsArray = context.argsArray;- var j = context.currentOperation - 4, i = j + 5;- var ii = fnArray.length;-- for (; i < ii && fnArray[i - 5] === fnArray[i]; i++) {- if (fnArray[i] === OPS.setFont) {- if (argsArray[i - 5][0] !== argsArray[i][0] ||- argsArray[i - 5][1] !== argsArray[i][1]) {- break;- }- }- }- var count = Math.min(((i - j) / 5) | 0, MAX_CHARS_IN_BLOCK);- if (count < MIN_CHARS_IN_BLOCK) {- context.currentOperation = i - 1;- return;- }- if (j >= 4 && fnArray[j - 4] === fnArray[j + 1] &&- fnArray[j - 3] === fnArray[j + 2] &&- fnArray[j - 2] === fnArray[j + 3] &&- fnArray[j - 1] === fnArray[j + 4] &&- argsArray[j - 4][0] === argsArray[j + 1][0] &&- argsArray[j - 4][1] === argsArray[j + 1][1]) {- // extending one block ahead (very first block might have 'dependency')- count++;- j -= 5;- }- var k = j + 7;- i = j + 4;- for (var q = 1; q < count; q++) {- fnArray[i] = fnArray[k];- argsArray[i] = argsArray[k];- fnArray[i + 1] = fnArray[k + 1];- argsArray[i + 1] = argsArray[k + 1];- i += 2;- k += 5;- }- var removed = (count - 1) * 3;- fnArray.splice(i, removed);- argsArray.splice(i, removed);-- context.currentOperation = i;- });-- function QueueOptimizer() {}-- QueueOptimizer.prototype = {- optimize: function QueueOptimizer_optimize(queue) {- var fnArray = queue.fnArray, argsArray = queue.argsArray;- var context = {- currentOperation: 0,- fnArray: fnArray,- argsArray: argsArray- };- var i, ii = argsArray.length;- var state;- for (i = 0; i < ii; i++) {- state = (state || InitialState)[fnArray[i]];- if (typeof state === 'function') { // we found some handler- context.currentOperation = i;- state = state(context);- i = context.currentOperation;- ii = context.fnArray.length;- }- }- }- };- return QueueOptimizer;-})();-+ // Heuristic: detection of monospace font by checking all non-zero widths+ var isMonospace = true, firstWidth = defaultWidth;+ for (var glyph in glyphsWidths) {+ var glyphWidth = glyphsWidths[glyph];+ if (!glyphWidth)+ continue;+ if (!firstWidth) {+ firstWidth = glyphWidth;+ continue;+ }+ if (firstWidth != glyphWidth) {+ isMonospace = false;+ break;+ }+ }+ if (isMonospace)+ properties.flags |= FontFlags.FixedPitch;-var BUILT_IN_CMAPS = [-// << Start unicode maps.-'Adobe-GB1-UCS2',-'Adobe-CNS1-UCS2',-'Adobe-Japan1-UCS2',-'Adobe-Korea1-UCS2',-// >> End unicode maps.-'78-EUC-H',-'78-EUC-V',-'78-H',-'78-RKSJ-H',-'78-RKSJ-V',-'78-V',-'78ms-RKSJ-H',-'78ms-RKSJ-V',-'83pv-RKSJ-H',-'90ms-RKSJ-H',-'90ms-RKSJ-V',-'90msp-RKSJ-H',-'90msp-RKSJ-V',-'90pv-RKSJ-H',-'90pv-RKSJ-V',-'Add-H',-'Add-RKSJ-H',-'Add-RKSJ-V',-'Add-V',-'Adobe-CNS1-0',-'Adobe-CNS1-1',-'Adobe-CNS1-2',-'Adobe-CNS1-3',-'Adobe-CNS1-4',-'Adobe-CNS1-5',-'Adobe-CNS1-6',-'Adobe-GB1-0',-'Adobe-GB1-1',-'Adobe-GB1-2',-'Adobe-GB1-3',-'Adobe-GB1-4',-'Adobe-GB1-5',-'Adobe-Japan1-0',-'Adobe-Japan1-1',-'Adobe-Japan1-2',-'Adobe-Japan1-3',-'Adobe-Japan1-4',-'Adobe-Japan1-5',-'Adobe-Japan1-6',-'Adobe-Korea1-0',-'Adobe-Korea1-1',-'Adobe-Korea1-2',-'B5-H',-'B5-V',-'B5pc-H',-'B5pc-V',-'CNS-EUC-H',-'CNS-EUC-V',-'CNS1-H',-'CNS1-V',-'CNS2-H',-'CNS2-V',-'ETHK-B5-H',-'ETHK-B5-V',-'ETen-B5-H',-'ETen-B5-V',-'ETenms-B5-H',-'ETenms-B5-V',-'EUC-H',-'EUC-V',-'Ext-H',-'Ext-RKSJ-H',-'Ext-RKSJ-V',-'Ext-V',-'GB-EUC-H',-'GB-EUC-V',-'GB-H',-'GB-V',-'GBK-EUC-H',-'GBK-EUC-V',-'GBK2K-H',-'GBK2K-V',-'GBKp-EUC-H',-'GBKp-EUC-V',-'GBT-EUC-H',-'GBT-EUC-V',-'GBT-H',-'GBT-V',-'GBTpc-EUC-H',-'GBTpc-EUC-V',-'GBpc-EUC-H',-'GBpc-EUC-V',-'H',-'HKdla-B5-H',-'HKdla-B5-V',-'HKdlb-B5-H',-'HKdlb-B5-V',-'HKgccs-B5-H',-'HKgccs-B5-V',-'HKm314-B5-H',-'HKm314-B5-V',-'HKm471-B5-H',-'HKm471-B5-V',-'HKscs-B5-H',-'HKscs-B5-V',-'Hankaku',-'Hiragana',-'KSC-EUC-H',-'KSC-EUC-V',-'KSC-H',-'KSC-Johab-H',-'KSC-Johab-V',-'KSC-V',-'KSCms-UHC-H',-'KSCms-UHC-HW-H',-'KSCms-UHC-HW-V',-'KSCms-UHC-V',-'KSCpc-EUC-H',-'KSCpc-EUC-V',-'Katakana',-'NWP-H',-'NWP-V',-'RKSJ-H',-'RKSJ-V',-'Roman',-'UniCNS-UCS2-H',-'UniCNS-UCS2-V',-'UniCNS-UTF16-H',-'UniCNS-UTF16-V',-'UniCNS-UTF32-H',-'UniCNS-UTF32-V',-'UniCNS-UTF8-H',-'UniCNS-UTF8-V',-'UniGB-UCS2-H',-'UniGB-UCS2-V',-'UniGB-UTF16-H',-'UniGB-UTF16-V',-'UniGB-UTF32-H',-'UniGB-UTF32-V',-'UniGB-UTF8-H',-'UniGB-UTF8-V',-'UniJIS-UCS2-H',-'UniJIS-UCS2-HW-H',-'UniJIS-UCS2-HW-V',-'UniJIS-UCS2-V',-'UniJIS-UTF16-H',-'UniJIS-UTF16-V',-'UniJIS-UTF32-H',-'UniJIS-UTF32-V',-'UniJIS-UTF8-H',-'UniJIS-UTF8-V',-'UniJIS2004-UTF16-H',-'UniJIS2004-UTF16-V',-'UniJIS2004-UTF32-H',-'UniJIS2004-UTF32-V',-'UniJIS2004-UTF8-H',-'UniJIS2004-UTF8-V',-'UniJISPro-UCS2-HW-V',-'UniJISPro-UCS2-V',-'UniJISPro-UTF8-V',-'UniJISX0213-UTF32-H',-'UniJISX0213-UTF32-V',-'UniJISX02132004-UTF32-H',-'UniJISX02132004-UTF32-V',-'UniKS-UCS2-H',-'UniKS-UCS2-V',-'UniKS-UTF16-H',-'UniKS-UTF16-V',-'UniKS-UTF32-H',-'UniKS-UTF32-V',-'UniKS-UTF8-H',-'UniKS-UTF8-V',-'V',-'WP-Symbol'];--// CMap, not to be confused with TrueType's cmap.-var CMap = (function CMapClosure() {- function CMap(builtInCMap) {- // Codespace ranges are stored as follows:- // [[1BytePairs], [2BytePairs], [3BytePairs], [4BytePairs]]- // where nBytePairs are ranges e.g. [low1, high1, low2, high2, ...]- this.codespaceRanges = [[], [], [], []];- this.numCodespaceRanges = 0;- this.map = [];- this.vertical = false;- this.useCMap = null;- this.builtInCMap = builtInCMap;- }- CMap.prototype = {- addCodespaceRange: function(n, low, high) {- this.codespaceRanges[n - 1].push(low, high);- this.numCodespaceRanges++;+ properties.defaultWidth = defaultWidth;+ properties.widths = glyphsWidths;+ properties.defaultVMetrics = defaultVMetrics;+ properties.vmetrics = glyphsVMetrics;},- mapRange: function(low, high, dstLow) {- var lastByte = dstLow.length - 1;- while (low <= high) {- this.map[low] = dstLow;- // Only the last byte has to be incremented.- dstLow = dstLow.substr(0, lastByte) +- String.fromCharCode(dstLow.charCodeAt(lastByte) + 1);- ++low;- }- },+ isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {- mapRangeToArray: function(low, high, array) {- var i = 0;- while (low <= high) {- this.map[low] = array[i++];- ++low;- }+ // Simulating descriptor flags attribute+ var fontNameWoStyle = baseFontName.split('-')[0];+ return (fontNameWoStyle in serifFonts) ||+ (fontNameWoStyle.search(/serif/gi) !== -1);},- mapOne: function(src, dst) {- this.map[src] = dst;- },+ getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {+ var defaultWidth = 0, widths = [], monospace = false;- lookup: function(code) {- return this.map[code];- },+ var lookupName = stdFontMap[name] || name;- readCharCode: function(str, offset) {- var c = 0;- var codespaceRanges = this.codespaceRanges;- var codespaceRangesLen = this.codespaceRanges.length;- // 9.7.6.2 CMap Mapping- // The code length is at most 4.- for (var n = 0; n < codespaceRangesLen; n++) {- c = ((c << 8) | str.charCodeAt(offset + n)) >>> 0;- // Check each codespace range to see if it falls within.- var codespaceRange = codespaceRanges[n];- for (var k = 0, kk = codespaceRange.length; k < kk;) {- var low = codespaceRange[k++];- var high = codespaceRange[k++];- if (c >= low && c <= high) {- return [c, n + 1];- }+ if (!(lookupName in Metrics)) {+ // Use default fonts for looking up font metrics if the passed+ // font is not a base font+ if (this.isSerifFont(name)) {+ lookupName = 'Times-Roman';+ } else {+ lookupName = 'Helvetica';}}+ var glyphWidths = Metrics[lookupName];- return [0, 1];- }-- };- return CMap;-})();--var IdentityCMap = (function IdentityCMapClosure() {- function IdentityCMap(vertical, n) {- CMap.call(this);- this.vertical = vertical;- this.addCodespaceRange(n, 0, 0xffff);- this.mapRange(0, 0xffff, '\u0000');- }- Util.inherit(IdentityCMap, CMap, {});-- return IdentityCMap;-})();--var BinaryCMapReader = (function BinaryCMapReaderClosure() {- function fetchBinaryData(url) {- var nonBinaryRequest = PDFJS.disableWorker;- var request = new XMLHttpRequest();- request.open('GET', url, false);- if (!nonBinaryRequest) {- try {- request.responseType = 'arraybuffer';- nonBinaryRequest = request.responseType !== 'arraybuffer';- } catch (e) {- nonBinaryRequest = true;+ if (isNum(glyphWidths)) {+ defaultWidth = glyphWidths;+ monospace = true;+ } else {+ widths = glyphWidths;}- }- if (nonBinaryRequest && request.overrideMimeType) {- request.overrideMimeType('text/plain; charset=x-user-defined');- }- request.send(null);- if (request.status === 0 && /^https?:/i.test(url)) {- error('Unable to get binary cMap at: ' + url);- }- if (nonBinaryRequest) {- var data = Array.prototype.map.call(request.responseText, function (ch) {- return ch.charCodeAt(0) & 255;- });- return new Uint8Array(data);- }- return new Uint8Array(request.response);- }- function hexToInt(a, size) {- var n = 0;- for (var i = 0; i <= size; i++) {- n = (n << 8) | a[i];- }- return n >>> 0;- }-- function hexToStr(a, size) {- return String.fromCharCode.apply(null, a.subarray(0, size + 1));- }-- function addHex(a, b, size) {- var c = 0;- for (var i = size; i >= 0; i--) {- c += a[i] + b[i];- a[i] = c & 255;- c >>= 8;- }- }+ return {+ defaultWidth: defaultWidth,+ monospace: monospace,+ widths: widths+ };+ },- function incHex(a, size) {- var c = 1;- for (var i = size; i >= 0 && c > 0; i--) {- c += a[i];- a[i] = c & 255;- c >>= 8;- }- }+ translateFont: function PartialEvaluator_translateFont(dict,+ xref) {+ var baseDict = dict;+ var type = dict.get('Subtype');+ assertWellFormed(isName(type), 'invalid font Subtype');- var MAX_NUM_SIZE = 16;- var MAX_ENCODED_NUM_SIZE = 19; // ceil(MAX_NUM_SIZE * 7 / 8)+ var composite = false;+ if (type.name == 'Type0') {+ // If font is a composite+ // - get the descendant font+ // - set the type according to the descendant font+ // - get the FontDescriptor from the descendant font+ var df = dict.get('DescendantFonts');+ if (!df)+ error('Descendant fonts are not specified');- function BinaryCMapStream(data) {- this.buffer = data;- this.pos = 0;- this.end = data.length;- this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);- }+ dict = isArray(df) ? xref.fetchIfRef(df[0]) : df;- BinaryCMapStream.prototype = {- readByte: function () {- if (this.pos >= this.end) {- return -1;- }- return this.buffer[this.pos++];- },- readNumber: function () {- var n = 0;- var last;- do {- var b = this.readByte();- if (b < 0) {- error('unexpected EOF in bcmap');- }- last = !(b & 0x80);- n = (n << 7) | (b & 0x7F);- } while (!last);- return n;- },- readSigned: function () {- var n = this.readNumber();- return (n & 1) ? ~(n >>> 1) : n >>> 1;- },- readHex: function (num, size) {- num.set(this.buffer.subarray(this.pos,- this.pos + size + 1));- this.pos += size + 1;- },- readHexNumber: function (num, size) {- var last;- var stack = this.tmpBuf, sp = 0;- do {- var b = this.readByte();- if (b < 0) {- error('unexpected EOF in bcmap');- }- last = !(b & 0x80);- stack[sp++] = b & 0x7F;- } while (!last);- var i = size, buffer = 0, bufferSize = 0;- while (i >= 0) {- while (bufferSize < 8 && stack.length > 0) {- buffer = (stack[--sp] << bufferSize) | buffer;- bufferSize += 7;- }- num[i] = buffer & 255;- i--;- buffer >>= 8;- bufferSize -= 8;- }- },- readHexSigned: function (num, size) {- this.readHexNumber(num, size);- var sign = num[size] & 1 ? 255 : 0;- var c = 0;- for (var i = 0; i <= size; i++) {- c = ((c & 1) << 8) | num[i];- num[i] = (c >> 1) ^ sign;- }- },- readString: function () {- var len = this.readNumber();- var s = '';- for (var i = 0; i < len; i++) {- s += String.fromCharCode(this.readNumber());+ type = dict.get('Subtype');+ assertWellFormed(isName(type), 'invalid font Subtype');+ composite = true;}- return s;- }- };+ var maxCharIndex = composite ? 0xFFFF : 0xFF;++ var descriptor = dict.get('FontDescriptor');+ if (!descriptor) {+ if (type.name == 'Type3') {+ // FontDescriptor is only required for Type3 fonts when the document+ // is a tagged pdf. Create a barbebones one to get by.+ descriptor = new Dict();+ descriptor.set('FontName', new Name(type.name));+ } else {+ // Before PDF 1.5 if the font was one of the base 14 fonts, having a+ // FontDescriptor was not required.+ // This case is here for compatibility.+ var baseFontName = dict.get('BaseFont');+ if (!isName(baseFontName))+ error('Base font is not specified');- function processBinaryCMap(url, cMap, extend) {- var data = fetchBinaryData(url);- var stream = new BinaryCMapStream(data);+ // Using base font name as a font name.+ baseFontName = baseFontName.name.replace(/[,_]/g, '-');+ var metrics = this.getBaseFontMetrics(baseFontName);- var header = stream.readByte();- cMap.vertical = !!(header & 1);+ // Simulating descriptor flags attribute+ var fontNameWoStyle = baseFontName.split('-')[0];+ var flags = (+ this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |+ (metrics.monospace ? FontFlags.FixedPitch : 0) |+ (symbolsFonts[fontNameWoStyle] ? FontFlags.Symbolic :+ FontFlags.Nonsymbolic);- var useCMap = null;- var start = new Uint8Array(MAX_NUM_SIZE);- var end = new Uint8Array(MAX_NUM_SIZE);- var char = new Uint8Array(MAX_NUM_SIZE);- var charCode = new Uint8Array(MAX_NUM_SIZE);- var tmp = new Uint8Array(MAX_NUM_SIZE);- var code;+ var properties = {+ type: type.name,+ widths: metrics.widths,+ defaultWidth: metrics.defaultWidth,+ flags: flags,+ firstChar: 0,+ lastChar: maxCharIndex+ };+ this.extractDataStructures(dict, dict, xref, properties);- var b;- while ((b = stream.readByte()) >= 0) {- var type = b >> 5;- if (type === 7) { // metadata, e.g. comment or usecmap- switch (b & 0x1F) {- case 0:- stream.readString(); // skipping comment- break;- case 1:- useCMap = stream.readString();- break;+ return new Font(baseFontName, null, properties);}- continue;}- var sequence = !!(b & 0x10);- var dataSize = b & 15;- assert(dataSize + 1 <= MAX_NUM_SIZE);+ // According to the spec if 'FontDescriptor' is declared, 'FirstChar',+ // 'LastChar' and 'Widths' should exist too, but some PDF encoders seem+ // to ignore this rule when a variant of a standart font is used.+ // TODO Fill the width array depending on which of the base font this is+ // a variant.+ var firstChar = dict.get('FirstChar') || 0;+ var lastChar = dict.get('LastChar') || maxCharIndex;- var ucs2DataSize = 1;- var subitemsCount = stream.readNumber();- var i;- switch (type) {- case 0: // codespacerange- stream.readHex(start, dataSize);- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),- hexToInt(end, dataSize));- for (i = 1; i < subitemsCount; i++) {- incHex(end, dataSize);- stream.readHexNumber(start, dataSize);- addHex(start, end, dataSize);- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize),- hexToInt(end, dataSize));- }- break;- case 1: // notdefrange- stream.readHex(start, dataSize);- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- code = stream.readNumber();- // undefined range, skipping- for (i = 1; i < subitemsCount; i++) {- incHex(end, dataSize);- stream.readHexNumber(start, dataSize);- addHex(start, end, dataSize);- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- code = stream.readNumber();- // nop- }- break;- case 2: // cidchar- stream.readHex(char, dataSize);- code = stream.readNumber();- cMap.mapOne(hexToInt(char, dataSize), String.fromCharCode(code));- for (i = 1; i < subitemsCount; i++) {- incHex(char, dataSize);- if (!sequence) {- stream.readHexNumber(tmp, dataSize);- addHex(char, tmp, dataSize);- }- code = stream.readSigned() + (code + 1);- cMap.mapOne(hexToInt(char, dataSize), String.fromCharCode(code));- }- break;- case 3: // cidrange- stream.readHex(start, dataSize);- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- code = stream.readNumber();- cMap.mapRange(hexToInt(start, dataSize), hexToInt(end, dataSize),- String.fromCharCode(code));- for (i = 1; i < subitemsCount; i++) {- incHex(end, dataSize);- if (!sequence) {- stream.readHexNumber(start, dataSize);- addHex(start, end, dataSize);- } else {- start.set(end);- }- stream.readHexNumber(end, dataSize);- addHex(end, start, dataSize);- code = stream.readNumber();- cMap.mapRange(hexToInt(start, dataSize), hexToInt(end, dataSize),- String.fromCharCode(code));- }- break;- case 4: // bfchar- stream.readHex(char, ucs2DataSize);- stream.readHex(charCode, dataSize);- cMap.mapOne(hexToInt(char, ucs2DataSize),- hexToStr(charCode, dataSize));- for (i = 1; i < subitemsCount; i++) {- incHex(char, ucs2DataSize);- if (!sequence) {- stream.readHexNumber(tmp, ucs2DataSize);- addHex(char, tmp, ucs2DataSize);- }- incHex(charCode, dataSize);- stream.readHexSigned(tmp, dataSize);- addHex(charCode, tmp, dataSize);- cMap.mapOne(hexToInt(char, ucs2DataSize),- hexToStr(charCode, dataSize));- }- break;- case 5: // bfrange- stream.readHex(start, ucs2DataSize);- stream.readHexNumber(end, ucs2DataSize);- addHex(end, start, ucs2DataSize);- stream.readHex(charCode, dataSize);- cMap.mapRange(hexToInt(start, ucs2DataSize),- hexToInt(end, ucs2DataSize),- hexToStr(charCode, dataSize));- for (i = 1; i < subitemsCount; i++) {- incHex(end, ucs2DataSize);- if (!sequence) {- stream.readHexNumber(start, ucs2DataSize);- addHex(start, end, ucs2DataSize);- } else {- start.set(end);- }- stream.readHexNumber(end, ucs2DataSize);- addHex(end, start, ucs2DataSize);- stream.readHex(charCode, dataSize);- cMap.mapRange(hexToInt(start, ucs2DataSize),- hexToInt(end, ucs2DataSize),- hexToStr(charCode, dataSize));- }- break;- default:- error('Unknown type: ' + type);- break;+ var fontName = descriptor.get('FontName');+ var baseFont = dict.get('BaseFont');+ // Some bad pdf's have a string as the font name.+ if (isString(fontName)) {+ fontName = new Name(fontName);+ }+ if (isString(baseFont)) {+ baseFont = new Name(baseFont);}- }-- if (useCMap) {- extend(useCMap);- }- return cMap;- }-- function BinaryCMapReader() {}-- BinaryCMapReader.prototype = {- read: processBinaryCMap- };-- return BinaryCMapReader;-})();-var CMapFactory = (function CMapFactoryClosure() {- function strToInt(str) {- var a = 0;- for (var i = 0; i < str.length; i++) {- a = (a << 8) | str.charCodeAt(i);- }- return a >>> 0;- }+ if (type.name !== 'Type3') {+ var fontNameStr = fontName && fontName.name;+ var baseFontStr = baseFont && baseFont.name;+ if (fontNameStr !== baseFontStr) {+ info('The FontDescriptor\'s FontName is "' + fontNameStr ++ '" but should be the same as the Font\'s BaseFont "' ++ baseFontStr + '"');+ }+ }+ fontName = fontName || baseFont;- function expectString(obj) {- if (!isString(obj)) {- error('Malformed CMap: expected string.');- }- }+ assertWellFormed(isName(fontName), 'invalid font name');- function expectInt(obj) {- if (!isInt(obj)) {- error('Malformed CMap: expected int.');- }- }+ var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');+ if (fontFile) {+ if (fontFile.dict) {+ var subtype = fontFile.dict.get('Subtype');+ if (subtype)+ subtype = subtype.name;- function parseBfChar(cMap, lexer) {- while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- }- if (isCmd(obj, 'endbfchar')) {- return;- }- expectString(obj);- var src = strToInt(obj);- obj = lexer.getObj();- // TODO are /dstName used?- expectString(obj);- var dst = obj;- cMap.mapOne(src, dst);- }- }+ var length1 = fontFile.dict.get('Length1');- function parseBfRange(cMap, lexer) {- while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- }- if (isCmd(obj, 'endbfrange')) {- return;- }- expectString(obj);- var low = strToInt(obj);- obj = lexer.getObj();- expectString(obj);- var high = strToInt(obj);- obj = lexer.getObj();- if (isInt(obj) || isString(obj)) {- var dstLow = isInt(obj) ? String.fromCharCode(obj) : obj;- cMap.mapRange(low, high, dstLow);- } else if (isCmd(obj, '[')) {- obj = lexer.getObj();- var array = [];- while (!isCmd(obj, ']') && !isEOF(obj)) {- array.push(obj);- obj = lexer.getObj();+ var length2 = fontFile.dict.get('Length2');}- cMap.mapRangeToArray(low, high, array);- } else {- break;}- }- error('Invalid bf range.');- }- function parseCidChar(cMap, lexer) {- while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- }- if (isCmd(obj, 'endcidchar')) {- return;- }- expectString(obj);- var src = strToInt(obj);- obj = lexer.getObj();- expectInt(obj);- var dst = String.fromCharCode(obj);- cMap.mapOne(src, dst);- }- }+ var properties = {+ type: type.name,+ subtype: subtype,+ file: fontFile,+ length1: length1,+ length2: length2,+ loadedName: baseDict.loadedName,+ composite: composite,+ wideChars: composite,+ fixedPitch: false,+ fontMatrix: dict.get('FontMatrix') || FONT_IDENTITY_MATRIX,+ firstChar: firstChar || 0,+ lastChar: lastChar || maxCharIndex,+ bbox: descriptor.get('FontBBox'),+ ascent: descriptor.get('Ascent'),+ descent: descriptor.get('Descent'),+ xHeight: descriptor.get('XHeight'),+ capHeight: descriptor.get('CapHeight'),+ flags: descriptor.get('Flags'),+ italicAngle: descriptor.get('ItalicAngle'),+ coded: false+ };- function parseCidRange(cMap, lexer) {- while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- }- if (isCmd(obj, 'endcidrange')) {- return;+ if (composite) {+ var cidEncoding = baseDict.get('Encoding');+ if (isName(cidEncoding)) {+ properties.cidEncoding = cidEncoding.name;+ properties.vertical = /-V$/.test(cidEncoding.name);+ }}- expectString(obj);- var low = strToInt(obj);- obj = lexer.getObj();- expectString(obj);- var high = strToInt(obj);- obj = lexer.getObj();- expectInt(obj);- var dstLow = String.fromCharCode(obj);- cMap.mapRange(low, high, dstLow);- }- }+ this.extractWidths(dict, xref, descriptor, properties);+ this.extractDataStructures(dict, baseDict, xref, properties);- function parseCodespaceRange(cMap, lexer) {- while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- }- if (isCmd(obj, 'endcodespacerange')) {- return;- }- if (!isString(obj)) {- break;- }- var low = strToInt(obj);- obj = lexer.getObj();- if (!isString(obj)) {- break;+ if (type.name === 'Type3') {+ properties.coded = true;}- var high = strToInt(obj);- cMap.addCodespaceRange(obj.length, low, high);- }- error('Invalid codespace range.');- }-- function parseWMode(cMap, lexer) {- var obj = lexer.getObj();- if (isInt(obj)) {- cMap.vertical = !!obj;- }- }- function parseCMap(cMap, lexer, builtInCMapParams, useCMap) {- var previous;- var embededUseCMap;- objLoop: while (true) {- var obj = lexer.getObj();- if (isEOF(obj)) {- break;- } else if (isName(obj)) {- if (obj.name === 'WMode') {- parseWMode(cMap, lexer);- }- previous = obj;- } else if (isCmd(obj)) {- switch (obj.cmd) {- case 'endcmap':- break objLoop;- case 'usecmap':- if (isName(previous)) {- embededUseCMap = previous.name;- }- break;- case 'begincodespacerange':- parseCodespaceRange(cMap, lexer);- break;- case 'beginbfchar':- parseBfChar(cMap, lexer);- break;- case 'begincidchar':- parseCidChar(cMap, lexer);- break;- case 'beginbfrange':- parseBfRange(cMap, lexer);- break;- case 'begincidrange':- parseCidRange(cMap, lexer);- break;- }- }+ return new Font(fontName.name, fontFile, properties);}+ };- if (!useCMap && embededUseCMap) {- // Load the usecmap definition from the file only if there wasn't one- // specified.- useCMap = embededUseCMap;- }- if (useCMap) {- extendCMap(cMap, builtInCMapParams, useCMap);- }- }+ PartialEvaluator.optimizeQueue =+ function PartialEvaluator_optimizeQueue(queue) {- function extendCMap(cMap, builtInCMapParams, useCMap) {- cMap.useCMap = createBuiltInCMap(useCMap, builtInCMapParams);- // If there aren't any code space ranges defined clone all the parent ones- // into this cMap.- if (cMap.numCodespaceRanges === 0) {- var useCodespaceRanges = cMap.useCMap.codespaceRanges;- for (var i = 0; i < useCodespaceRanges.length; i++) {- cMap.codespaceRanges[i] = useCodespaceRanges[i].slice();- }- cMap.numCodespaceRanges = cMap.useCMap.numCodespaceRanges;- }- // Merge the map into the current one, making sure not to override- // any previously defined entries.- for (var key in cMap.useCMap.map) {- if (key in cMap.map) {- continue;+ var fnArray = queue.fnArray, argsArray = queue.argsArray;+ // grouping paintInlineImageXObject's into paintInlineImageXObjectGroup+ // searching for (save, transform, paintInlineImageXObject, restore)++ var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;+ var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;+ var MAX_WIDTH = 1000;+ var IMAGE_PADDING = 1;+ for (var i = 0, ii = fnArray.length; i < ii; i++) {+ if (fnArray[i] === 'paintInlineImageXObject' &&+ fnArray[i - 2] === 'save' && fnArray[i - 1] === 'transform' &&+ fnArray[i + 1] === 'restore') {+ var j = i - 2;+ for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {+ }+ var count = Math.min((i - j) >> 2,+ MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);+ if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {+ continue;+ }+ // assuming that heights of those image is too small (~1 pixel)+ // packing as much as possible by lines+ var maxX = 0;+ var map = [], maxLineHeight = 0;+ var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;+ for (var q = 0; q < count; q++) {+ var transform = argsArray[j + (q << 2) + 1];+ var img = argsArray[j + (q << 2) + 2][0];+ if (currentX + img.width > MAX_WIDTH) {+ // starting new line+ maxX = Math.max(maxX, currentX);+ currentY += maxLineHeight + 2 * IMAGE_PADDING;+ currentX = 0;+ maxLineHeight = 0;+ }+ map.push({+ transform: transform,+ x: currentX, y: currentY,+ w: img.width, h: img.height+ });+ currentX += img.width + 2 * IMAGE_PADDING;+ maxLineHeight = Math.max(maxLineHeight, img.height);+ }+ var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;+ var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;+ var imgData = new Uint8Array(imgWidth * imgHeight * 4);+ var imgRowSize = imgWidth << 2;+ for (var q = 0; q < count; q++) {+ var data = argsArray[j + (q << 2) + 2][0].data;+ // copy image by lines and extends pixels into padding+ var rowSize = map[q].w << 2;+ var dataOffset = 0;+ var offset = (map[q].x + map[q].y * imgWidth) << 2;+ imgData.set(+ data.subarray(0, rowSize), offset - imgRowSize);+ for (var k = 0, kk = map[q].h; k < kk; k++) {+ imgData.set(+ data.subarray(dataOffset, dataOffset + rowSize), offset);+ dataOffset += rowSize;+ offset += imgRowSize;+ }+ imgData.set(+ data.subarray(dataOffset - rowSize, dataOffset), offset);+ while (offset >= 0) {+ data[offset - 4] = data[offset];+ data[offset - 3] = data[offset + 1];+ data[offset - 2] = data[offset + 2];+ data[offset - 1] = data[offset + 3];+ data[offset + rowSize] = data[offset + rowSize - 4];+ data[offset + rowSize + 1] = data[offset + rowSize - 3];+ data[offset + rowSize + 2] = data[offset + rowSize - 2];+ data[offset + rowSize + 3] = data[offset + rowSize - 1];+ offset -= imgRowSize;+ }+ }+ // replacing queue items+ fnArray.splice(j, count * 4, ['paintInlineImageXObjectGroup']);+ argsArray.splice(j, count * 4,+ [{width: imgWidth, height: imgHeight, data: imgData}, map]);+ i = j;+ ii = fnArray.length;+ }+ }+ // grouping paintImageMaskXObject's into paintImageMaskXObjectGroup+ // searching for (save, transform, paintImageMaskXObject, restore)++ var MIN_IMAGES_IN_MASKS_BLOCK = 10;+ var MAX_IMAGES_IN_MASKS_BLOCK = 100;+ for (var i = 0, ii = fnArray.length; i < ii; i++) {+ if (fnArray[i] === 'paintImageMaskXObject' &&+ fnArray[i - 2] === 'save' && fnArray[i - 1] === 'transform' &&+ fnArray[i + 1] === 'restore') {+ var j = i - 2;+ for (i += 2; i < ii && fnArray[i - 4] === fnArray[i]; i++) {+ }+ var count = Math.min((i - j) >> 2,+ MAX_IMAGES_IN_MASKS_BLOCK);+ if (count < MIN_IMAGES_IN_MASKS_BLOCK) {+ continue;+ }+ var images = [];+ for (var q = 0; q < count; q++) {+ var transform = argsArray[j + (q << 2) + 1];+ var maskParams = argsArray[j + (q << 2) + 2][0];+ images.push({data: maskParams.data, width: maskParams.width,+ height: maskParams.height, transform: transform});+ }+ // replacing queue items+ fnArray.splice(j, count * 4, ['paintImageMaskXObjectGroup']);+ argsArray.splice(j, count * 4, [images]);+ i = j;+ ii = fnArray.length;}- cMap.map[key] = cMap.useCMap.map[key];}- }-- function parseBinaryCMap(name, builtInCMapParams) {- var url = builtInCMapParams.url + name + '.bcmap';- var cMap = new CMap(true);- new BinaryCMapReader().read(url, cMap, function (useCMap) {- extendCMap(cMap, builtInCMapParams, useCMap);- });- return cMap;- }+ };- function createBuiltInCMap(name, builtInCMapParams) {- if (name === 'Identity-H') {- return new IdentityCMap(false, 2);- } else if (name === 'Identity-V') {- return new IdentityCMap(true, 2);- }- if (BUILT_IN_CMAPS.indexOf(name) === -1) {- error('Unknown cMap name: ' + name);- }- assert (builtInCMapParams, 'buildin cmap parameters are not provided');- if (builtInCMapParams.packed) {- return parseBinaryCMap(name, builtInCMapParams);- }+ return PartialEvaluator;+})();- var request = new XMLHttpRequest();- var url = builtInCMapParams.url + name;- request.open('GET', url, false);- request.send(null);- if (request.status === 0 && /^https?:/i.test(url)) {- error('Unable to get cMap at: ' + url);- }- var cMap = new CMap(true);- var lexer = new Lexer(new StringStream(request.responseText));- parseCMap(cMap, lexer, builtInCMapParams, null);- return cMap;+var EvalState = (function EvalStateClosure() {+ function EvalState() {+ // Are soft masks and alpha values shapes or opacities?+ this.alphaIsShape = false;+ this.fontSize = 0;+ this.textMatrix = IDENTITY_MATRIX;+ this.leading = 0;+ // Start of text line (in text coordinates)+ this.lineX = 0;+ this.lineY = 0;+ // Character and word spacing+ this.charSpacing = 0;+ this.wordSpacing = 0;+ this.textHScale = 1;+ // Color spaces+ this.fillColorSpace = null;+ this.strokeColorSpace = null;}-- return {- create: function (encoding, builtInCMapParams, useCMap) {- if (isName(encoding)) {- return createBuiltInCMap(encoding.name, builtInCMapParams);- } else if (isStream(encoding)) {- var cMap = new CMap();- var lexer = new Lexer(encoding);- try {- parseCMap(cMap, lexer, builtInCMapParams, useCMap);- } catch (e) {- warn('Invalid CMap data. ' + e);- }- return cMap;- }- error('Encoding required.');- }+ EvalState.prototype = {};+ return EvalState;})();+// Unicode Private Use Area-var PRIVATE_USE_OFFSET_START = 0xE000;-var PRIVATE_USE_OFFSET_END = 0xF8FF;-var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;+var CMAP_GLYPH_OFFSET = 0xE000;+var GLYPH_AREA_SIZE = 0x1900;+var SYMBOLIC_FONT_GLYPH_OFFSET = 0xF000;// PDF Glyph Space Units are one Thousandth of a TextSpace Unit// except for Type 3 fonts@@ -18341,6 +17920,10 @@ var HINTING_ENABLED = false;// to control analysis of seac charstrings.var SEAC_ANALYSIS_ENABLED = false;+var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];++PDFJS.disableFontFace = false;+var FontFlags = {FixedPitch: 1,Serif: 2,@@ -18459,7 +18042,7 @@ var Encodings = {'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine','Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot','radical', 'florin', 'approxequal', 'Delta', 'guillemotleft',- 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE',+ 'guillemotright', 'ellipsis', '', 'Agrave', 'Atilde', 'Otilde', 'OE','oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft','quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction','currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl',@@ -18511,7 +18094,7 @@ var Encodings = {'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft','quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash','emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet',- 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling',+ 'zcaron', 'Ydieresis', '', 'exclamdown', 'cent', 'sterling','currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright','ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered','macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute',@@ -18528,8 +18111,8 @@ var Encodings = {'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash','ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn','ydieresis'],- SymbolSetEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '',- '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',+ symbolsEncoding: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '',+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '','space', 'exclam', 'universal', 'numbersign', 'existential', 'percent','ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus','comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',@@ -18673,7 +18256,7 @@ var nonStdFontMap = {'MS-PMincho': 'MS PMincho','MS-PMincho-Bold': 'MS PMincho-Bold','MS-PMincho-BoldItalic': 'MS PMincho-BoldItalic',- 'MS-PMincho-Italic': 'MS PMincho-Italic'+ 'MS-PMincho-Italic': 'MS PMincho-Italic',};var serifFonts = {@@ -18717,7 +18300,7 @@ var serifFonts = {'Seagull': true, 'Sistina': true, 'Souvenir': true,'STIX': true, 'Stone Informal': true, 'Stone Serif': true,'Sylfaen': true, 'Times': true, 'Trajan': true,- 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,+ 'Trinité': true, 'Trump Mediaeval': true, 'Utopia': true,'Vale Type': true, 'Bitstream Vera': true, 'Vera Serif': true,'Versailles': true, 'Wanted': true, 'Weiss': true,'Wide Latin': true, 'Windsor': true, 'XITS': true@@ -18727,101 +18310,313 @@ var symbolsFonts = {'Dingbats': true, 'Symbol': true, 'ZapfDingbats': true};-// Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID fonts-// but does not embed the CID to GID mapping. The mapping is incomplete for all-// glyphs, but common for some set of the standard fonts.-var GlyphMapForStandardFonts = {- '2': 10, '3': 32, '4': 33, '5': 34, '6': 35, '7': 36, '8': 37, '9': 38,- '10': 39, '11': 40, '12': 41, '13': 42, '14': 43, '15': 44, '16': 173,- '17': 46, '18': 47, '19': 48, '20': 49, '21': 50, '22': 51, '23': 52,- '24': 53, '25': 54, '26': 55, '27': 56, '28': 57, '29': 58, '30': 894,- '31': 60, '32': 61, '33': 62, '34': 63, '35': 64, '36': 65, '37': 66,- '38': 67, '39': 68, '40': 69, '41': 70, '42': 71, '43': 72, '44': 73,- '45': 74, '46': 75, '47': 76, '48': 77, '49': 78, '50': 79, '51': 80,- '52': 81, '53': 82, '54': 83, '55': 84, '56': 85, '57': 86, '58': 87,- '59': 88, '60': 89, '61': 90, '62': 91, '63': 92, '64': 93, '65': 94,- '66': 95, '67': 96, '68': 97, '69': 98, '70': 99, '71': 100, '72': 101,- '73': 102, '74': 103, '75': 104, '76': 105, '77': 106, '78': 107, '79': 108,- '80': 109, '81': 110, '82': 111, '83': 112, '84': 113, '85': 114, '86': 115,- '87': 116, '88': 117, '89': 118, '90': 119, '91': 120, '92': 121, '93': 122,- '94': 123, '95': 124, '96': 125, '97': 126, '98': 196, '99': 197, '100': 199,- '101': 201, '102': 209, '103': 214, '104': 220, '105': 225, '106': 224,- '107': 226, '108': 228, '109': 227, '110': 229, '111': 231, '112': 233,- '113': 232, '114': 234, '115': 235, '116': 237, '117': 236, '118': 238,- '119': 239, '120': 241, '121': 243, '122': 242, '123': 244, '124': 246,- '125': 245, '126': 250, '127': 249, '128': 251, '129': 252, '130': 8224,- '131': 176, '132': 162, '133': 163, '134': 167, '135': 8226, '136': 182,- '137': 223, '138': 174, '139': 169, '140': 8482, '141': 180, '142': 168,- '143': 8800, '144': 198, '145': 216, '146': 8734, '147': 177, '148': 8804,- '149': 8805, '150': 165, '151': 181, '152': 8706, '153': 8721, '154': 8719,- '156': 8747, '157': 170, '158': 186, '159': 8486, '160': 230, '161': 248,- '162': 191, '163': 161, '164': 172, '165': 8730, '166': 402, '167': 8776,- '168': 8710, '169': 171, '170': 187, '171': 8230, '210': 218, '305': 963,- '306': 964, '307': 966, '308': 8215, '309': 8252, '310': 8319, '311': 8359,- '312': 8592, '313': 8593, '337': 9552, '493': 1039, '494': 1040, '705': 1524,- '706': 8362, '710': 64288, '711': 64298, '759': 1617, '761': 1776,- '763': 1778, '775': 1652, '777': 1764, '778': 1780, '779': 1781, '780': 1782,- '782': 771, '783': 64726, '786': 8363, '788': 8532, '790': 768, '791': 769,- '792': 768, '795': 803, '797': 64336, '798': 64337, '799': 64342,- '800': 64343, '801': 64344, '802': 64345, '803': 64362, '804': 64363,- '805': 64364, '2424': 7821, '2425': 7822, '2426': 7823, '2427': 7824,- '2428': 7825, '2429': 7826, '2430': 7827, '2433': 7682, '2678': 8045,- '2679': 8046, '2830': 1552, '2838': 686, '2840': 751, '2842': 753,- '2843': 754, '2844': 755, '2846': 757, '2856': 767, '2857': 848, '2858': 849,- '2862': 853, '2863': 854, '2864': 855, '2865': 861, '2866': 862, '2906': 7460,- '2908': 7462, '2909': 7463, '2910': 7464, '2912': 7466, '2913': 7467,- '2914': 7468, '2916': 7470, '2917': 7471, '2918': 7472, '2920': 7474,- '2921': 7475, '2922': 7476, '2924': 7478, '2925': 7479, '2926': 7480,- '2928': 7482, '2929': 7483, '2930': 7484, '2932': 7486, '2933': 7487,- '2934': 7488, '2936': 7490, '2937': 7491, '2938': 7492, '2940': 7494,- '2941': 7495, '2942': 7496, '2944': 7498, '2946': 7500, '2948': 7502,- '2950': 7504, '2951': 7505, '2952': 7506, '2954': 7508, '2955': 7509,- '2956': 7510, '2958': 7512, '2959': 7513, '2960': 7514, '2962': 7516,- '2963': 7517, '2964': 7518, '2966': 7520, '2967': 7521, '2968': 7522,- '2970': 7524, '2971': 7525, '2972': 7526, '2974': 7528, '2975': 7529,- '2976': 7530, '2978': 1537, '2979': 1538, '2980': 1539, '2982': 1549,- '2983': 1551, '2984': 1552, '2986': 1554, '2987': 1555, '2988': 1556,- '2990': 1623, '2991': 1624, '2995': 1775, '2999': 1791, '3002': 64290,- '3003': 64291, '3004': 64292, '3006': 64294, '3007': 64295, '3008': 64296,- '3011': 1900, '3014': 8223, '3015': 8244, '3017': 7532, '3018': 7533,- '3019': 7534, '3075': 7590, '3076': 7591, '3079': 7594, '3080': 7595,- '3083': 7598, '3084': 7599, '3087': 7602, '3088': 7603, '3091': 7606,- '3092': 7607, '3095': 7610, '3096': 7611, '3099': 7614, '3100': 7615,- '3103': 7618, '3104': 7619, '3107': 8337, '3108': 8338, '3116': 1884,- '3119': 1885, '3120': 1885, '3123': 1886, '3124': 1886, '3127': 1887,- '3128': 1887, '3131': 1888, '3132': 1888, '3135': 1889, '3136': 1889,- '3139': 1890, '3140': 1890, '3143': 1891, '3144': 1891, '3147': 1892,- '3148': 1892, '3153': 580, '3154': 581, '3157': 584, '3158': 585, '3161': 588,- '3162': 589, '3165': 891, '3166': 892, '3169': 1274, '3170': 1275,- '3173': 1278, '3174': 1279, '3181': 7622, '3182': 7623, '3282': 11799,- '3316': 578, '3379': 42785, '3393': 1159, '3416': 8377+var CMapConverterList = {+ 'H': jis7ToUnicode,+ 'V': jis7ToUnicode,+ 'EUC-H': eucjpToUnicode,+ 'EUC-V': eucjpToUnicode,+ '83pv-RKSJ-H': sjis83pvToUnicode,+ '90pv-RKSJ-H': sjis90pvToUnicode,+ '90ms-RKSJ-H': sjisToUnicode,+ '90ms-RKSJ-V': sjisToUnicode,+ '90msp-RKSJ-H': sjisToUnicode,+ '90msp-RKSJ-V': sjisToUnicode,+ 'GBK-EUC-H': gbkToUnicode,+ 'B5pc-H': big5ToUnicode,+ 'ETenms-B5-H': big5ToUnicode,+ 'ETenms-B5-V': big5ToUnicode,+};++// CMaps using Hankaku (Halfwidth) Latin glyphs instead of proportional one.+// We need to distinguish them to get correct widths from CIDFont dicts.+var HalfwidthCMaps = {+ 'H': true,+ 'V': true,+ 'EUC-H': true,+ 'EUC-V': true,+ '90ms-RKSJ-H': true,+ '90ms-RKSJ-V': true,+ 'UniJIS-UCS2-HW-H': true,+ 'UniJIS-UCS2-HW-V': true};+var decodeBytes;+if (typeof TextDecoder !== 'undefined') {+ // The encodings supported by TextDecoder can be found at:+ // http://encoding.spec.whatwg.org/#concept-encoding-get+ decodeBytes = function(bytes, encoding, fatal) {+ return new TextDecoder(encoding, {fatal: !!fatal}).decode(bytes);+ };+} else if (typeof FileReaderSync !== 'undefined') {+ decodeBytes = function(bytes, encoding) {+ return new FileReaderSync().readAsText(new Blob([bytes]), encoding);+ };+} else {+ // Clear the list so that decodeBytes will never be called.+ CMapConverterList = {};+}++function jis7ToUnicode(str) {+ var bytes = stringToBytes(str);+ var length = bytes.length;+ for (var i = 0; i < length; ++i) {+ bytes[i] |= 0x80;+ }+ return decodeBytes(bytes, 'euc-jp');+}++function eucjpToUnicode(str) {+ return decodeBytes(stringToBytes(str), 'euc-jp');+}++function sjisToUnicode(str) {+ return decodeBytes(stringToBytes(str), 'shift_jis');+}++function sjis83pvToUnicode(str) {+ var bytes = stringToBytes(str);+ try {+ // TODO: 83pv has incompatible mappings in ed40..ee9c range.+ return decodeBytes(bytes, 'shift_jis', true);+ } catch (e) {+ TODO('Unsupported 83pv character found');+ // Just retry without checking errors for now.+ return decodeBytes(bytes, 'shift_jis');+ }+}++function sjis90pvToUnicode(str) {+ var bytes = stringToBytes(str);+ try {+ // TODO: 90pv has incompatible mappings in 8740..879c and eb41..ee9c.+ return decodeBytes(bytes, 'shift_jis', true);+ } catch (e) {+ TODO('Unsupported 90pv character found');+ // Just retry without checking errors for now.+ return decodeBytes(bytes, 'shift_jis');+ }+}++function gbkToUnicode(str) {+ return decodeBytes(stringToBytes(str), 'gbk');+}++function big5ToUnicode(str) {+ return decodeBytes(stringToBytes(str), 'big5');+}+// Some characters, e.g. copyrightserif, mapped to the private use area and// might not be displayed using standard fonts. Mapping/hacking well-known chars// to the similar equivalents in the normal characters range.-function mapSpecialUnicodeValues(code) {- if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials unicode block.- return 0;- }+function mapPrivateUseChars(code) {switch (code) {case 0xF8E9: // copyrightsanscase 0xF6D9: // copyrightserifreturn 0x00A9; // copyright-- case 0xF8E8: // registersans- case 0xF6DA: // registerserif- return 0x00AE; // registered-- case 0xF8EA: // trademarksans- case 0xF6DB: // trademarkserif- return 0x2122; // trademark-default:return code;}}+var FontLoader = {+ loadingContext: {+ requests: [],+ nextRequestId: 0+ },++ isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {+ if (isWorker)+ return false;++ // User agent string sniffing is bad, but there is no reliable way to tell+ // if font is fully loaded and ready to be used with canvas.+ var userAgent = window.navigator.userAgent;+ var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);+ if (m && m[1] >= 14)+ return true;+ // TODO other browsers+ return false;+ })(),++ bind: function fontLoaderBind(fonts, callback) {+ assert(!isWorker, 'bind() shall be called from main thread');++ var rules = [], fontsToLoad = [];+ for (var i = 0, ii = fonts.length; i < ii; i++) {+ var font = fonts[i];++ // Add the font to the DOM only once or skip if the font+ // is already loaded.+ if (font.attached || font.loading === false) {+ continue;+ }+ font.attached = true;++ var rule = font.bindDOM();+ if (rule) {+ rules.push(rule);+ fontsToLoad.push(font);+ }+ }++ var request = FontLoader.queueLoadingCallback(callback);+ if (rules.length > 0 && !this.isSyncFontLoadingSupported) {+ FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);+ } else {+ request.complete();+ }+ },++ queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {+ function LoadLoader_completeRequest() {+ assert(!request.end, 'completeRequest() cannot be called twice');+ request.end = Date.now();++ // sending all completed requests in order how they were queued+ while (context.requests.length > 0 && context.requests[0].end) {+ var otherRequest = context.requests.shift();+ setTimeout(otherRequest.callback, 0);+ }+ }++ var context = FontLoader.loadingContext;+ var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);+ var request = {+ id: requestId,+ complete: LoadLoader_completeRequest,+ callback: callback,+ started: Date.now()+ };+ context.requests.push(request);+ return request;+ },++ // Set things up so that at least one pdfjsFontLoad event is+ // dispatched when all the @font-face |rules| for |fonts| have been+ // loaded in a subdocument. It's expected that the load of |rules|+ // has already started in this (outer) document, so that they should+ // be ordered before the load in the subdocument.+ prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,+ fonts,+ request) {+ /** Hack begin */+ // There's no event when a font has finished downloading so the+ // following code is a dirty hack to 'guess' when a font is+ // ready. This code will be obsoleted by Mozilla bug 471915.+ //+ // The only reliable way to know if a font is loaded in Gecko+ // (at the moment) is document.onload in a document with+ // a @font-face rule defined in a "static" stylesheet. We use a+ // subdocument in an <iframe>, set up properly, to know when+ // our @font-face rule was loaded. However, the subdocument and+ // outer document can't share CSS rules, so the inner document+ // is only part of the puzzle. The second piece is an invisible+ // div created in order to force loading of the @font-face in+ // the *outer* document. (The font still needs to be loaded for+ // its metrics, for reflow). We create the div first for the+ // outer document, then create the iframe. Unless something+ // goes really wonkily, we expect the @font-face for the outer+ // document to be processed before the inner. That's still+ // fragile, but seems to work in practice.+ //+ // The postMessage() hackery was added to work around chrome bug+ // 82402.++ var requestId = request.id;+ // Validate the requestId parameter -- the value used to construct HTML.+ if (!/^[\w\-]+$/.test(requestId)) {+ error('Invalid request id: ' + requestId);++ // Normally the error-function throws. But if a malicious code+ // intercepts the function call then the return is needed.+ return;+ }++ var names = [];+ for (var i = 0, ii = fonts.length; i < ii; i++)+ names.push(fonts[i].loadedName);++ // Validate the names parameter -- the values can used to construct HTML.+ if (!/^\w+$/.test(names.join(''))) {+ error('Invalid font name(s): ' + names.join());++ // Normally the error-function throws. But if a malicious code+ // intercepts the function call then the return is needed.+ return;+ }++ var div = document.createElement('div');+ div.setAttribute('style',+ 'visibility: hidden;' ++ 'width: 10px; height: 10px;' ++ 'position: absolute; top: 0px; left: 0px;');+ var html = '';+ for (var i = 0, ii = names.length; i < ii; ++i) {+ html += '<span style="font-family:' + names[i] + '">Hi</span>';+ }+ div.innerHTML = html;+ document.body.appendChild(div);++ window.addEventListener(+ 'message',+ function fontLoaderMessage(e) {+ if (e.data !== requestId)+ return;+ for (var i = 0, ii = fonts.length; i < ii; ++i) {+ var font = fonts[i];+ font.loading = false;+ }+ request.complete();+ // cleanup+ if (frame) {+ document.body.removeChild(frame);+ }+ window.removeEventListener('message', fontLoaderMessage, false);+ },+ false);++ // XXX we should have a time-out here too, and maybe fire+ // pdfjsFontLoadFailed?+ var src = '<!DOCTYPE HTML><html><head><meta charset="utf-8">';+ src += '<style type="text/css">';+ for (var i = 0, ii = rules.length; i < ii; ++i) {+ src += rules[i];+ }+ src += '</style>';+ src += '<script type="application/javascript">';+ src += ' window.onload = function fontLoaderOnload() {\n';+ src += ' parent.postMessage("' + requestId + '", "*");\n';+ // Chrome stuck on loading (see chrome issue 145227) - resetting url+ src += ' window.location = "about:blank";\n';+ src += ' }';+ // Hack so the end script tag isn't counted if this is inline JS.+ src += '</scr' + 'ipt></head><body>';+ for (var i = 0, ii = names.length; i < ii; ++i) {+ src += '<p style="font-family:\'' + names[i] + '\'">Hi</p>';+ }+ src += '</body></html>';++ var MAX_IFRAME_SRC_LENGTH = 1000000, IFRAME_TIMEOUT = 2000;+ // Chrome fails for long src attributes (see issue 174023)+ if (src.length > MAX_IFRAME_SRC_LENGTH) {+ // ... waiting for some fixed period of time instead+ window.setTimeout(function() {+ window.postMessage(requestId, '*');+ }, IFRAME_TIMEOUT);+ return;+ }++ var frame = document.createElement('iframe');+ frame.src = 'data:text/html,' + src;+ frame.setAttribute('style',+ 'visibility: hidden;' ++ 'width: 10px; height: 10px;' ++ 'position: absolute; top: 0px; left: 0px;');+ document.body.appendChild(frame);+ /** Hack end */+ }+};+var UnicodeRanges = [{ 'begin': 0x0000, 'end': 0x007F }, // Basic Latin{ 'begin': 0x0080, 'end': 0x00FF }, // Latin-1 Supplement@@ -18989,25 +18784,28 @@ var MacStandardGlyphOrdering = [function getUnicodeRangeFor(value) {for (var i = 0, ii = UnicodeRanges.length; i < ii; i++) {var range = UnicodeRanges[i];- if (value >= range.begin && value < range.end) {+ if (value >= range.begin && value < range.end)return i;- }}return -1;}function isRTLRangeFor(value) {var range = UnicodeRanges[13];- if (value >= range.begin && value < range.end) {+ if (value >= range.begin && value < range.end)return true;- }range = UnicodeRanges[11];- if (value >= range.begin && value < range.end) {+ if (value >= range.begin && value < range.end)return true;- }return false;}+function isSpecialUnicode(unicode) {+ return (unicode <= 0x1F || (unicode >= 127 && unicode < GLYPH_AREA_SIZE)) ||+ (unicode >= CMAP_GLYPH_OFFSET &&+ unicode < CMAP_GLYPH_OFFSET + GLYPH_AREA_SIZE);+}+// The normalization table is obtained by filtering the Unicode characters// database with <compat> entries.var NormalizedUnicodes = {@@ -20393,16 +20191,31 @@ var NormalizedUnicodes = {function reverseIfRtl(chars) {var charsLength = chars.length;//reverse an arabic ligature- if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0))) {+ if (charsLength <= 1 || !isRTLRangeFor(chars.charCodeAt(0)))return chars;- }+var s = '';- for (var ii = charsLength - 1; ii >= 0; ii--) {+ for (var ii = charsLength - 1; ii >= 0; ii--)s += chars[ii];- }return s;}+function fontCharsToUnicode(charCodes, font) {+ var glyphs = font.charsToGlyphs(charCodes);+ var result = '';+ for (var i = 0, ii = glyphs.length; i < ii; i++) {+ var glyph = glyphs[i];+ if (!glyph)+ continue;++ var glyphUnicode = glyph.unicode;+ if (glyphUnicode in NormalizedUnicodes)+ glyphUnicode = NormalizedUnicodes[glyphUnicode];+ result += reverseIfRtl(glyphUnicode);+ }+ return result;+}+function adjustWidths(properties) {if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {return;@@ -20416,29 +20229,6 @@ function adjustWidths(properties) {properties.defaultWidth *= scale;}-var Glyph = (function GlyphClosure() {- function Glyph(fontChar, unicode, accent, width, vmetric, operatorList) {- this.fontChar = fontChar;- this.unicode = unicode;- this.accent = accent;- this.width = width;- this.vmetric = vmetric;- this.operatorList = operatorList;- }-- Glyph.prototype.matchesForCache =- function(fontChar, unicode, accent, width, vmetric, operatorList) {- return this.fontChar === fontChar &&- this.unicode === unicode &&- this.accent === accent &&- this.width === width &&- this.vmetric === vmetric &&- this.operatorList === operatorList;- };-- return Glyph;-})();-/*** 'Font' is the class the outside world should use, it encapsulate all the font* decoding logics whatever type it is (assuming the font type is supported).@@ -20449,7 +20239,14 @@ var Glyph = (function GlyphClosure() {*/var Font = (function FontClosure() {function Font(name, file, properties) {- var charCode;+ if (arguments.length === 1) {+ // importing translated data+ var data = arguments[0];+ for (var i in data) {+ this[i] = data[i];+ }+ return;+ }this.name = name;this.loadedName = properties.loadedName;@@ -20457,8 +20254,6 @@ var Font = (function FontClosure() {this.loadCharProcs = properties.coded;this.sizes = [];- this.glyphCache = {};-var names = name.split('+');names = names.length > 1 ? names[1] : names[0];names = names.split(/[-,_]/g)[0];@@ -20469,33 +20264,24 @@ var Font = (function FontClosure() {var type = properties.type;this.type = type;- this.fallbackName = (this.isMonospace ? 'monospace' :- (this.isSerifFont ? 'serif' : 'sans-serif'));+ this.fallbackName = this.isMonospace ? 'monospace' :+ this.isSerifFont ? 'serif' : 'sans-serif';this.differences = properties.differences;this.widths = properties.widths;this.defaultWidth = properties.defaultWidth;this.composite = properties.composite;this.wideChars = properties.wideChars;- this.cMap = properties.cMap;- this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;- this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;- this.fontMatrix = properties.fontMatrix;-- var unicode = this.buildToUnicode(properties);- this.toUnicode = properties.toUnicode = unicode.toUnicode;- this.isIdentityUnicode = properties.isIdentityUnicode = unicode.isIdentity;-- this.toFontChar = [];+ this.hasEncoding = properties.hasEncoding;+ this.fontMatrix = properties.fontMatrix;if (properties.type == 'Type3') {- for (charCode = 0; charCode < 256; charCode++) {- this.toFontChar[charCode] = (this.differences[charCode] ||- properties.defaultEncoding[charCode]);- }+ this.encoding = properties.baseEncoding;return;}+ // Trying to fix encoding using glyph CIDSystemInfo.+ this.loadCidToUnicode(properties);this.cidEncoding = properties.cidEncoding;this.vertical = properties.vertical;if (this.vertical) {@@ -20503,17 +20289,22 @@ var Font = (function FontClosure() {this.defaultVMetrics = properties.defaultVMetrics;}+ if (properties.toUnicode && properties.toUnicode.length > 0)+ this.toUnicode = properties.toUnicode;+ else+ this.rebuildToUnicode(properties);++ this.toFontChar = this.buildToFontChar(this.toUnicode);+if (!file) {- this.missingFile = true;// The file data is not specified. Trying to fix the font name// to be used with the canvas.font.var fontName = name.replace(/[,_]/g, '-');- var isStandardFont = fontName in stdFontMap;fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;this.bold = (fontName.search(/bold/gi) != -1);- this.italic = ((fontName.search(/oblique/gi) != -1) ||- (fontName.search(/italic/gi) != -1));+ this.italic = (fontName.search(/oblique/gi) != -1) ||+ (fontName.search(/italic/gi) != -1);// Use 'name' instead of 'fontName' here because the original// name ArialBlack for example will be replaced by Helvetica.@@ -20521,37 +20312,9 @@ var Font = (function FontClosure() {// if at least one width is present, remeasure all chars when existsthis.remeasure = Object.keys(this.widths).length > 0;- if (isStandardFont && type === 'CIDFontType2' &&- properties.cidEncoding.indexOf('Identity-') === 0) {- // Standard fonts might be embedded as CID font without glyph mapping.- // Building one based on GlyphMapForStandardFonts.- var map = [];- for (var code in GlyphMapForStandardFonts) {- map[+code] = GlyphMapForStandardFonts[code];- }- this.toFontChar = map;- this.toUnicode = map;- } else if (/Symbol/i.test(fontName)) {- var symbols = Encodings.SymbolSetEncoding;- for (charCode in symbols) {- var fontChar = GlyphsUnicode[symbols[charCode]];- if (!fontChar) {- continue;- }- this.toFontChar[charCode] = fontChar;- }- } else if (isStandardFont) {- this.toFontChar = [];- for (charCode in properties.defaultEncoding) {- var glyphName = properties.differences[charCode] ||- properties.defaultEncoding[charCode];- this.toFontChar[charCode] = GlyphsUnicode[glyphName];- }- } else {- for (charCode in this.toUnicode) {- this.toFontChar[charCode] = this.toUnicode[charCode].charCodeAt(0);- }- }++ this.encoding = properties.baseEncoding;+ this.noUnicodeAdaptation = true;this.loadedName = fontName.split('-')[0];this.loading = false;return;@@ -20559,12 +20322,10 @@ var Font = (function FontClosure() {// Some fonts might use wrong font types for Type1C or CIDFontType0Cvar subtype = properties.subtype;- if (subtype == 'Type1C' && (type != 'Type1' && type != 'MMType1')) {+ if (subtype == 'Type1C' && (type != 'Type1' && type != 'MMType1'))type = 'Type1';- }- if (subtype == 'CIDFontType0C' && type != 'CIDFontType0') {+ if (subtype == 'CIDFontType0C' && type != 'CIDFontType0')type = 'CIDFontType0';- }// XXX: Temporarily change the type for open type so we trigger a warning.// This should be removed when we add support for open type.if (subtype === 'OpenType') {@@ -20586,7 +20347,6 @@ var Font = (function FontClosure() {data = this.convert(name, cff, properties);break;- case 'OpenType':case 'TrueType':case 'CIDFontType2':this.mimetype = 'font/opentype';@@ -20594,10 +20354,14 @@ var Font = (function FontClosure() {// Repair the TrueType file. It is can be damaged in the point of// view of the sanitizerdata = this.checkAndRepair(name, file, properties);+ if (!data) {+ // TrueType data is not found, e.g. when the font is an OpenType font+ warn('Font is not a TrueType font');+ }break;default:- error('Font ' + type + ' is not supported');+ warn('Font ' + type + ' is not supported');break;}@@ -20613,19 +20377,34 @@ var Font = (function FontClosure() {this.loading = true;}- Font.getFontID = (function () {- var ID = 1;- return function Font_getFontID() {- return String(ID++);- };- })();+ var numFonts = 0;+ function getUniqueName() {+ return 'pdfFont' + numFonts++;+ }++ function stringToArray(str) {+ var array = [];+ for (var i = 0, ii = str.length; i < ii; ++i)+ array[i] = str.charCodeAt(i);++ return array;+ }++ function arrayToString(arr) {+ var str = '';+ for (var i = 0, ii = arr.length; i < ii; ++i)+ str += String.fromCharCode(arr[i]);- function int16(b0, b1) {- return (b0 << 8) + b1;+ return str;+ }++ function int16(bytes) {+ return (bytes[0] << 8) + (bytes[1] & 0xff);}- function int32(b0, b1, b2, b3) {- return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;+ function int32(bytes) {+ return (bytes[0] << 24) + (bytes[1] << 16) ++ (bytes[2] << 8) + (bytes[3] & 0xff);}function getMaxPower2(number) {@@ -20637,27 +20416,34 @@ var Font = (function FontClosure() {}value = 2;- for (var i = 1; i < maxPower; i++) {+ for (var i = 1; i < maxPower; i++)value *= 2;- }return value;}function string16(value) {- return String.fromCharCode((value >> 8) & 0xff, value & 0xff);+ return String.fromCharCode((value >> 8) & 0xff) ++ String.fromCharCode(value & 0xff);}function safeString16(value) {// clamp value to the 16-bit int range- value = (value > 0x7FFF ? 0x7FFF : (value < -0x8000 ? -0x8000 : value));- return String.fromCharCode((value >> 8) & 0xff, value & 0xff);+ value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value;+ return String.fromCharCode((value >> 8) & 0xff) ++ String.fromCharCode(value & 0xff);+ }++ function string32(value) {+ return String.fromCharCode((value >> 24) & 0xff) ++ String.fromCharCode((value >> 16) & 0xff) ++ String.fromCharCode((value >> 8) & 0xff) ++ String.fromCharCode(value & 0xff);}function createOpenTypeHeader(sfnt, file, numTables) {// Windows hates the Mac TrueType sfnt version number- if (sfnt == 'true') {+ if (sfnt == 'true')sfnt = string32(0x00010000);- }// sfnt version (4 bytes)var header = sfnt;@@ -20688,19 +20474,17 @@ var Font = (function FontClosure() {var length = data.length;// Per spec tables must be 4-bytes align so add padding as needed- while (data.length & 3) {+ while (data.length & 3)data.push(0x00);- }- while (file.virtualOffset & 3) {++ while (file.virtualOffset & 3)file.virtualOffset++;- }// checksumvar checksum = 0, n = data.length;- for (var i = 0; i < n; i += 4) {- checksum = (checksum + int32(data[i], data[i + 1], data[i + 2],- data[i + 3])) | 0;- }+ for (var i = 0; i < n; i += 4)+ checksum = (checksum + int32([data[i], data[i + 1], data[i + 2],+ data[i + 3]])) | 0;var tableEntry = (tag + string32(checksum) +string32(offset) + string32(length));@@ -20708,101 +20492,29 @@ var Font = (function FontClosure() {file.virtualOffset += data.length;}- /**- * Rebuilds the char code to glyph ID map by trying to replace the char codes- * with their unicode value. It also moves char codes that are in known- * problematic locations.- * @return {Object} Two properties:- * 'toFontChar' - maps original char codes(the value that will be read- * from commands such as show text) to the char codes that will be used in the- * font that we build- * 'charCodeToGlyphId' - maps the new font char codes to glyph ids- */- function adjustMapping(charCodeToGlyphId, properties) {- var toUnicode = properties.toUnicode;- var isSymbolic = !!(properties.flags & FontFlags.Symbolic);- var isIdentityUnicode = properties.isIdentityUnicode;- var newMap = Object.create(null);- var toFontChar = [];- var usedCharCodes = [];- var usedFontCharCodes = [];- var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;- for (var originalCharCode in charCodeToGlyphId) {- originalCharCode |= 0;- var glyphId = charCodeToGlyphId[originalCharCode];- var fontCharCode = originalCharCode;- // First try to map the value to a unicode position if a non identity map- // was created.- if (!isIdentityUnicode && originalCharCode in toUnicode) {- var unicode = toUnicode[fontCharCode];- // TODO: Try to map ligatures to the correct spot.- if (unicode.length === 1) {- fontCharCode = unicode.charCodeAt(0);- }- }- // Try to move control characters, special characters and already mapped- // characters to the private use area since they will not be drawn by- // canvas if left in their current position. Also, move characters if the- // font was symbolic and there is only an identity unicode map since the- // characters probably aren't in the correct position (fixes an issue- // with firefox and thuluthfont).- if ((fontCharCode in usedFontCharCodes ||- fontCharCode <= 0x1f || // Control chars- fontCharCode === 0x7F || // Control char- fontCharCode === 0xAD || // Soft hyphen- (fontCharCode >= 0x80 && fontCharCode <= 0x9F) || // Control chars- (isSymbolic && isIdentityUnicode)) &&- nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) { // Room left.- // Loop to try and find a free spot in the private use area.- do {- fontCharCode = nextAvailableFontCharCode++;-- if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {- fontCharCode = 0xF020;- nextAvailableFontCharCode = fontCharCode + 1;- }-- } while (fontCharCode in usedFontCharCodes &&- nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);- }-- newMap[fontCharCode] = glyphId;- toFontChar[originalCharCode] = fontCharCode;- usedFontCharCodes[fontCharCode] = true;- }- return {- toFontChar: toFontChar,- charCodeToGlyphId: newMap,- nextAvailableFontCharCode: nextAvailableFontCharCode- };- }-- function getRanges(glyphs) {+ function getRanges(glyphs, deltas) {// Array.sort() sorts by characters, not numerically, so convert to an// array of characters.var codes = [];- for (var charCode in glyphs) {- codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });- }+ var length = glyphs.length;+ for (var n = 0; n < length; ++n)+ codes.push({ unicode: glyphs[n].unicode, code: n });codes.sort(function fontGetRangesSort(a, b) {- return a.fontCharCode - b.fontCharCode;+ return a.unicode - b.unicode;});// Split the sorted codes into ranges.var ranges = [];- var length = codes.length;for (var n = 0; n < length; ) {- var start = codes[n].fontCharCode;- var codeIndices = [codes[n].glyphId];+ var start = codes[n].unicode;+ var codeIndices = [deltas ? deltas[codes[n].code] : codes[n].code + 1];++n;var end = start;- while (n < length && end + 1 == codes[n].fontCharCode) {- codeIndices.push(codes[n].glyphId);+ while (n < length && end + 1 == codes[n].unicode) {+ codeIndices.push(deltas ? deltas[codes[n].code] : codes[n].code + 1);++end;++n;- if (end === 0xFFFF) {- break;- }+ if (end === 0xFFFF) { break; }}ranges.push([start, end, codeIndices]);}@@ -20810,8 +20522,9 @@ var Font = (function FontClosure() {return ranges;}- function createCmapTable(glyphs) {- var ranges = getRanges(glyphs);+ function createCmapTable(glyphs, deltas) {+ var ranges = getRanges(glyphs, deltas);+var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;var cmap = '\x00\x00' + // versionstring16(numTables) + // numTables@@ -20819,8 +20532,7 @@ var Font = (function FontClosure() {'\x00\x01' + // encodingIDstring32(4 + numTables * 8); // start of the table record- var i, ii, j, jj;- for (i = ranges.length - 1; i >= 0; --i) {+ for (var i = ranges.length - 1; i >= 0; --i) {if (ranges[i][0] <= 0xFFFF) { break; }}var bmpLength = i + 1;@@ -20842,17 +20554,16 @@ var Font = (function FontClosure() {var idRangeOffsets = '';var glyphsIds = '';var bias = 0;-- var range, start, end, codes;- for (i = 0, ii = bmpLength; i < ii; i++) {- range = ranges[i];- start = range[0];- end = range[1];++ for (var i = 0, ii = bmpLength; i < ii; i++) {+ var range = ranges[i];+ var start = range[0];+ var end = range[1];startCount += string16(start);endCount += string16(end);- codes = range[2];+ var codes = range[2];var contiguous = true;- for (j = 1, jj = codes.length; j < jj; ++j) {+ for (var j = 1, jj = codes.length; j < jj; ++j) {if (codes[j] !== codes[j - 1] + 1) {contiguous = false;break;@@ -20865,7 +20576,7 @@ var Font = (function FontClosure() {idDeltas += string16(0);idRangeOffsets += string16(offset);- for (j = 0, jj = codes.length; j < jj; ++j) {+ for (var j = 0, jj = codes.length; j < jj; ++j) {glyphsIds += string16(codes[j]);}} else {@@ -20899,14 +20610,14 @@ var Font = (function FontClosure() {string32(4 + numTables * 8 +4 + format314.length); // start of the table recordformat31012 = '';- for (i = 0, ii = ranges.length; i < ii; i++) {- range = ranges[i];- start = range[0];- codes = range[2];+ for (var i = 0, ii = ranges.length; i < ii; i++) {+ var range = ranges[i];+ var start = range[0];+ var codes = range[2];var code = codes[0];- for (j = 1, jj = codes.length; j < jj; ++j) {+ for (var j = 1, jj = codes.length; j < jj; ++j) {if (codes[j] !== codes[j - 1] + 1) {- end = range[0] + j - 1;+ var end = range[0] + j - 1;format31012 += string32(start) + // startCharCodestring32(end) + // endCharCodestring32(code); // startGlyphID@@ -20933,21 +20644,21 @@ var Font = (function FontClosure() {function validateOS2Table(os2) {var stream = new Stream(os2.data);- var version = stream.getUint16();+ var version = int16(stream.getBytes(2));// TODO verify all OS/2 tables fields, but currently we validate only those// that give us issuesstream.getBytes(60); // skipping type, misc sizes, panose, unicode ranges- var selection = stream.getUint16();+ var selection = int16(stream.getBytes(2));if (version < 4 && (selection & 0x0300)) {return false;}- var firstChar = stream.getUint16();- var lastChar = stream.getUint16();+ var firstChar = int16(stream.getBytes(2));+ var lastChar = int16(stream.getBytes(2));if (firstChar > lastChar) {return false;}stream.getBytes(6); // skipping sTypoAscender/Descender/LineGap- var usWinAscent = stream.getUint16();+ var usWinAscent = int16(stream.getBytes(2));if (usWinAscent === 0) { // makes font unreadable by windowsreturn false;}@@ -20975,14 +20686,12 @@ var Font = (function FontClosure() {var lastCharIndex = 0;if (charstrings) {- for (var code in charstrings) {- code |= 0;- if (firstCharIndex > code || !firstCharIndex) {+ for (var i = 0; i < charstrings.length; ++i) {+ var code = charstrings[i].unicode;+ if (firstCharIndex > code || !firstCharIndex)firstCharIndex = code;- }- if (lastCharIndex < code) {+ if (lastCharIndex < code)lastCharIndex = code;- }var position = getUnicodeRangeFor(code);if (position < 32) {@@ -21004,18 +20713,18 @@ var Font = (function FontClosure() {}var bbox = properties.bbox || [0, 0, 0, 0];- var unitsPerEm = (override.unitsPerEm ||- 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0]);+ var unitsPerEm = override.unitsPerEm ||+ 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];// if the font units differ to the PDF glyph space units// then scale up the values- var scale = (properties.ascentScaled ? 1.0 :- unitsPerEm / PDF_GLYPH_SPACE_UNITS);+ var scale = properties.ascentScaled ? 1.0 :+ unitsPerEm / PDF_GLYPH_SPACE_UNITS;- var typoAscent = (override.ascent ||- Math.round(scale * (properties.ascent || bbox[3])));- var typoDescent = (override.descent ||- Math.round(scale * (properties.descent || bbox[1])));+ var typoAscent = override.ascent || Math.round(scale *+ (properties.ascent || bbox[3]));+ var typoDescent = override.descent || Math.round(scale *+ (properties.descent || bbox[1]));if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {typoDescent = -typoDescent; // fixing incorrect descent}@@ -21066,15 +20775,15 @@ var Font = (function FontClosure() {function createPostTable(properties) {var angle = Math.floor(properties.italicAngle * (Math.pow(2, 16)));- return ('\x00\x03\x00\x00' + // Version number- string32(angle) + // italicAngle- '\x00\x00' + // underlinePosition- '\x00\x00' + // underlineThickness- string32(properties.fixedPitch) + // isFixedPitch- '\x00\x00\x00\x00' + // minMemType42- '\x00\x00\x00\x00' + // maxMemType42- '\x00\x00\x00\x00' + // minMemType1- '\x00\x00\x00\x00'); // maxMemType1+ return '\x00\x03\x00\x00' + // Version number+ string32(angle) + // italicAngle+ '\x00\x00' + // underlinePosition+ '\x00\x00' + // underlineThickness+ string32(properties.fixedPitch) + // isFixedPitch+ '\x00\x00\x00\x00' + // minMemType42+ '\x00\x00\x00\x00' + // maxMemType42+ '\x00\x00\x00\x00' + // minMemType1+ '\x00\x00\x00\x00'; // maxMemType1}function createNameTable(name, proto) {@@ -21098,15 +20807,13 @@ var Font = (function FontClosure() {// Mac want 1-byte per character strings while Windows want// 2-bytes per character, so duplicate the names tablevar stringsUnicode = [];- var i, ii, j, jj, str;- for (i = 0, ii = strings.length; i < ii; i++) {- str = proto[1][i] || strings[i];+ for (var i = 0, ii = strings.length; i < ii; i++) {+ var str = proto[1][i] || strings[i];- var strBufUnicode = [];- for (j = 0, jj = str.length; j < jj; j++) {- strBufUnicode.push(string16(str.charCodeAt(j)));- }- stringsUnicode.push(strBufUnicode.join(''));+ var strUnicode = '';+ for (var j = 0, jj = str.length; j < jj; j++)+ strUnicode += string16(str.charCodeAt(j));+ stringsUnicode.push(strUnicode);}var names = [strings, stringsUnicode];@@ -21122,10 +20829,10 @@ var Font = (function FontClosure() {// Build the name records fieldvar strOffset = 0;- for (i = 0, ii = platforms.length; i < ii; i++) {+ for (var i = 0, ii = platforms.length; i < ii; i++) {var strs = names[i];- for (j = 0, jj = strs.length; j < jj; j++) {- str = strs[j];+ for (var j = 0, jj = strs.length; j < jj; j++) {+ var str = strs[j];var nameRecord =platforms[i] + // platform IDencodings[i] + // encoding ID@@ -21142,11 +20849,43 @@ var Font = (function FontClosure() {return nameTable;}+ // Normalize the charcodes in the cmap table into unicode values+ // that will work with the (3, 1) cmap table we will write out.+ function cmapCharcodeToUnicode(charcode, symbolic, platformId, encodingId) {+ var unicode;+ if (symbolic) {+ // These codes will be shifted into the range+ // SYMBOLIC_FONT_GLYPH_OFFSET to (SYMBOLIC_FONT_GLYPH_OFFSET + 0xFF)+ // so that they are not in the control character range that could+ // be displayed as spaces by browsers.+ if (platformId === 3 && encodingId === 0 ||+ platformId === 1 && encodingId === 0) {+ unicode = SYMBOLIC_FONT_GLYPH_OFFSET | (charcode & 0xFF);+ }+ } else {+ if (platformId === 3 && encodingId === 1) {+ // A (3, 1) table is alredy unicode (Microsoft Unicode format)+ unicode = charcode;+ } else if (platformId === 1 && encodingId === 0) {+ // TODO(mack): Should apply the changes to convert the+ // MacRomanEncoding to Mac OS Roman encoding in 9.6.6.4+ // table 115 of the pdf spec+ var glyphName = Encodings.MacRomanEncoding[charcode];+ if (glyphName) {+ unicode = GlyphsUnicode[glyphName];+ }+ }+ }+ return unicode;+ }++Font.prototype = {name: null,font: null,mimetype: null,encoding: null,+get renderer() {var renderer = FontRendererFactory.create(this);return shadow(this, 'renderer', renderer);@@ -21155,20 +20894,23 @@ var Font = (function FontClosure() {exportData: function Font_exportData() {var data = {};for (var i in this) {- if (this.hasOwnProperty(i)) {+ if (this.hasOwnProperty(i))data[i] = this[i];- }}return data;},checkAndRepair: function Font_checkAndRepair(name, font, properties) {function readTableEntry(file) {- var tag = bytesToString(file.getBytes(4));+ var tag = file.getBytes(4);+ tag = String.fromCharCode(tag[0]) ++ String.fromCharCode(tag[1]) ++ String.fromCharCode(tag[2]) ++ String.fromCharCode(tag[3]);- var checksum = file.getUint32();- var offset = file.getUint32();- var length = file.getUint32();+ var checksum = int32(file.getBytes(4));+ var offset = int32(file.getBytes(4));+ var length = int32(file.getBytes(4));// Read the table associated datavar previousPosition = file.pos;@@ -21194,57 +20936,116 @@ var Font = (function FontClosure() {function readOpenTypeHeader(ttf) {return {- version: bytesToString(ttf.getBytes(4)),- numTables: ttf.getUint16(),- searchRange: ttf.getUint16(),- entrySelector: ttf.getUint16(),- rangeShift: ttf.getUint16()+ version: arrayToString(ttf.getBytes(4)),+ numTables: int16(ttf.getBytes(2)),+ searchRange: int16(ttf.getBytes(2)),+ entrySelector: int16(ttf.getBytes(2)),+ rangeShift: int16(ttf.getBytes(2))};}+ function createGlyphNameMap(glyphs, ids, properties) {+ var glyphNames = properties.glyphNames;+ if (!glyphNames) {+ properties.glyphNameMap = {};+ return;+ }+ var glyphsLength = glyphs.length;+ var glyphNameMap = {};+ var encoding = [];+ for (var i = 0; i < glyphsLength; ++i) {+ var glyphName = glyphNames[ids[i]];+ if (!glyphName)+ continue;+ var unicode = glyphs[i].unicode;+ glyphNameMap[glyphName] = unicode;+ var code = glyphs[i].code;+ encoding[code] = glyphName;+ }+ properties.glyphNameMap = glyphNameMap;+ if (properties.overridableEncoding)+ properties.baseEncoding = encoding;+ }+/*** Read the appropriate subtable from the cmap according to 9.6.6.4 from* PDF spec*/- function readCmapTable(cmap, font, isSymbolicFont) {- var segment;+ function readCmapTable(cmap, font, hasEncoding, isSymbolicFont) {var start = (font.start ? font.start : 0) + cmap.offset;font.pos = start;- var version = font.getUint16();- var numTables = font.getUint16();+ var version = int16(font.getBytes(2));+ var numTables = int16(font.getBytes(2));var potentialTable;- var canBreak = false;- // There's an order of preference in terms of which cmap subtable to- // use:- // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table- // - symbolic fonts the preference is a 3,0 table then a 1,0 table- // The following takes advantage of the fact that the tables are sorted- // to work.+ var foundPreferredTable;+ // There's an order of preference in terms of which cmap subtable we+ // want to use. So scan through them to find our preferred table.for (var i = 0; i < numTables; i++) {- var platformId = font.getUint16();- var encodingId = font.getUint16();- var offset = font.getUint32();+ var platformId = int16(font.getBytes(2));+ var encodingId = int16(font.getBytes(2));+ var offset = int32(font.getBytes(4));var useTable = false;+ var canBreak = false;- if (platformId == 1 && encodingId === 0) {- useTable = true;- // Continue the loop since there still may be a higher priority- // table.- } else if (!isSymbolicFont && platformId === 3 && encodingId === 1) {+ // The following block implements the following from the spec:+ //+ // When the font has no Encoding entry, or the font descriptor’s+ // Symbolic flag is set (in which case the Encoding entry+ // is ignored), this shall occur:+ // - If the font contains a (3, 0) subtable, the range of+ // - Otherwise, the (1, 0) subtable will be used.+ // Otherwise, if the font does have an encoding:+ // - Use the (3, 1) cmap subtable+ // - Otherwise, use the (1, 0) subtable if present+ //+ // The following diverges slightly from the above spec in order+ // to handle the case that hasEncoding and isSymbolicFont are both+ // true. In this, based on the ordering of the rules in the spec,+ // my interpretation is that we should be acting as if the font is+ // symbolic.+ //+ // However, in this case, the test pdf 'preistabelle.pdf'+ // is interpreting this case as a non-symbolic font. In this case+ // though, 'presitabelle.pdf' does contain a (3, 1) table and does+ // not contain a (3, 0) table which indicates it is non-symbolic.+ //+ // Thus, I am using this heurisitic of looking at which table is+ // found to truly determine whether or not the font is symbolic.+ // That is, if the specific symbolic/non-symbolic font specific+ // tables (3, 0) or (3, 1) is found, that information is used for+ // deciding if the font is symbolic or not.+ //+ // TODO(mack): This section needs some more thought on whether the+ // heuristic is good enough. For now, it passes all the regression+ // tests.+ if (isSymbolicFont && platformId === 3 && encodingId === 0) {useTable = true;canBreak = true;- } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {+ foundPreferredTable = true;+ } else if (hasEncoding && platformId === 3 && encodingId === 1) {useTable = true;canBreak = true;+ foundPreferredTable = true;+ // Update the isSymbolicFont based on this heuristic+ isSymbolicFont = false;+ } else if (platformId === 1 && encodingId === 0 &&+ !foundPreferredTable) {+ useTable = true;+ foundPreferredTable = true;+ } else if (!potentialTable) {+ // We will use an arbitrary table if we cannot find a preferred+ // table+ useTable = true;}if (useTable) {potentialTable = {platformId: platformId,encodingId: encodingId,- offset: offset+ offset: offset,+ isSymbolicFont: isSymbolicFont};}if (canBreak) {@@ -21253,28 +21054,35 @@ var Font = (function FontClosure() {}if (!potentialTable) {- warn('Could not find a preferred cmap table.');- return [];+ error('Could not find a cmap table');+ return;+ }++ if (!foundPreferredTable) {+ warn('Did not find a cmap of suitable format. Interpreting (' ++ potentialTable.platformId + ', ' + potentialTable.encodingId ++ ') as (3, 1) table');+ potentialTable.platformId = 3;+ potentialTable.encodingId = 1;}font.pos = start + potentialTable.offset;- var format = font.getUint16();- var length = font.getUint16();- var language = font.getUint16();+ var format = int16(font.getBytes(2));+ var length = int16(font.getBytes(2));+ var language = int16(font.getBytes(2));var hasShortCmap = false;var mappings = [];- var j, glyphId;// TODO(mack): refactor this cmap subtable reading logic outif (format === 0) {- for (j = 0; j < 256; j++) {+ for (var j = 0; j < 256; j++) {var index = font.getByte();if (!index) {continue;}mappings.push({- charCode: j,+ charcode: j,glyphId: index});}@@ -21282,25 +21090,25 @@ var Font = (function FontClosure() {} else if (format === 4) {// re-creating the table in format 4 since the encoding// might be changed- var segCount = (font.getUint16() >> 1);+ var segCount = (int16(font.getBytes(2)) >> 1);font.getBytes(6); // skipping range fieldsvar segIndex, segments = [];for (segIndex = 0; segIndex < segCount; segIndex++) {- segments.push({ end: font.getUint16() });+ segments.push({ end: int16(font.getBytes(2)) });}- font.getUint16();+ font.getBytes(2);for (segIndex = 0; segIndex < segCount; segIndex++) {- segments[segIndex].start = font.getUint16();+ segments[segIndex].start = int16(font.getBytes(2));}for (segIndex = 0; segIndex < segCount; segIndex++) {- segments[segIndex].delta = font.getUint16();+ segments[segIndex].delta = int16(font.getBytes(2));}var offsetsCount = 0;for (segIndex = 0; segIndex < segCount; segIndex++) {- segment = segments[segIndex];- var rangeOffset = font.getUint16();+ var segment = segments[segIndex];+ var rangeOffset = int16(font.getBytes(2));if (!rangeOffset) {segment.offsetIndex = -1;continue;@@ -21309,34 +21117,32 @@ var Font = (function FontClosure() {var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);segment.offsetIndex = offsetIndex;offsetsCount = Math.max(offsetsCount, offsetIndex +- segment.end - segment.start + 1);+ segment.end - segment.start + 1);}var offsets = [];- for (j = 0; j < offsetsCount; j++) {- offsets.push(font.getUint16());+ for (var j = 0; j < offsetsCount; j++) {+ offsets.push(int16(font.getBytes(2)));}for (segIndex = 0; segIndex < segCount; segIndex++) {- segment = segments[segIndex];- start = segment.start;- var end = segment.end;- var delta = segment.delta;- offsetIndex = segment.offsetIndex;+ var segment = segments[segIndex];+ var start = segment.start, end = segment.end;+ var delta = segment.delta, offsetIndex = segment.offsetIndex;- for (j = start; j <= end; j++) {+ for (var j = start; j <= end; j++) {if (j == 0xFFFF) {continue;}- glyphId = (offsetIndex < 0 ?- j : offsets[offsetIndex + j - start]);+ var glyphId = offsetIndex < 0 ? j :+ offsets[offsetIndex + j - start];glyphId = (glyphId + delta) & 0xFFFF;if (glyphId === 0) {continue;}mappings.push({- charCode: j,+ charcode: j,glyphId: glyphId});}@@ -21347,17 +21153,17 @@ var Font = (function FontClosure() {// table. (This looks weird, so I can have missed something), this// works on Linux but seems to fails on Mac so let's rewrite the// cmap table to a 3-1-4 style- var firstCode = font.getUint16();- var entryCount = font.getUint16();+ var firstCode = int16(font.getBytes(2));+ var entryCount = int16(font.getBytes(2));var glyphs = [];var ids = [];- for (j = 0; j < entryCount; j++) {- glyphId = font.getUint16();- var charCode = firstCode + j;+ for (var j = 0; j < entryCount; j++) {+ var glyphId = int16(font.getBytes(2));+ var charcode = firstCode + j;mappings.push({- charCode: charCode,+ charcode: charcode,glyphId: glyphId});}@@ -21365,20 +21171,10 @@ var Font = (function FontClosure() {error('cmap table has unsupported format: ' + format);}- // removing duplicate entries- mappings.sort(function (a, b) {- return a.charCode - b.charCode;- });- for (i = 1; i < mappings.length; i++) {- if (mappings[i - 1].charCode === mappings[i].charCode) {- mappings.splice(i, 1);- i--;- }- }-return {platformId: potentialTable.platformId,encodingId: potentialTable.encodingId,+ isSymbolicFont: potentialTable.isSymbolicFont,mappings: mappings,hasShortCmap: hasShortCmap};@@ -21394,7 +21190,7 @@ var Font = (function FontClosure() {font.pos = (font.start ? font.start : 0) + header.offset;font.pos += header.length - 2;- var numOfMetrics = font.getUint16();+ var numOfMetrics = int16(font.getBytes(2));if (numOfMetrics > numGlyphs) {info('The numOfMetrics (' + numOfMetrics + ') should not be ' +@@ -21409,16 +21205,13 @@ var Font = (function FontClosure() {var numMissing = numOfSidebearings -((metrics.length - numOfMetrics * 4) >> 1);- var i, ii;if (numMissing > 0) {font.pos = (font.start ? font.start : 0) + metrics.offset;var entries = '';- for (i = 0, ii = metrics.length; i < ii; i++) {+ for (var i = 0, ii = metrics.length; i < ii; i++)entries += String.fromCharCode(font.getByte());- }- for (i = 0; i < numMissing; i++) {+ for (var i = 0; i < numMissing; i++)entries += '\x00\x00';- }metrics.data = stringToArray(entries);}}@@ -21437,8 +21230,8 @@ var Font = (function FontClosure() {return glyf.length;}- var i, j = 10, flagsCount = 0;- for (i = 0; i < contoursCount; i++) {+ var j = 10, flagsCount = 0;+ for (var i = 0; i < contoursCount; i++) {var endPoint = (glyf[j] << 8) | glyf[j + 1];flagsCount = endPoint + 1;j += 2;@@ -21450,11 +21243,11 @@ var Font = (function FontClosure() {var instructionsEnd = j;// validating flagsvar coordinatesLength = 0;- for (i = 0; i < flagsCount; i++) {+ for (var i = 0; i < flagsCount; i++) {var flag = glyf[j++];if (flag & 0xC0) {- // reserved flags must be zero, cleaning up- glyf[j - 1] = flag & 0x3F;+ // reserved flags must be zero, rejecting+ return 0;}var xyLength = ((flag & 2) ? 1 : (flag & 16) ? 0 : 2) +((flag & 4) ? 1 : (flag & 32) ? 0 : 2);@@ -21465,10 +21258,6 @@ var Font = (function FontClosure() {coordinatesLength += repeat * xyLength;}}- // glyph without coordinates will be rejected- if (coordinatesLength === 0) {- return 0;- }var glyphDataLength = j + coordinatesLength;if (glyphDataLength > glyf.length) {// not enough data for coordinates@@ -21501,7 +21290,7 @@ var Font = (function FontClosure() {// Validate version:// Should always be 0x00010000- var version = int32(data[0], data[1], data[2], data[3]);+ var version = int32([data[0], data[1], data[2], data[3]]);if (version >> 16 !== 1) {info('Attempting to fix invalid version in head table: ' + version);data[0] = 0;@@ -21510,7 +21299,7 @@ var Font = (function FontClosure() {data[3] = 0;}- var indexToLocFormat = int16(data[50], data[51]);+ var indexToLocFormat = int16([data[50], data[51]]);if (indexToLocFormat < 0 || indexToLocFormat > 1) {info('Attempting to fix invalid indexToLocFormat in head table: ' +indexToLocFormat);@@ -21541,8 +21330,7 @@ var Font = (function FontClosure() {}function sanitizeGlyphLocations(loca, glyf, numGlyphs,- isGlyphLocationsLong, hintsValid,- dupFirstEntry) {+ isGlyphLocationsLong, hintsValid) {var itemSize, itemDecode, itemEncode;if (isGlyphLocationsLong) {itemSize = 4;@@ -21567,13 +21355,6 @@ var Font = (function FontClosure() {};}var locaData = loca.data;- var locaDataSize = itemSize * (1 + numGlyphs);- // is loca.data too short or long?- if (locaData.length !== locaDataSize) {- locaData = new Uint8Array(locaDataSize);- locaData.set(loca.data.subarray(0, locaDataSize));- loca.data = locaData;- }// removing the invalid glyphsvar oldGlyfData = glyf.data;var oldGlyfDataLength = oldGlyfData.length;@@ -21581,15 +21362,8 @@ var Font = (function FontClosure() {var startOffset = itemDecode(locaData, 0);var writeOffset = 0;itemEncode(locaData, 0, writeOffset);- var i, j;- for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {+ for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {var endOffset = itemDecode(locaData, j);- if (endOffset > oldGlyfDataLength &&- ((oldGlyfDataLength + 3) & ~3) === endOffset) {- // Aspose breaks fonts by aligning the glyphs to the qword, but not- // the glyf table size, which makes last glyph out of range.- endOffset = oldGlyfDataLength;- }if (endOffset > oldGlyfDataLength) {// glyph end offset points outside glyf data, rejecting the glyphitemEncode(locaData, j, writeOffset);@@ -21609,26 +21383,36 @@ var Font = (function FontClosure() {// to have single glyph with one pointvar simpleGlyph = new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);- for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {+ for (var i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize)itemEncode(locaData, j, simpleGlyph.length);- }glyf.data = simpleGlyph;return;}- if (dupFirstEntry) {- var firstEntryLength = itemDecode(locaData, itemSize);- if (newGlyfData.length > firstEntryLength + writeOffset) {- glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);- } else {- glyf.data = new Uint8Array(firstEntryLength + writeOffset);- glyf.data.set(newGlyfData.subarray(0, writeOffset));- }- glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);- itemEncode(loca.data, locaData.length - itemSize,- writeOffset + firstEntryLength);+ glyf.data = newGlyfData.subarray(0, writeOffset);+ }++ function findEmptyGlyphs(locaTable, isGlyphLocationsLong, emptyGlyphIds) {+ var itemSize, itemDecode;+ if (isGlyphLocationsLong) {+ itemSize = 4;+ itemDecode = function fontItemDecodeLong(data, offset) {+ return (data[offset] << 24) | (data[offset + 1] << 16) |+ (data[offset + 2] << 8) | data[offset + 3];+ };} else {- glyf.data = newGlyfData.subarray(0, writeOffset);+ itemSize = 2;+ itemDecode = function fontItemDecode(data, offset) {+ return (data[offset] << 9) | (data[offset + 1] << 1);+ };+ }+ var data = locaTable.data, length = data.length;+ var lastOffset = itemDecode(data, 0);+ for (var i = itemSize, j = 0; i < length; i += itemSize, j++) {+ var offset = itemDecode(data, i);+ if (offset == lastOffset)+ emptyGlyphIds[j] = true;+ lastOffset = offset;}}@@ -21637,27 +21421,25 @@ var Font = (function FontClosure() {font.pos = start;var length = post.length, end = start + length;- var version = font.getUint32();+ var version = int32(font.getBytes(4));// skip rest to the tablesfont.getBytes(28);var glyphNames;var valid = true;- var i;-switch (version) {case 0x00010000:glyphNames = MacStandardGlyphOrdering;break;case 0x00020000:- var numGlyphs = font.getUint16();+ var numGlyphs = int16(font.getBytes(2));if (numGlyphs != maxpNumGlyphs) {valid = false;break;}var glyphNameIndexes = [];- for (i = 0; i < numGlyphs; ++i) {- var index = font.getUint16();+ for (var i = 0; i < numGlyphs; ++i) {+ var index = int16(font.getBytes(2));if (index >= 32768) {valid = false;break;@@ -21671,13 +21453,12 @@ var Font = (function FontClosure() {while (font.pos < end) {var stringLength = font.getByte();var string = '';- for (i = 0; i < stringLength; ++i) {- string += String.fromCharCode(font.getByte());- }+ for (var i = 0; i < stringLength; ++i)+ string += font.getChar();customNames.push(string);}glyphNames = [];- for (i = 0; i < numGlyphs; ++i) {+ for (var i = 0; i < numGlyphs; ++i) {var j = glyphNameIndexes[i];if (j < 258) {glyphNames.push(MacStandardGlyphOrdering[j]);@@ -21703,27 +21484,25 @@ var Font = (function FontClosure() {var names = [[], []];var length = nameTable.length, end = start + length;- var format = font.getUint16();+ var format = int16(font.getBytes(2));var FORMAT_0_HEADER_LENGTH = 6;if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {// unsupported name table format or table "too" smallreturn names;}- var numRecords = font.getUint16();- var stringsStart = font.getUint16();+ var numRecords = int16(font.getBytes(2));+ var stringsStart = int16(font.getBytes(2));var records = [];var NAME_RECORD_LENGTH = 12;- var i, ii;-- for (i = 0; i < numRecords &&+ for (var i = 0; i < numRecords &&font.pos + NAME_RECORD_LENGTH <= end; i++) {var r = {- platform: font.getUint16(),- encoding: font.getUint16(),- language: font.getUint16(),- name: font.getUint16(),- length: font.getUint16(),- offset: font.getUint16()+ platform: int16(font.getBytes(2)),+ encoding: int16(font.getBytes(2)),+ language: int16(font.getBytes(2)),+ name: int16(font.getBytes(2)),+ length: int16(font.getBytes(2)),+ offset: int16(font.getBytes(2))};// using only Macintosh and Windows platform/encoding namesif ((r.platform == 1 && r.encoding === 0 && r.language === 0) ||@@ -21731,7 +21510,7 @@ var Font = (function FontClosure() {records.push(r);}}- for (i = 0, ii = records.length; i < ii; i++) {+ for (var i = 0, ii = records.length; i < ii; i++) {var record = records[i];var pos = start + stringsStart + record.offset;if (pos + record.length > end) {@@ -21744,7 +21523,7 @@ var Font = (function FontClosure() {// unicodevar str = '';for (var j = 0, jj = record.length; j < jj; j += 2) {- str += String.fromCharCode(font.getUint16());+ str += String.fromCharCode(int16(font.getBytes(2)));}names[1][nameIndex] = str;} else {@@ -21768,7 +21547,7 @@ var Font = (function FontClosure() {function sanitizeTTProgram(table, ttContext) {var data = table.data;- var i = 0, j, n, b, funcId, pc, lastEndf = 0, lastDeff = 0;+ var i = 0, n, lastEndf = 0, lastDeff = 0;var stack = [];var callstack = [];var functionsCalled = [];@@ -21784,7 +21563,7 @@ var Font = (function FontClosure() {if (inFDEF || inELSE) {i += n;} else {- for (j = 0; j < n; j++) {+ for (var j = 0; j < n; j++) {stack.push(data[i++]);}}@@ -21793,8 +21572,8 @@ var Font = (function FontClosure() {if (inFDEF || inELSE) {i += n * 2;} else {- for (j = 0; j < n; j++) {- b = data[i++];+ for (var j = 0; j < n; j++) {+ var b = data[i++];stack.push((b << 8) | data[i++]);}}@@ -21803,7 +21582,7 @@ var Font = (function FontClosure() {if (inFDEF || inELSE) {i += n;} else {- for (j = 0; j < n; j++) {+ for (var j = 0; j < n; j++) {stack.push(data[i++]);}}@@ -21812,15 +21591,15 @@ var Font = (function FontClosure() {if (inFDEF || inELSE) {i += n * 2;} else {- for (j = 0; j < n; j++) {- b = data[i++];+ for (var j = 0; j < n; j++) {+ var b = data[i++];stack.push((b << 8) | data[i++]);}}} else if (op === 0x2B && !tooComplexToFollowFunctions) { // CALLif (!inFDEF && !inELSE) {// collecting inforamtion about which functions are used- funcId = stack[stack.length - 1];+ var funcId = stack[stack.length - 1];ttContext.functionsUsed[funcId] = true;if (funcId in ttContext.functionsStackDeltas) {stack.length += ttContext.functionsStackDeltas[funcId];@@ -21828,12 +21607,7 @@ var Font = (function FontClosure() {functionsCalled.indexOf(funcId) < 0) {callstack.push({data: data, i: i, stackTop: stack.length - 1});functionsCalled.push(funcId);- pc = ttContext.functionsDefined[funcId];- if (!pc) {- warn('TT: CALL non-existent function');- ttContext.hintsValid = false;- return;- }+ var pc = ttContext.functionsDefined[funcId];data = pc.data;i = pc.i;}@@ -21846,20 +21620,15 @@ var Font = (function FontClosure() {inFDEF = true;// collecting inforamtion about which functions are definedlastDeff = i;- funcId = stack.pop();+ var funcId = stack.pop();ttContext.functionsDefined[funcId] = {data: data, i: i};} else if (op === 0x2D) { // ENDF - end of functionif (inFDEF) {inFDEF = false;lastEndf = i;} else {- pc = callstack.pop();- if (!pc) {- warn('TT: ENDF bad stack');- ttContext.hintsValid = false;- return;- }- funcId = functionsCalled.pop();+ var pc = callstack.pop();+ var funcId = functionsCalled.pop();data = pc.data;i = pc.i;ttContext.functionsStackDeltas[funcId] =@@ -21883,13 +21652,9 @@ var Font = (function FontClosure() {}--ifLevel;} else if (op === 0x1C) { // JMPR- if (!inFDEF && !inELSE) {- var offset = stack[stack.length - 1];- // only jumping forward to prevent infinite loop- if (offset > 0) {- i += offset - 1;- }- }+ var offset = stack[stack.length - 1];+ // only jumping forward to prevent infinite loop+ if (offset > 0) { i += offset - 1; }}// Adjusting stack not extactly, but just enough to get function idif (!inFDEF && !inELSE) {@@ -21929,11 +21694,6 @@ var Font = (function FontClosure() {if (ttContext.tooComplexToFollowFunctions) {return;}- if (ttContext.functionsDefined.length > maxFunctionDefs) {- warn('TT: more functions defined than expected');- ttContext.hintsValid = false;- return;- }for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {if (j > maxFunctionDefs) {warn('TT: invalid function id: ' + j);@@ -21952,14 +21712,13 @@ var Font = (function FontClosure() {if (content.length > 1) {// concatenating the content itemsvar newLength = 0;- var j, jj;- for (j = 0, jj = content.length; j < jj; j++) {+ for (var j = 0, jj = content.length; j < jj; j++) {newLength += content[j].length;}newLength = (newLength + 3) & ~3;var result = new Uint8Array(newLength);var pos = 0;- for (j = 0, jj = content.length; j < jj; j++) {+ for (var j = 0, jj = content.length; j < jj; j++) {result.set(content[j], pos);pos += content[j].length;}@@ -21968,7 +21727,7 @@ var Font = (function FontClosure() {}}- function sanitizeTTPrograms(fpgm, prep, cvt) {+ function sanitizeTTPrograms(fpgm, prep) {var ttContext = {functionsDefined: [],functionsUsed: [],@@ -21985,103 +21744,81 @@ var Font = (function FontClosure() {if (fpgm) {checkInvalidFunctions(ttContext, maxFunctionDefs);}- if (cvt && (cvt.length & 1)) {- var cvtData = new Uint8Array(cvt.length + 1);- cvtData.set(cvt.data);- cvt.data = cvtData;- }return ttContext.hintsValid;}// The following steps modify the original font data, making copyfont = new Stream(new Uint8Array(font.getBytes()));- var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp',- 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];+ // Check that required tables are present+ var requiredTables = ['OS/2', 'cmap', 'head', 'hhea',+ 'hmtx', 'maxp', 'name', 'post'];var header = readOpenTypeHeader(font);var numTables = header.numTables;- var cff, cffFile;- var tables = { 'OS/2': null, cmap: null, head: null, hhea: null,- hmtx: null, maxp: null, name: null, post: null };- var table, tableData;+ var cmap, post, maxp, hhea, hmtx, head, os2;+ var glyf, fpgm, loca, prep, cvt;+ var tables = [];for (var i = 0; i < numTables; i++) {- table = readTableEntry(font);- if (VALID_TABLES.indexOf(table.tag) < 0) {- continue; // skipping table if it's not a required or optional table- }- if (table.length === 0) {- continue; // skipping empty tables- }- tables[table.tag] = table;- }-- var isTrueType = !tables['CFF '];- if (!isTrueType) {- // OpenType font- if (!tables.head || !tables.hhea || !tables.maxp || !tables.post) {- // no major tables: throwing everything at CFFFont- cffFile = new Stream(tables['CFF '].data);- cff = new CFFFont(cffFile, properties);-- return this.convert(name, cff, properties);- }-- delete tables.glyf;- delete tables.loca;- delete tables.fpgm;- delete tables.prep;- delete tables['cvt '];- } else {- if (!tables.glyf || !tables.loca) {- error('Required "glyf" or "loca" tables are not found');+ var table = readTableEntry(font);+ var index = requiredTables.indexOf(table.tag);+ if (index != -1) {+ if (table.tag == 'cmap')+ cmap = table;+ else if (table.tag == 'post')+ post = table;+ else if (table.tag == 'maxp')+ maxp = table;+ else if (table.tag == 'hhea')+ hhea = table;+ else if (table.tag == 'hmtx')+ hmtx = table;+ else if (table.tag == 'head')+ head = table;+ else if (table.tag == 'OS/2')+ os2 = table;++ requiredTables.splice(index, 1);+ } else {+ if (table.tag == 'loca')+ loca = table;+ else if (table.tag == 'glyf')+ glyf = table;+ else if (table.tag == 'fpgm')+ fpgm = table;+ else if (table.tag == 'prep')+ prep = table;+ else if (table.tag == 'cvt ')+ cvt = table;+ else if (table.tag == 'CFF ')+ return null; // XXX: OpenType font is found, stopping+ else // skipping table if it's not a required or optional table+ continue;}+ tables.push(table);}- if (!tables.maxp) {- error('Required "maxp" table is not found');+ // Ensure the hmtx table contains the advance width and+ // sidebearings information for numGlyphs in the maxp table+ font.pos = (font.start || 0) + maxp.offset;+ var version = int32(font.getBytes(4));+ var numGlyphs = int16(font.getBytes(2));+ var maxFunctionDefs = 0;+ if (version >= 0x00010000 && maxp.length >= 22) {+ font.pos += 14;+ var maxFunctionDefs = int16(font.getBytes(2));}- font.pos = (font.start || 0) + tables.maxp.offset;- var version = font.getUint32();- var numGlyphs = font.getUint16();- var maxFunctionDefs = 0;- if (version >= 0x00010000 && tables.maxp.length >= 22) {- // maxZones can be invalid- font.pos += 8;- var maxZones = font.getUint16();- if (maxZones > 2) { // reset to 2 if font has invalid maxZones- tables.maxp.data[14] = 0;- tables.maxp.data[15] = 2;- }- font.pos += 4;- maxFunctionDefs = font.getUint16();- }-- var dupFirstEntry = false;- if (properties.type == 'CIDFontType2' && properties.toUnicode &&- properties.toUnicode[0] > '\u0000') {- // oracle's defect (see 3427), duplicating first entry- dupFirstEntry = true;- numGlyphs++;- tables.maxp.data[4] = numGlyphs >> 8;- tables.maxp.data[5] = numGlyphs & 255;- }-- var hintsValid = sanitizeTTPrograms(tables.fpgm, tables.prep,- tables['cvt '], maxFunctionDefs);+ var hintsValid = sanitizeTTPrograms(fpgm, prep, maxFunctionDefs);if (!hintsValid) {- delete tables.fpgm;- delete tables.prep;- delete tables['cvt '];+ tables.splice(tables.indexOf(fpgm), 1);+ fpgm = null;+ tables.splice(tables.indexOf(prep), 1);+ prep = null;}- // Tables needs to be written by ascendant alphabetic order- var tablesNames = Object.keys(tables);- tablesNames.sort();-- numTables = tablesNames.length;+ var numTables = tables.length + requiredTables.length;// header and new offsets. Table entry information is appended to the// end of file. The virtualOffset represents where to put the actual@@ -22095,238 +21832,342 @@ var Font = (function FontClosure() {// of missing tablescreateOpenTypeHeader(header.version, ttf, numTables);- // Ensure the hmtx table contains the advance width and- // sidebearings information for numGlyphs in the maxp table- sanitizeMetrics(font, tables.hhea, tables.hmtx, numGlyphs);+ sanitizeMetrics(font, hhea, hmtx, numGlyphs);- if (!tables.head) {- error('Required "head" table is not found');+ if (head) {+ sanitizeHead(head, numGlyphs, loca.length);}- sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);-- if (isTrueType) {- var isGlyphLocationsLong = int16(tables.head.data[50],- tables.head.data[51]);- sanitizeGlyphLocations(tables.loca, tables.glyf, numGlyphs,- isGlyphLocationsLong, hintsValid, dupFirstEntry);+ var isGlyphLocationsLong = int16([head.data[50], head.data[51]]);+ if (head && loca && glyf) {+ sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong,+ hintsValid);}- if (!tables.hhea) {- error('Required "hhea" table is not found');- }+ var emptyGlyphIds = [];+ if (glyf)+ findEmptyGlyphs(loca, isGlyphLocationsLong, emptyGlyphIds);// Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth// Sometimes it's 0. That needs to be fixed- if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {- tables.hhea.data[10] = 0xFF;- tables.hhea.data[11] = 0xFF;+ if (hhea.data[10] === 0 && hhea.data[11] === 0) {+ hhea.data[10] = 0xFF;+ hhea.data[11] = 0xFF;}// The 'post' table has glyphs names.- if (tables.post) {- var valid = readPostScriptTable(tables.post, properties, numGlyphs);+ if (post) {+ var valid = readPostScriptTable(post, properties, numGlyphs);if (!valid) {- tables.post = null;+ tables.splice(tables.indexOf(post), 1);+ post = null;}}- var charCodeToGlyphId = [], charCode;+ var glyphs, ids;if (properties.type == 'CIDFontType2') {+ // Replace the old CMAP table with a shiny new one+ // Type2 composite fonts map characters directly to glyphs so the cmap+ // table must be replaced.+ // canvas fillText will reencode some characters even if the font has a+ // glyph at that position - e.g. newline is converted to a space and+ // U+00AD (soft hyphen) is not drawn.+ // So, offset all the glyphs by 0xFF to avoid these cases and use+ // the encoding to map incoming characters to the new glyph positions+ if (!cmap) {+ cmap = {+ tag: 'cmap',+ data: null+ };+ tables.push(cmap);+ }+var cidToGidMap = properties.cidToGidMap || [];- var cMap = properties.cMap.map;- for (charCode in cMap) {- charCode |= 0;- var cid = cMap[charCode];- assert(cid.length === 1, 'Max size of CID is 65,535');- cid = cid.charCodeAt(0);- var glyphId = -1;- if (cidToGidMap.length === 0) {- glyphId = charCode;- } else if (cid in cidToGidMap) {- glyphId = cidToGidMap[cid];+ var gidToCidMap = [0];+ if (cidToGidMap.length > 0) {+ for (var j = cidToGidMap.length - 1; j >= 0; j--) {+ var gid = cidToGidMap[j];+ if (gid)+ gidToCidMap[gid] = j;+ }+ // filling the gaps using CID above the CIDs currently used in font+ var nextCid = cidToGidMap.length;+ for (var i = 1; i < numGlyphs; i++) {+ if (!gidToCidMap[i])+ gidToCidMap[i] = nextCid++;+ }+ }++ glyphs = [];+ ids = [];++ var usedUnicodes = [];+ var unassignedUnicodeItems = [];+ var toFontChar = this.cidToFontChar || this.toFontChar;+ for (var i = 1; i < numGlyphs; i++) {+ var cid = gidToCidMap[i] || i;+ var unicode = toFontChar[cid];+ if (!unicode || typeof unicode !== 'number' ||+ isSpecialUnicode(unicode) || unicode in usedUnicodes) {+ unassignedUnicodeItems.push(i);+ continue;}- if (glyphId >= 0 && glyphId < numGlyphs) {- charCodeToGlyphId[charCode] = glyphId;+ usedUnicodes[unicode] = true;+ glyphs.push({ unicode: unicode, code: cid });+ ids.push(i);+ }+ // unassigned codepoints will never be used for non-Identity CMap+ // because the input will be Unicode+ if (!this.cidToFontChar) {+ // trying to fit as many unassigned symbols as we can+ // in the range allocated for the user defined symbols+ var unusedUnicode = CMAP_GLYPH_OFFSET;+ for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) {+ var i = unassignedUnicodeItems[j];+ var cid = gidToCidMap[i] || i;+ while (unusedUnicode in usedUnicodes)+ unusedUnicode++;+ if (unusedUnicode >= CMAP_GLYPH_OFFSET + GLYPH_AREA_SIZE)+ break;+ var unicode = unusedUnicode++;+ this.toFontChar[cid] = unicode;+ usedUnicodes[unicode] = true;+ glyphs.push({ unicode: unicode, code: cid });+ ids.push(i);}}- if (dupFirstEntry) {- charCodeToGlyphId[0] = numGlyphs - 1;- }} else {+ this.useToFontChar = true;// Most of the following logic in this code branch is based on the// 9.6.6.4 of the PDF spec.- var cmapTable = readCmapTable(tables.cmap, font, this.isSymbolicFont);++ // TODO(mack):+ // We are using this.hasEncoding to mean that the encoding is either+ // MacRomanEncoding or WinAnsiEncoding (following spec in 9.6.6.4),+ // but this.hasEncoding is currently true for any encodings on the+ // Encodings object (e.g. MacExpertEncoding). So should consider using+ // better check for this.+ var cmapTable = readCmapTable(cmap, font, this.hasEncoding,+ this.isSymbolicFont);++ // TODO(mack): If the (3, 0) cmap table used, then the font is+ // symbolic. The range of charcodes in the cmap table should be+ // one of the following:+ // -> 0x0000 - 0x00FF+ // -> 0xF000 - 0xF0FF+ // -> 0xF100 - 0xF1FF+ // -> 0xF200 - 0xF2FF+ // If it is not, we should change not consider this a symbolic font+ this.isSymbolicFont = cmapTable.isSymbolicFont;+var cmapPlatformId = cmapTable.platformId;var cmapEncodingId = cmapTable.encodingId;var cmapMappings = cmapTable.mappings;var cmapMappingsLength = cmapMappings.length;- var hasEncoding = properties.differences.length ||- !!properties.baseEncodingName;-- // The spec seems to imply that if the font is symbolic the encoding- // should be ignored, this doesn't appear to work for 'preistabelle.pdf'- // where the the font is symbolic and it has an encoding.- if (hasEncoding &&- (cmapPlatformId === 3 && cmapEncodingId === 1 ||- cmapPlatformId === 1 && cmapEncodingId === 0)) {- var baseEncoding = [];- if (properties.baseEncodingName === 'MacRomanEncoding' ||- properties.baseEncodingName === 'WinAnsiEncoding') {- baseEncoding = Encodings[properties.baseEncodingName];+ var glyphs = [];+ var ids = [];+ for (var i = 0; i < cmapMappingsLength; ++i) {+ var cmapMapping = cmapMappings[i];+ var charcode = cmapMapping.charcode;+ var unicode = cmapCharcodeToUnicode(charcode, this.isSymbolicFont,+ cmapPlatformId, cmapEncodingId);++ if (!unicode) {+ // TODO(mack): gotta check if skipping mappings where we cannot find+ // a unicode is the correct behaviour+ continue;}- for (charCode = 0; charCode < 256; charCode++) {- var glyphName;- if (this.differences && charCode in this.differences) {- glyphName = this.differences[charCode];- } else if (charCode in baseEncoding &&- baseEncoding[charCode] !== '') {- glyphName = baseEncoding[charCode];- } else {- glyphName = Encodings.StandardEncoding[charCode];- }- if (!glyphName) {+ glyphs.push({+ code: charcode,+ unicode: unicode+ });+ ids.push(cmapMapping.glyphId);+ }++ var hasShortCmap = cmapTable.hasShortCmap;+ var toFontChar = this.toFontChar;++ if (hasShortCmap && ids.length == numGlyphs) {+ // Fixes the short cmap tables -- some generators use incorrect+ // glyph id.+ for (var i = 0, ii = ids.length; i < ii; i++) {+ ids[i] = i;+ }+ }++ // Rewrite the whole toFontChar dictionary with a new one using the+ // information from the mappings in the cmap table.+ var newToFontChar = [];+ if (this.isSymbolicFont) {+ for (var i = 0, ii = glyphs.length; i < ii; i++) {+ var glyph = glyphs[i];+ // For (3, 0) cmap tables:+ // The charcode key being stored in toFontChar is the lower byte+ // of the two-byte charcodes of the cmap table since according to+ // the spec: 'each byte from the string shall be prepended with the+ // high byte of the range [of charcodes in the cmap table], to form+ // a two-byte character, which shall be used to select the+ // associated glyph description from the subtable'.+ //+ // For (1, 0) cmap tables:+ // 'single bytes from the string shall be used to look up the+ // associated glyph descriptions from the subtable'. This means+ // charcodes in the cmap will be single bytes, so no-op since+ // glyph.code & 0xFF === glyph.code+ newToFontChar[glyph.code & 0xFF] = glyph.unicode;+ }+ } else {++ var encoding = properties.baseEncoding;+ var differences = properties.differences;++ // TODO(mack): check if it is necessary to shift control characters+ // for non-symbolic fonts so that browsers dont't render them using+ // space characters++ var glyphCodeMapping = cmapTable.glyphCodeMapping;+ for (var charcode = 0; charcode < encoding.length; ++charcode) {+ if (!encoding.hasOwnProperty(charcode)) {continue;}- var unicodeOrCharCode;- if (cmapPlatformId === 3 && cmapEncodingId === 1) {- unicodeOrCharCode = GlyphsUnicode[glyphName];- } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {- // TODO: the encoding needs to be updated with mac os table.- unicodeOrCharCode = Encodings.MacRomanEncoding.indexOf(glyphName);- }- var found = false;- for (i = 0; i < cmapMappingsLength; ++i) {- if (cmapMappings[i].charCode === unicodeOrCharCode) {- charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;- found = true;- break;- }+ // Since the cmap table that we will be writing out is a (3, 1)+ // unicode table, in this section we will rewrites the charcodes+ // in the pdf into unicodes++ var glyphName = encoding[charcode];+ // A nonsymbolic font should not have a Differences array, but+ // if it does have one, we should still use it+ if (charcode in differences) {+ glyphName = differences[charcode];}- if (!found && properties.glyphNames) {- // Try to map using the post table. There are currently no known- // pdfs that this fixes.- glyphId = properties.glyphNames.indexOf(glyphName);- if (glyphId > 0) {- charCodeToGlyphId[charCode] = glyphId;- }++ // Finally, any undefined entries in the table shall be filled+ // using StandardEncoding+ if (!glyphName) {+ glyphName = Encodings.StandardEncoding[charcode];}- }- } else {- // For (3, 0) cmap tables:- // The charcode key being stored in charCodeToGlyphId is the lower- // byte of the two-byte charcodes of the cmap table since according to- // the spec: 'each byte from the string shall be prepended with the- // high byte of the range [of charcodes in the cmap table], to form- // a two-byte character, which shall be used to select the- // associated glyph description from the subtable'.- //- // For (1, 0) cmap tables:- // 'single bytes from the string shall be used to look up the- // associated glyph descriptions from the subtable'. This means- // charcodes in the cmap will be single bytes, so no-op since- // glyph.charCode & 0xFF === glyph.charCode- for (i = 0; i < cmapMappingsLength; ++i) {- charCode = cmapMappings[i].charCode & 0xFF;- charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;++ // TODO(mack): Handle the case that the glyph name cannot be+ // mapped as specified, in which case the glyph name shall be+ // looked up in the font program's 'post' table (if one is+ // present) and the associated glyph id shall be used.+ //+ // For now, we're just using the '.notdef' glyph name in this+ // case.+ glyphName = glyphName || '.notdef';++ var unicode = GlyphsUnicode[glyphName];+ newToFontChar[charcode] = unicode;}}+ this.toFontChar = toFontChar = newToFontChar;++ createGlyphNameMap(glyphs, ids, properties);+ this.glyphNameMap = properties.glyphNameMap;}- if (charCodeToGlyphId.length === 0) {+ if (glyphs.length === 0) {// defines at least one glyph- charCodeToGlyphId[0] = 0;+ glyphs.push({ unicode: 0xF000, code: 0xF000, glyph: '.notdef' });+ ids.push(0);}// Converting glyphs and ids into font's cmap table- var newMapping = adjustMapping(charCodeToGlyphId, properties);- this.toFontChar = newMapping.toFontChar;- tables.cmap = {- tag: 'cmap',- data: createCmapTable(newMapping.charCodeToGlyphId)- };+ cmap.data = createCmapTable(glyphs, ids);+ var unicodeIsEnabled = [];+ for (var i = 0, ii = glyphs.length; i < ii; i++) {+ unicodeIsEnabled[glyphs[i].unicode] = true;+ }+ this.unicodeIsEnabled = unicodeIsEnabled;++ if (os2 && !validateOS2Table(os2)) {+ tables.splice(tables.indexOf(os2), 1);+ os2 = null;+ }- if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {+ if (!os2) {// extract some more font properties from the OpenType head and// hhea tables; yMin and descent value are always negativevar override = {- unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),- yMax: int16(tables.head.data[42], tables.head.data[43]),- yMin: int16(tables.head.data[38], tables.head.data[39]) - 0x10000,- ascent: int16(tables.hhea.data[4], tables.hhea.data[5]),- descent: int16(tables.hhea.data[6], tables.hhea.data[7]) - 0x10000+ unitsPerEm: int16([head.data[18], head.data[19]]),+ yMax: int16([head.data[42], head.data[43]]),+ yMin: int16([head.data[38], head.data[39]]) - 0x10000,+ ascent: int16([hhea.data[4], hhea.data[5]]),+ descent: int16([hhea.data[6], hhea.data[7]]) - 0x10000};- tables['OS/2'] = {+ tables.push({tag: 'OS/2',- data: stringToArray(createOS2Table(properties,- newMapping.charCodeToGlyphId,- override))- };+ data: stringToArray(createOS2Table(properties, glyphs, override))+ });}// Rewrite the 'post' table if needed- if (!tables.post) {- tables.post = {+ if (!post) {+ tables.push({tag: 'post',data: stringToArray(createPostTable(properties))- };- }-- if (!isTrueType) {- try {- // Trying to repair CFF file- cffFile = new Stream(tables['CFF '].data);- var parser = new CFFParser(cffFile, properties);- cff = parser.parse();- var compiler = new CFFCompiler(cff);- tables['CFF '].data = compiler.compile();- } catch (e) {- warn('Failed to compile font ' + properties.loadedName);- }+ });}// Re-creating 'name' table- if (!tables.name) {- tables.name = {+ if (requiredTables.indexOf('name') != -1) {+ tables.push({tag: 'name',data: stringToArray(createNameTable(this.name))- };+ });} else {// ... using existing 'name' table as prototype- var namePrototype = readNameTable(tables.name);- tables.name.data = stringToArray(createNameTable(name, namePrototype));+ for (var i = 0, ii = tables.length; i < ii; i++) {+ var table = tables[i];+ if (table.tag === 'name') {+ var namePrototype = readNameTable(table);+ table.data = stringToArray(createNameTable(name, namePrototype));+ break;+ }+ }}+ // Tables needs to be written by ascendant alphabetic order+ tables.sort(function tables_sort(a, b) {+ return (a.tag > b.tag) - (a.tag < b.tag);+ });+// rewrite the tables but tweak offsets- for (i = 0; i < numTables; i++) {- table = tables[tablesNames[i]];+ for (var i = 0, ii = tables.length; i < ii; i++) {+ var table = tables[i];var data = [];- tableData = table.data;- for (var j = 0, jj = tableData.length; j < jj; j++) {+ var tableData = table.data;+ for (var j = 0, jj = tableData.length; j < jj; j++)data.push(tableData[j]);- }createTableEntry(ttf, table.tag, data);}// Add the table datas- for (i = 0; i < numTables; i++) {- table = tables[tablesNames[i]];- tableData = table.data;- ttf.file += bytesToString(new Uint8Array(tableData));+ for (var i = 0, ii = tables.length; i < ii; i++) {+ var table = tables[i];+ var tableData = table.data;+ ttf.file += arrayToString(tableData);// 4-byte aligned data- while (ttf.file.length & 3) {+ while (ttf.file.length & 3)ttf.file += String.fromCharCode(0);- }}return stringToArray(ttf.file);},convert: function Font_convert(fontName, font, properties) {+ function isFixedPitch(glyphs) {+ for (var i = 0, ii = glyphs.length - 1; i < ii; i++) {+ if (glyphs[i] != glyphs[i + 1])+ return false;+ }+ return true;+ }+// The offsets object holds at the same time a representation of where// to write the table entry information about a table and another offset// representing the offset where to draw the actual data of a particular@@ -22340,70 +22181,63 @@ var Font = (function FontClosure() {createOpenTypeHeader('\x4F\x54\x54\x4F', otf, 9);- // TODO: Check the charstring widths to determine this.- properties.fixedPitch = false;-- var mapping = font.getGlyphMapping(properties);- var newMapping = adjustMapping(mapping, properties);- this.toFontChar = newMapping.toFontChar;- var numGlyphs = font.numGlyphs;+ var charstrings = font.charstrings;+ properties.fixedPitch = isFixedPitch(charstrings);- function getCharCode(charCodeToGlyphId, glyphId, addMap) {- for (var charCode in charCodeToGlyphId) {- if (glyphId === charCodeToGlyphId[charCode]) {- return charCode | 0;- }- }- if (addMap) {- newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =- glyphId;- return newMapping.nextAvailableFontCharCode++;- }- return null;+ var glyphNameMap = {};+ for (var i = 0; i < charstrings.length; ++i) {+ var charstring = charstrings[i];+ glyphNameMap[charstring.glyph] = charstring.unicode;}+ this.glyphNameMap = glyphNameMap;var seacs = font.seacs;- if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {+ if (SEAC_ANALYSIS_ENABLED && seacs) {+ var seacMap = [];var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;- var charset = font.getCharset();- var seacMap = Object.create(null);- for (var glyphId in seacs) {- glyphId |= 0;- var seac = seacs[glyphId];+ for (var i = 0; i < charstrings.length; ++i) {+ var charstring = charstrings[i];+ var seac = seacs[charstring.gid];+ if (!seac) {+ continue;+ }var baseGlyphName = Encodings.StandardEncoding[seac[2]];+ var baseUnicode = glyphNameMap[baseGlyphName];var accentGlyphName = Encodings.StandardEncoding[seac[3]];- var baseGlyphId = charset.indexOf(baseGlyphName);- var accentGlyphId = charset.indexOf(accentGlyphName);- if (baseGlyphId < 0 || accentGlyphId < 0) {+ var accentUnicode = glyphNameMap[accentGlyphName];+ if (!baseUnicode || !accentUnicode) {continue;}var accentOffset = {x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]};-- var charCode = getCharCode(mapping, glyphId);- if (charCode === null) {- // There's no point in mapping it if the char code was never mapped- // to begin with.- continue;- }- // Find a fontCharCode that maps to the base and accent glyphs. If one- // doesn't exists, create it.- var charCodeToGlyphId = newMapping.charCodeToGlyphId;- var baseFontCharCode = getCharCode(charCodeToGlyphId, baseGlyphId,- true);- var accentFontCharCode = getCharCode(charCodeToGlyphId, accentGlyphId,- true);- seacMap[charCode] = {- baseFontCharCode: baseFontCharCode,- accentFontCharCode: accentFontCharCode,+ seacMap[charstring.unicode] = {+ baseUnicode: baseUnicode,+ accentUnicode: accentUnicode,accentOffset: accentOffset};}properties.seacMap = seacMap;}+ if (!properties.hasEncoding && (properties.subtype == 'Type1C' ||+ properties.subtype == 'CIDFontType0C')) {+ var encoding = [];+ for (var i = 0; i < charstrings.length; ++i) {+ var charstring = charstrings[i];+ encoding[charstring.code] = charstring.glyph;+ }+ properties.baseEncoding = encoding;+ }+ if (properties.subtype == 'CIDFontType0C') {+ var toFontChar = [];+ for (var i = 0; i < charstrings.length; ++i) {+ var charstring = charstrings[i];+ toFontChar[charstring.code] = charstring.unicode;+ }+ this.toFontChar = toFontChar;+ }var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];var fields = {@@ -22411,65 +22245,62 @@ var Font = (function FontClosure() {'CFF ': font.data,// OS/2 and Windows Specific metrics- 'OS/2': stringToArray(createOS2Table(properties,- newMapping.charCodeToGlyphId)),+ 'OS/2': stringToArray(createOS2Table(properties, charstrings)),// Character to glyphs mapping- 'cmap': createCmapTable(newMapping.charCodeToGlyphId),+ 'cmap': createCmapTable(charstrings.slice(),+ ('glyphIds' in font) ? font.glyphIds : null),// Font header'head': (function fontFieldsHead() {return stringToArray(- '\x00\x01\x00\x00' + // Version number- '\x00\x00\x10\x00' + // fontRevision- '\x00\x00\x00\x00' + // checksumAdjustement- '\x5F\x0F\x3C\xF5' + // magicNumber- '\x00\x00' + // Flags- safeString16(unitsPerEm) + // unitsPerEM- '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date- '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date- '\x00\x00' + // xMin- safeString16(properties.descent) + // yMin- '\x0F\xFF' + // xMax- safeString16(properties.ascent) + // yMax- string16(properties.italicAngle ? 2 : 0) + // macStyle- '\x00\x11' + // lowestRecPPEM- '\x00\x00' + // fontDirectionHint- '\x00\x00' + // indexToLocFormat- '\x00\x00'); // glyphDataFormat+ '\x00\x01\x00\x00' + // Version number+ '\x00\x00\x10\x00' + // fontRevision+ '\x00\x00\x00\x00' + // checksumAdjustement+ '\x5F\x0F\x3C\xF5' + // magicNumber+ '\x00\x00' + // Flags+ safeString16(unitsPerEm) + // unitsPerEM+ '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // creation date+ '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + // modifification date+ '\x00\x00' + // xMin+ safeString16(properties.descent) + // yMin+ '\x0F\xFF' + // xMax+ safeString16(properties.ascent) + // yMax+ string16(properties.italicAngle ? 2 : 0) + // macStyle+ '\x00\x11' + // lowestRecPPEM+ '\x00\x00' + // fontDirectionHint+ '\x00\x00' + // indexToLocFormat+ '\x00\x00'); // glyphDataFormat})(),// Horizontal header'hhea': (function fontFieldsHhea() {return stringToArray(- '\x00\x01\x00\x00' + // Version number- safeString16(properties.ascent) + // Typographic Ascent- safeString16(properties.descent) + // Typographic Descent- '\x00\x00' + // Line Gap- '\xFF\xFF' + // advanceWidthMax- '\x00\x00' + // minLeftSidebearing- '\x00\x00' + // minRightSidebearing- '\x00\x00' + // xMaxExtent- safeString16(properties.capHeight) + // caretSlopeRise- safeString16(Math.tan(properties.italicAngle) *- properties.xHeight) + // caretSlopeRun- '\x00\x00' + // caretOffset- '\x00\x00' + // -reserved-- '\x00\x00' + // -reserved-- '\x00\x00' + // -reserved-- '\x00\x00' + // -reserved-- '\x00\x00' + // metricDataFormat- string16(numGlyphs)); // Number of HMetrics+ '\x00\x01\x00\x00' + // Version number+ safeString16(properties.ascent) + // Typographic Ascent+ safeString16(properties.descent) + // Typographic Descent+ '\x00\x00' + // Line Gap+ '\xFF\xFF' + // advanceWidthMax+ '\x00\x00' + // minLeftSidebearing+ '\x00\x00' + // minRightSidebearing+ '\x00\x00' + // xMaxExtent+ safeString16(properties.capHeight) + // caretSlopeRise+ safeString16(Math.tan(properties.italicAngle) *+ properties.xHeight) + // caretSlopeRun+ '\x00\x00' + // caretOffset+ '\x00\x00' + // -reserved-+ '\x00\x00' + // -reserved-+ '\x00\x00' + // -reserved-+ '\x00\x00' + // -reserved-+ '\x00\x00' + // metricDataFormat+ string16(charstrings.length + 1)); // Number of HMetrics})(),// Horizontal metrics'hmtx': (function fontFieldsHmtx() {- var charstrings = font.charstrings;var hmtx = '\x00\x00\x00\x00'; // Fake .notdef- for (var i = 1, ii = numGlyphs; i < ii; i++) {- // TODO: For CFF fonts the width should technically match th x in- // the glyph, but it doesn't seem to matter.- var charstring = charstrings ? charstrings[i - 1] : {};+ for (var i = 0, ii = charstrings.length; i < ii; i++) {+ var charstring = charstrings[i];var width = 'width' in charstring ? charstring.width : 0;hmtx += string16(width) + string16(0);}@@ -22479,8 +22310,8 @@ var Font = (function FontClosure() {// Maximum profile'maxp': (function fontFieldsMaxp() {return stringToArray(- '\x00\x00\x50\x00' + // Version number- string16(numGlyphs)); // Num of glyphs+ '\x00\x00\x50\x00' + // Version number+ string16(charstrings.length + 1)); // Num of glyphs})(),// Naming tables@@ -22490,132 +22321,166 @@ var Font = (function FontClosure() {'post': stringToArray(createPostTable(properties))};- var field;- for (field in fields) {+ for (var field in fields)createTableEntry(otf, field, fields[field]);- }- for (field in fields) {++ for (var field in fields) {var table = fields[field];- otf.file += bytesToString(new Uint8Array(table));+ otf.file += arrayToString(table);}return stringToArray(otf.file);},- /**- * Builds a char code to unicode map based on section 9.10 of the spec.- * @param {Object} properties Font properties object.- * @return {Object} Has two properties: 'toUnicode' which maps char codes to- * unicode (string) values and 'isIdentity' which is true if an identity map- * is used.- */- buildToUnicode: function Font_buildToUnicode(properties) {- var map = {- isIdentity: false,- toUnicode: null- };- // Section 9.10.2 Mapping Character Codes to Unicode Values- if (properties.toUnicode && properties.toUnicode.length !== 0) {- map.toUnicode = properties.toUnicode;- return map;- }- // According to the spec if the font is a simple font we should only map- // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or- // the differences array only contains adobe standard or symbol set names,- // in pratice it seems better to always try to create a toUnicode- // map based of the default encoding.- var toUnicode, charcode;- if (!properties.composite /* is simple font */) {- toUnicode = [];- var encoding = properties.defaultEncoding.slice();- // Merge in the differences array.- var differences = properties.differences;- for (charcode in differences) {- encoding[charcode] = differences[charcode];- }- for (charcode in encoding) {- // a) Map the character code to a character name.- var glyphName = encoding[charcode];- // b) Look up the character name in the Adobe Glyph List (see the- // Bibliography) to obtain the corresponding Unicode value.- if (glyphName === '' || !(glyphName in GlyphsUnicode)) {- // (undocumented) c) Few heuristics to recognize unknown glyphs- // NOTE: Adobe Reader does not do this step, but OSX Preview does- var code;- // Gxx glyph- if (glyphName.length === 3 &&- glyphName[0] === 'G' &&- (code = parseInt(glyphName.substr(1), 16))) {- toUnicode[charcode] = String.fromCharCode(code);- }- // Cddd glyph- if (glyphName.length >= 3 &&- glyphName[0] === 'C' &&- (code = +glyphName.substr(1))) {- toUnicode[charcode] = String.fromCharCode(code);+ buildToFontChar: function Font_buildToFontChar(toUnicode) {+ var result = [];+ var unusedUnicode = CMAP_GLYPH_OFFSET;+ for (var i = 0, ii = toUnicode.length; i < ii; i++) {+ var unicode = toUnicode[i];+ var fontCharCode = typeof unicode === 'object' ? unusedUnicode++ :+ unicode;+ if (typeof unicode !== 'undefined')+ result[i] = fontCharCode;+ }+ return result;+ },++ rebuildToUnicode: function Font_rebuildToUnicode(properties) {+ var firstChar = properties.firstChar, lastChar = properties.lastChar;+ var map = [];+ var toUnicode = this.toUnicode || this.cidToUnicode;+ if (toUnicode) {+ var isIdentityMap = toUnicode.length === 0;+ for (var i = firstChar, ii = lastChar; i <= ii; i++) {+ // TODO missing map the character according font's CMap+ map[i] = isIdentityMap ? i : toUnicode[i];+ }+ } else {+ for (var i = firstChar, ii = lastChar; i <= ii; i++) {+ var glyph = properties.differences[i];+ if (!glyph)+ glyph = properties.baseEncoding[i];+ if (!!glyph && (glyph in GlyphsUnicode))+ map[i] = GlyphsUnicode[glyph];+ }+ }+ this.toUnicode = map;+ },++ loadCidToUnicode: function Font_loadCidToUnicode(properties) {+ if (!properties.cidSystemInfo)+ return;++ var cidToUnicodeMap = [], unicodeToCIDMap = [];+ this.cidToUnicode = cidToUnicodeMap;+ this.unicodeToCID = unicodeToCIDMap;++ var cidEncoding = properties.cidEncoding;+ if (properties.toUnicode) {+ if (cidEncoding && cidEncoding.indexOf('Identity-') !== 0) {+ TODO('Need to create a reverse mapping from \'ToUnicode\' CMap');+ }+ return; // 'ToUnicode' CMap will be used+ }++ var cidSystemInfo = properties.cidSystemInfo;+ var cidToUnicode;+ if (cidSystemInfo) {+ cidToUnicode = CIDToUnicodeMaps[+ cidSystemInfo.registry + '-' + cidSystemInfo.ordering];+ }++ if (!cidToUnicode)+ return; // identity encoding++ var overwrite = HalfwidthCMaps[cidEncoding];+ var cid = 1, i, j, k, ii;+ for (i = 0, ii = cidToUnicode.length; i < ii; ++i) {+ var unicode = cidToUnicode[i];+ if (isArray(unicode)) {+ var length = unicode.length;+ for (j = 0; j < length; j++) {+ cidToUnicodeMap[cid] = k = unicode[j];+ if (!unicodeToCIDMap[k] || overwrite) {+ unicodeToCIDMap[k] = cid;}- continue;}- toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);- }- map.toUnicode = toUnicode;- return map;- }- // If the font is a composite font that uses one of the predefined CMaps- // listed in Table 118 (except Identity–H and Identity–V) or whose- // descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or- // Adobe-Korea1 character collection:- if (properties.composite && (- (properties.cMap.builtInCMap &&- !(properties.cMap instanceof IdentityCMap)) ||- (properties.cidSystemInfo.registry === 'Adobe' &&- (properties.cidSystemInfo.ordering === 'GB1' ||- properties.cidSystemInfo.ordering === 'CNS1' ||- properties.cidSystemInfo.ordering === 'Japan1' ||- properties.cidSystemInfo.ordering === 'Korea1')))) {- // Then:- // a) Map the character code to a character identifier (CID) according- // to the font’s CMap.- // b) Obtain the registry and ordering of the character collection used- // by the font’s CMap (for example, Adobe and Japan1) from its- // CIDSystemInfo dictionary.- var registry = properties.cidSystemInfo.registry;- var ordering = properties.cidSystemInfo.ordering;- // c) Construct a second CMap name by concatenating the registry and- // ordering obtained in step (b) in the format registry–ordering–UCS2- // (for example, Adobe–Japan1–UCS2).- var ucs2CMapName = new Name(registry + '-' + ordering + '-UCS2');- // d) Obtain the CMap with the name constructed in step (c) (available- // from the ASN Web site; see the Bibliography).- var ucs2CMap = CMapFactory.create(ucs2CMapName,- { url: PDFJS.cMapUrl, packed: PDFJS.cMapPacked }, null);- var cMap = properties.cMap;- toUnicode = [];- for (charcode in cMap.map) {- var cid = cMap.map[charcode];- assert(cid.length === 1, 'Max size of CID is 65,535');- // e) Map the CID obtained in step (a) according to the CMap obtained- // in step (d), producing a Unicode value.- var ucs2 = ucs2CMap.map[cid.charCodeAt(0)];- if (!ucs2) {- continue;+ cid++;+ } else if (typeof unicode === 'object') {+ var fillLength = unicode.f;+ if (fillLength) {+ k = unicode.c;+ for (j = 0; j < fillLength; ++j) {+ cidToUnicodeMap[cid] = k;+ if (!unicodeToCIDMap[k] || overwrite) {+ unicodeToCIDMap[k] = cid;+ }+ cid++;+ k++;+ }+ } else+ cid += unicode.s;+ } else if (unicode) {+ cidToUnicodeMap[cid] = unicode;+ if (!unicodeToCIDMap[unicode] || overwrite) {+ unicodeToCIDMap[unicode] = cid;}- toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) +- ucs2.charCodeAt(1));+ cid++;+ } else+ cid++;+ }++ if (!cidEncoding) {+ return;+ }+ if (cidEncoding.indexOf('Identity-') !== 0) {+ // input is already Unicode for non-Identity CMap encodings.+ this.cidToUnicode = [];+ // For CIDFontType2, however, we need cid-to-Unicode conversion+ // to rebuild cmap.+ if (properties.type == 'CIDFontType2') {+ this.cidToFontChar = cidToUnicodeMap;}- map.toUnicode = toUnicode;- return map;+ } else {+ // We don't have to do reverse conversions if the string is+ // already CID.+ this.unicodeToCID = [];}+ },- // The viewer's choice, just use an identity map.- toUnicode = [];- var firstChar = properties.firstChar, lastChar = properties.lastChar;- for (var i = firstChar; i <= lastChar; i++) {- toUnicode[i] = String.fromCharCode(i);+ bindDOM: function Font_bindDOM() {+ if (!this.data)+ return null;++ if (PDFJS.disableFontFace) {+ this.disableFontFace = true;+ return null;}- map.isIdentity = true;- map.toUnicode = toUnicode;- return map;++ var data = bytesToString(this.data);+ var fontName = this.loadedName;++ // Add the font-face rule to the document+ var url = ('url(data:' + this.mimetype + ';base64,' ++ window.btoa(data) + ');');+ var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';++ var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');+ if (!styleElement) {+ styleElement = document.createElement('style');+ styleElement.id = 'PDFJS_FONT_STYLE_TAG';+ document.documentElement.getElementsByTagName('head')[0].appendChild(+ styleElement);+ }++ var styleSheet = styleElement.sheet;+ styleSheet.insertRule(rule, styleSheet.cssRules.length);++ if (PDFJS.pdfBug && 'FontInspector' in globalScope &&+ globalScope['FontInspector'].enabled)+ globalScope['FontInspector'].fontAdded(this, url);++ return rule;},get spaceWidth() {@@ -22636,24 +22501,18 @@ var Font = (function FontClosure() {var glyphUnicode = GlyphsUnicode[glyphName];// finding the charcode via unicodeToCID mapvar charcode = 0;- if (this.composite) {- if (glyphUnicode in this.cMap.map) {- charcode = this.cMap.lookup(glyphUnicode).charCodeAt(0);- }- }+ if (this.composite)+ charcode = this.unicodeToCID[glyphUnicode];// ... via toUnicode map- if (!charcode && 'toUnicode' in this) {+ if (!charcode && 'toUnicode' in this)charcode = this.toUnicode.indexOf(glyphUnicode);- }// setting it to unicode if negative or undefined- if (charcode <= 0) {+ if (charcode <= 0)charcode = glyphUnicode;- }// trying to get width via charcodewidth = this.widths[charcode];- if (width) {+ if (width)break; // the non-zero width found- }}width = width || this.defaultWidth;// Do not shadow the property here. See discussion:@@ -22663,101 +22522,166 @@ var Font = (function FontClosure() {},charToGlyph: function Font_charToGlyph(charcode) {- var fontCharCode, width, operatorList;+ var fontCharCode, width, operatorList, disabled;- var widthCode = charcode;- if (this.cMap && charcode in this.cMap.map) {- widthCode = this.cMap.map[charcode].charCodeAt(0);- }- width = this.widths[widthCode];- width = isNum(width) ? width : this.defaultWidth;- var vmetric = this.vmetrics && this.vmetrics[widthCode];+ var width = this.widths[charcode];+ var vmetric = this.vmetrics && this.vmetrics[charcode];- var unicode = this.toUnicode[charcode] || charcode;- if (typeof unicode === 'number') {- unicode = String.fromCharCode(unicode);- }+ switch (this.type) {+ case 'CIDFontType0':+ var cid = this.unicodeToCID[charcode] || charcode;+ if (this.unicodeToCID.length > 0) {+ width = this.widths[cid];+ vmetric = this.vmetrics && this.vmetrics[cid];+ }+ if (this.noUnicodeAdaptation) {+ fontCharCode = this.toFontChar[charcode] || charcode;+ break;+ }+ // CIDFontType0 is not encoded in Unicode.+ fontCharCode = this.toFontChar[cid] || cid;+ break;+ case 'CIDFontType2':+ if (this.unicodeToCID.length > 0) {+ var cid = this.unicodeToCID[charcode] || charcode;+ width = this.widths[cid];+ vmetric = this.vmetrics && this.vmetrics[cid];+ fontCharCode = charcode;+ break;+ }+ fontCharCode = this.toFontChar[charcode] || charcode;+ break;+ case 'MMType1': // XXX at the moment only "standard" fonts are supported+ case 'Type1':+ var glyphName = this.differences[charcode] || this.encoding[charcode];+ if (!isNum(width))+ width = this.widths[glyphName];+ if (this.noUnicodeAdaptation) {+ fontCharCode = mapPrivateUseChars(GlyphsUnicode[glyphName] ||+ charcode);+ break;+ }+ fontCharCode = this.glyphNameMap[glyphName] ||+ GlyphsUnicode[glyphName] || charcode;+ break;+ case 'Type3':+ var glyphName = this.differences[charcode] || this.encoding[charcode];+ operatorList = this.charProcOperatorList[glyphName];+ fontCharCode = charcode;+ break;+ case 'TrueType':+ if (this.useToFontChar) {+ fontCharCode = this.toFontChar[charcode] || charcode;+ break;+ }+ var glyphName = this.differences[charcode] || this.encoding[charcode];+ if (!glyphName)+ glyphName = Encodings.StandardEncoding[charcode];+ if (!isNum(width))+ width = this.widths[glyphName];+ if (this.noUnicodeAdaptation) {+ fontCharCode = GlyphsUnicode[glyphName] || charcode;+ break;+ }+ if (!this.hasEncoding || this.isSymbolicFont) {+ fontCharCode = this.useToFontChar ? this.toFontChar[charcode] :+ charcode;+ break;+ }++ // MacRoman encoding address by re-encoding the cmap table- // First try the toFontChar map, if it's not there then try falling- // back to the char code.- fontCharCode = this.toFontChar[charcode] || charcode;- if (this.missingFile) {- fontCharCode = mapSpecialUnicodeValues(fontCharCode);+ fontCharCode = glyphName in this.glyphNameMap ?+ this.glyphNameMap[glyphName] : GlyphsUnicode[glyphName];+ break;+ default:+ warn('Unsupported font type: ' + this.type);+ break;}- if (this.type === 'Type3') {- // Font char code in this case is actually a glyph name.- operatorList = this.charProcOperatorList[fontCharCode];+ var unicodeChars = !('toUnicode' in this) ? charcode :+ this.toUnicode[charcode] || charcode;+ if (typeof unicodeChars === 'number') {+ unicodeChars = String.fromCharCode(unicodeChars);}+ width = isNum(width) ? width : this.defaultWidth;+ disabled = this.unicodeIsEnabled ?+ !this.unicodeIsEnabled[fontCharCode] : false;+var accent = null;- if (this.seacMap && this.seacMap[charcode]) {- var seac = this.seacMap[charcode];- fontCharCode = seac.baseFontCharCode;+ if (this.seacMap && this.seacMap[fontCharCode]) {+ var seac = this.seacMap[fontCharCode];+ fontCharCode = seac.baseUnicode;accent = {- fontChar: String.fromCharCode(seac.accentFontCharCode),+ fontChar: String.fromCharCode(seac.accentUnicode),offset: seac.accentOffset};}- var fontChar = String.fromCharCode(fontCharCode);-- var glyph = this.glyphCache[charcode];- if (!glyph ||- !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric,- operatorList)) {- glyph = new Glyph(fontChar, unicode, accent, width, vmetric,- operatorList);- this.glyphCache[charcode] = glyph;- }- return glyph;+ return {+ fontChar: String.fromCharCode(fontCharCode),+ unicode: unicodeChars,+ accent: accent,+ width: width,+ vmetric: vmetric,+ disabled: disabled,+ operatorList: operatorList+ };},charsToGlyphs: function Font_charsToGlyphs(chars) {var charsCache = this.charsCache;- var glyphs, glyph, charcode;+ var glyphs;// if we translated this string before, just grab it from the cacheif (charsCache) {glyphs = charsCache[chars];- if (glyphs) {+ if (glyphs)return glyphs;- }}// lazily create the translation cache- if (!charsCache) {+ if (!charsCache)charsCache = this.charsCache = Object.create(null);- }glyphs = [];var charsCacheKey = chars;- var i = 0, ii;- if (this.cMap) {+ var converter;+ var cidEncoding = this.cidEncoding;+ if (cidEncoding) {+ converter = CMapConverterList[cidEncoding];+ if (converter) {+ chars = converter(chars);+ } else if (cidEncoding.indexOf('Uni') !== 0 &&+ cidEncoding.indexOf('Identity-') !== 0) {+ warn('Unsupported CMap: ' + cidEncoding);+ }+ }+ if (!converter && this.wideChars) {// composite fonts have multi-byte strings convert the string from// single-byte to multi-byte- while (i < chars.length) {- var c = this.cMap.readCharCode(chars, i);- charcode = c[0];- var length = c[1];- i += length;- glyph = this.charToGlyph(charcode);+ // XXX assuming CIDFonts are two-byte - later need to extract the+ // correct byte encoding according to the PDF spec+ var length = chars.length - 1; // looping over two bytes at a time so+ // loop should never end on the last byte+ for (var i = 0; i < length; i++) {+ var charcode = int16([chars.charCodeAt(i++), chars.charCodeAt(i)]);+ var glyph = this.charToGlyph(charcode);glyphs.push(glyph);// placing null after each word break charcode (ASCII SPACE)- // Ignore occurences of 0x20 in multiple-byte codes.- if (length === 1 && chars.charCodeAt(i - 1) === 0x20) {+ if (charcode == 0x20)glyphs.push(null);- }}- } else {- for (i = 0, ii = chars.length; i < ii; ++i) {- charcode = chars.charCodeAt(i);- glyph = this.charToGlyph(charcode);+ }+ else {+ for (var i = 0, ii = chars.length; i < ii; ++i) {+ var charcode = chars.charCodeAt(i);+ var glyph = this.charToGlyph(charcode);glyphs.push(glyph);- if (charcode == 0x20) {+ if (charcode == 0x20)glyphs.push(null);- }}}@@ -22786,61 +22710,6 @@ var ErrorFont = (function ErrorFontClosure() {return ErrorFont;})();-/**- * Shared logic for building a char code to glyph id mapping for Type1 and- * simple CFF fonts. See section 9.6.6.2 of the spec.- * @param {Object} properties Font properties object.- * @param {Object} builtInEncoding The encoding contained within the actual font- * data.- * @param {Array} Array of glyph names where the index is the glyph ID.- * @returns {Object} A char code to glyph ID map.- */-function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {- var charCodeToGlyphId = Object.create(null);- var glyphId, charCode, baseEncoding;-- if (properties.baseEncodingName) {- // If a valid base encoding name was used, the mapping is initialized with- // that.- baseEncoding = Encodings[properties.baseEncodingName];- for (charCode = 0; charCode < baseEncoding.length; charCode++) {- glyphId = glyphNames.indexOf(baseEncoding[charCode]);- if (glyphId >= 0) {- charCodeToGlyphId[charCode] = glyphId;- }- }- } else if (!!(properties.flags & FontFlags.Symbolic)) {- // For a symbolic font the encoding should be the fonts built-in- // encoding.- for (charCode in builtInEncoding) {- charCodeToGlyphId[charCode] = builtInEncoding[charCode];- }- } else {- // For non-symbolic fonts that don't have a base encoding the standard- // encoding should be used.- baseEncoding = Encodings.StandardEncoding;- for (charCode = 0; charCode < baseEncoding.length; charCode++) {- glyphId = glyphNames.indexOf(baseEncoding[charCode]);- if (glyphId >= 0) {- charCodeToGlyphId[charCode] = glyphId;- }- }- }-- // Lastly, merge in the differences.- var differences = properties.differences;- if (differences) {- for (charCode in differences) {- var glyphName = differences[charCode];- glyphId = glyphNames.indexOf(glyphName);- if (glyphId >= 0) {- charCodeToGlyphId[charCode] = glyphId;- }- }- }- return charCodeToGlyphId;-}-/** CharStrings are encoded following the the CharString Encoding sequence* describe in Chapter 6 of the "Adobe Type1 Font Format" specification.@@ -22910,7 +22779,6 @@ var Type1CharString = (function Type1CharStringClosure() {convert: function Type1CharString_convert(encoded, subrs) {var count = encoded.length;var error = false;- var wx, sbx, subrNumber;for (var i = 0; i < count; i++) {var value = encoded[i];if (value < 32) {@@ -22968,7 +22836,7 @@ var Type1CharString = (function Type1CharStringClosure() {error = true;break;}- subrNumber = this.stack.pop();+ var subrNumber = this.stack.pop();error = this.convert(subrs[subrNumber], subrs);break;case 11: // return@@ -22980,8 +22848,8 @@ var Type1CharString = (function Type1CharStringClosure() {}// To convert to type2 we have to move the width value to the// first part of the charstring and then use hmoveto with lsb.- wx = this.stack.pop();- sbx = this.stack.pop();+ var wx = this.stack.pop();+ var sbx = this.stack.pop();this.lsb = sbx;this.width = wx;this.stack.push(sbx);@@ -23054,9 +22922,9 @@ var Type1CharString = (function Type1CharStringClosure() {// (dx, dy). The height argument will not be used for vmtx and// vhea tables reconstruction -- ignoring it.var wy = this.stack.pop();- wx = this.stack.pop();+ var wx = this.stack.pop();var sby = this.stack.pop();- sbx = this.stack.pop();+ var sbx = this.stack.pop();this.lsb = sbx;this.width = wx;this.stack.push(sbx, sby);@@ -23076,7 +22944,7 @@ var Type1CharString = (function Type1CharStringClosure() {error = true;break;}- subrNumber = this.stack.pop();+ var subrNumber = this.stack.pop();var numArgs = this.stack.pop();if (subrNumber === 0 && numArgs === 3) {var flexArgs = this.stack.splice(this.stack.length - 17, 17);@@ -23157,7 +23025,7 @@ var Type1CharString = (function Type1CharStringClosure() {if (keepStack) {this.stack.splice(start, howManyArgs);} else {- this.stack.length = 0;+ this.stack = [];}return false;}@@ -23198,10 +23066,10 @@ var Type1Parser = (function Type1ParserClosure() {}function isSpecial(c) {- return c === 0x2F || // '/'- c === 0x5B || c === 0x5D || // '[', ']'- c === 0x7B || c === 0x7D || // '{', '}'- c === 0x28 || c === 0x29; // '(', ')'+ return c === '/' ||+ c === '[' || c === ']' ||+ c === '{' || c === '}' ||+ c === '(' || c === ')';}function Type1Parser(stream, encrypted) {@@ -23209,7 +23077,6 @@ var Type1Parser = (function Type1ParserClosure() {stream = new Stream(decrypt(stream.getBytes(), EEXEC_ENCRYPT_KEY, 4));}this.stream = stream;- this.nextChar();}Type1Parser.prototype = {@@ -23245,39 +23112,36 @@ var Type1Parser = (function Type1ParserClosure() {return token === 'true' ? 1 : 0;},- nextChar : function Type1_nextChar() {- return (this.currentChar = this.stream.getByte());- },-getToken: function Type1Parser_getToken() {// Eat whitespace and comments.var comment = false;- var ch = this.currentChar;+ var ch;+ var stream = this.stream;while (true) {- if (ch === -1) {+ if ((ch = stream.lookChar()) === null)return null;- }if (comment) {- if (ch === 0x0A || ch === 0x0D) {+ if (ch === '\x0a' || ch === '\x0d') {comment = false;}- } else if (ch === 0x25) { // '%'+ } else if (ch === '%') {comment = true;} else if (!Lexer.isSpace(ch)) {break;}- ch = this.nextChar();+ stream.skip();}if (isSpecial(ch)) {- this.nextChar();- return String.fromCharCode(ch);+ stream.skip();+ return ch;}var token = '';do {- token += String.fromCharCode(ch);- ch = this.nextChar();- } while (ch >= 0 && !Lexer.isSpace(ch) && !isSpecial(ch));+ token += ch;+ stream.skip();+ ch = stream.lookChar();+ } while (ch !== null && !Lexer.isSpace(ch) && !isSpecial(ch));return token;},@@ -23298,7 +23162,7 @@ var Type1Parser = (function Type1ParserClosure() {}}};- var token, length, data, lenIV, encoded;+ var token;while ((token = this.getToken()) !== null) {if (token !== '/') {continue;@@ -23322,14 +23186,14 @@ var Type1Parser = (function Type1ParserClosure() {continue;}var glyph = this.getToken();- length = this.readInt();+ var length = this.readInt();this.getToken(); // read in 'RD' or '-|'- data = stream.makeSubStream(stream.pos, length);- lenIV = program.properties.privateData['lenIV'];- encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);+ var data = stream.makeSubStream(stream.pos + 1, length);+ var lenIV = program.properties.privateData['lenIV'];+ var encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY,+ lenIV);// Skip past the required space and binary data.- stream.skip(length);- this.nextChar();+ stream.skip(1 + length);token = this.getToken(); // read in 'ND' or '|-'if (token === 'noaccess') {this.getToken(); // read in 'def'@@ -23345,14 +23209,14 @@ var Type1Parser = (function Type1ParserClosure() {this.getToken(); // read in 'array'while ((token = this.getToken()) === 'dup') {var index = this.readInt();- length = this.readInt();+ var length = this.readInt();this.getToken(); // read in 'RD' or '-|'- data = stream.makeSubStream(stream.pos, length);- lenIV = program.properties.privateData['lenIV'];- encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY, lenIV);+ var data = stream.makeSubStream(stream.pos + 1, length);+ var lenIV = program.properties.privateData['lenIV'];+ var encoded = decrypt(data.getBytes(), CHAR_STRS_ENCRYPT_KEY,+ lenIV);// Skip past the required space and binary data.- stream.skip(length);- this.nextChar();+ stream.skip(1 + length);token = this.getToken(); // read in 'NP' or '|'if (token === 'noaccess') {this.getToken(); // read in 'put'@@ -23396,8 +23260,8 @@ var Type1Parser = (function Type1ParserClosure() {}for (var i = 0; i < charstrings.length; i++) {- glyph = charstrings[i].glyph;- encoded = charstrings[i].encoded;+ var glyph = charstrings[i].glyph;+ var encoded = charstrings[i].encoded;var charString = new Type1CharString();var error = charString.convert(encoded, subrs);var output = charString.output;@@ -23408,11 +23272,11 @@ var Type1Parser = (function Type1ParserClosure() {output = [14];}program.charstrings.push({- glyphName: glyph,- charstring: output,- width: charString.width,+ glyph: glyph,+ data: output,+ seac: charString.seac,lsb: charString.lsb,- seac: charString.seac+ width: charString.width});}@@ -23443,32 +23307,20 @@ var Type1Parser = (function Type1ParserClosure() {this.getToken(); // read in 'array'for (var j = 0; j < size; j++) {- token = this.getToken();- // skipping till first dup or def (e.g. ignoring for statement)- while (token !== 'dup' && token !== 'def') {- token = this.getToken();- if (token === null) {- return; // invalid header- }+ var token = this.getToken();+ if (token === 'dup') {+ var index = this.readInt();+ this.getToken(); // read in '/'+ var glyph = this.getToken();+ encoding[index] = glyph;+ this.getToken(); // read the in 'put'}- if (token === 'def') {- break; // read all array data- }- var index = this.readInt();- this.getToken(); // read in '/'- var glyph = this.getToken();- encoding[index] = glyph;- this.getToken(); // read the in 'put'}}- properties.builtInEncoding = encoding;- break;- case 'FontBBox':- var fontBBox = this.readNumberArray();- // adjusting ascent/descent- properties.ascent = fontBBox[3];- properties.descent = fontBBox[1];- properties.ascentScaled = true;+ if (properties.overridableEncoding && encoding) {+ properties.baseEncoding = encoding;+ break;+ }break;}}@@ -23516,7 +23368,7 @@ var CFFStandardStrings = ['odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex','udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall','Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',- 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',+ 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff','onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle','threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle','sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',@@ -23552,40 +23404,19 @@ var CFFStandardStrings = [// Type1Font is also a CIDFontType0.var Type1Font = function Type1Font(name, file, properties) {- // Some bad generators embed pfb file as is, we have to strip 6-byte headers.- // Also, length1 and length2 might be off by 6 bytes as well.- // http://www.math.ubc.ca/~cass/piscript/type1.pdf- var PFB_HEADER_SIZE = 6;- var headerBlockLength = properties.length1;- var eexecBlockLength = properties.length2;- var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);- var pfbHeaderPresent = pfbHeader[0] == 0x80 && pfbHeader[1] == 0x01;- if (pfbHeaderPresent) {- file.skip(PFB_HEADER_SIZE);- headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |- (pfbHeader[3] << 8) | pfbHeader[2];- }-// Get the data block containing glyphs and subrs informations- var headerBlock = new Stream(file.getBytes(headerBlockLength));+ var headerBlock = new Stream(file.getBytes(properties.length1));var headerBlockParser = new Type1Parser(headerBlock);headerBlockParser.extractFontHeader(properties);- if (pfbHeaderPresent) {- pfbHeader = file.getBytes(PFB_HEADER_SIZE);- eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |- (pfbHeader[3] << 8) | pfbHeader[2];- }-// Decrypt the data blocks and retrieve it's content- var eexecBlock = new Stream(file.getBytes(eexecBlockLength));+ var eexecBlock = new Stream(file.getBytes(properties.length2));var eexecBlockParser = new Type1Parser(eexecBlock, true);var data = eexecBlockParser.extractFontProgram();- for (var info in data.properties) {+ for (var info in data.properties)properties[info] = data.properties[info];- }- var charstrings = data.charstrings;+ var charstrings = this.getOrderedCharStrings(data.charstrings, properties);var type2Charstrings = this.getType2Charstrings(charstrings);var subrs = this.getType2Subrs(data.subrs);@@ -23596,37 +23427,35 @@ var Type1Font = function Type1Font(name, file, properties) {};Type1Font.prototype = {- get numGlyphs() {- return this.charstrings.length + 1;- },-- getCharset: function Type1Font_getCharset() {- var charset = ['.notdef'];- var charstrings = this.charstrings;- for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {- charset.push(charstrings[glyphId].glyphName);- }- return charset;- },-- getGlyphMapping: function Type1Font_getGlyphMapping(properties) {- var charstrings = this.charstrings;- var glyphNames = ['.notdef'], glyphId;- for (glyphId = 0; glyphId < charstrings.length; glyphId++) {- glyphNames.push(charstrings[glyphId].glyphName);- }- var encoding = properties.builtInEncoding;- if (encoding) {- var builtInEncoding = {};- for (var charCode in encoding) {- glyphId = glyphNames.indexOf(encoding[charCode]);- if (glyphId >= 0) {- builtInEncoding[charCode] = glyphId;- }- }+ getOrderedCharStrings: function Type1Font_getOrderedCharStrings(glyphs,+ properties) {+ var charstrings = [];+ var usedUnicodes = [];+ var i, length, glyphName;+ var unusedUnicode = CMAP_GLYPH_OFFSET;+ for (i = 0, length = glyphs.length; i < length; i++) {+ var item = glyphs[i];+ var glyphName = item.glyph;+ var unicode = glyphName in GlyphsUnicode ?+ GlyphsUnicode[glyphName] : unusedUnicode++;+ while (usedUnicodes[unicode]) {+ unicode = unusedUnicode++;+ }+ usedUnicodes[unicode] = true;+ charstrings.push({+ glyph: glyphName,+ unicode: unicode,+ gid: i,+ charstring: item.data,+ width: item.width,+ lsb: item.lsb+ });}- return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);+ charstrings.sort(function charstrings_sort(a, b) {+ return a.unicode - b.unicode;+ });+ return charstrings;},getSeacs: function Type1Font_getSeacs(charstrings) {@@ -23635,8 +23464,7 @@ Type1Font.prototype = {for (i = 0, ii = charstrings.length; i < ii; i++) {var charstring = charstrings[i];if (charstring.seac) {- // Offset by 1 for .notdef- seacMap[i + 1] = charstring.seac;+ seacMap[i] = charstring.seac;}}return seacMap;@@ -23654,22 +23482,19 @@ Type1Font.prototype = {getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {var bias = 0;var count = type1Subrs.length;- if (count < 1133) {+ if (count < 1133)bias = 107;- } else if (count < 33769) {+ else if (count < 33769)bias = 1131;- } else {+ elsebias = 32768;- }// Add a bunch of empty subrs to deal with the Type2 biasvar type2Subrs = [];- var i;- for (i = 0; i < bias; i++) {+ for (var i = 0; i < bias; i++)type2Subrs.push([0x0B]);- }- for (i = 0; i < count; i++) {+ for (var i = 0; i < count; i++) {type2Subrs.push(type1Subrs[i]);}@@ -23710,23 +23535,22 @@ Type1Font.prototype = {var count = glyphs.length;var charsetArray = [0];- var i, ii;- for (i = 0; i < count; i++) {- var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);- // TODO: Insert the string and correctly map it. Previously it was- // thought mapping names that aren't in the standard strings to .notdef- // was fine, however in issue818 when mapping them all to .notdef the- // adieresis glyph no longer worked.- if (index == -1) {+ for (var i = 0; i < count; i++) {+ var index = CFFStandardStrings.indexOf(charstrings[i].glyph);+ // Some characters like asterikmath && circlecopyrt are+ // missing from the original strings, for the moment let's+ // map them to .notdef and see later if it cause any+ // problems+ if (index == -1)index = 0;- }+charsetArray.push((index >> 8) & 0xff, index & 0xff);}cff.charset = new CFFCharset(false, 0, [], charsetArray);var charStringsIndex = new CFFIndex();charStringsIndex.add([0x8B, 0x0E]); // .notdef- for (i = 0; i < count; i++) {+ for (var i = 0; i < count; i++) {charStringsIndex.add(glyphs[i]);}cff.charStrings = charStringsIndex;@@ -23749,11 +23573,10 @@ Type1Font.prototype = {'StdHW','StdVW'];- for (i = 0, ii = fields.length; i < ii; i++) {+ for (var i = 0, ii = fields.length; i < ii; i++) {var field = fields[i];- if (!properties.privateData.hasOwnProperty(field)) {+ if (!properties.privateData.hasOwnProperty(field))continue;- }var value = properties.privateData[field];if (isArray(value)) {// All of the private dictionary array data in CFF must be stored as@@ -23767,7 +23590,7 @@ Type1Font.prototype = {cff.topDict.privateDict = privateDict;var subrIndex = new CFFIndex();- for (i = 0, ii = subrs.length; i < ii; i++) {+ for (var i = 0, ii = subrs.length; i < ii; i++) {subrIndex.add(subrs[i]);}privateDict.subrsIndex = subrIndex;@@ -23784,7 +23607,7 @@ var CFFFont = (function CFFFontClosure() {var parser = new CFFParser(file, properties);this.cff = parser.parse();var compiler = new CFFCompiler(this.cff);- this.seacs = this.cff.seacs;+ this.readExtra();try {this.data = compiler.compile();} catch (e) {@@ -23796,42 +23619,87 @@ var CFFFont = (function CFFFontClosure() {}CFFFont.prototype = {- get numGlyphs() {- return this.cff.charStrings.count;- },- getCharset: function CFFFont_getCharset() {- return this.cff.charset.charset;+ readExtra: function CFFFont_readExtra() {+ // charstrings contains info about glyphs (one element per glyph+ // containing mappings for {unicode, width})+ var charstrings = this.getCharStrings();++ // create the mapping between charstring and glyph id+ var glyphIds = [];+ for (var i = 0, ii = charstrings.length; i < ii; i++)+ glyphIds.push(charstrings[i].gid);++ this.charstrings = charstrings;+ this.glyphIds = glyphIds;+ this.seacs = this.cff.seacs;},- getGlyphMapping: function CFFFont_getGlyphMapping() {+ getCharStrings: function CFFFont_getCharStrings() {var cff = this.cff;- var properties = this.properties;var charsets = cff.charset.charset;- var charCodeToGlyphId;- var glyphId;-- if (properties.composite) {- charCodeToGlyphId = Object.create(null);- if (cff.isCIDFont) {- // If the font is actually a CID font then we should use the charset- // to map CIDs to GIDs.- for (glyphId = 0; glyphId < charsets.length; glyphId++) {- var cidString = String.fromCharCode(charsets[glyphId]);- var charCode = properties.cMap.map.indexOf(cidString);- charCodeToGlyphId[charCode] = glyphId;- }+ var encoding = cff.encoding ? cff.encoding.encoding : null;+ var charstrings = [];+ var unicodeUsed = [];+ var unassignedUnicodeItems = [];+ var inverseEncoding = [];+ var gidStart = 0;+ // Even though the CFF font may not actually be a CID font is could have+ // CID information in the font descriptor.+ if (this.properties.cidSystemInfo) {+ // According to section 9.7.4.2 if the font is actually a CID font then+ // we should use the charset to map CIDs to GIDs. If it is not actually+ // a CID font then CIDs can be mapped directly to GIDs.+ if (this.cff.isCIDFont) {+ inverseEncoding = charsets;} else {- // If it is NOT actually a CID font then CIDs should be mapped- // directly to GIDs.- for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {- charCodeToGlyphId[glyphId] = glyphId;+ for (var i = 0, ii = charsets.length; i < charsets.length; i++) {+ inverseEncoding.push(i);}}- return charCodeToGlyphId;+ } else {+ for (var charcode in encoding)+ inverseEncoding[encoding[charcode]] = charcode | 0;+ if (charsets[0] === '.notdef') {+ gidStart = 1;+ }}- var encoding = cff.encoding ? cff.encoding.encoding : null;- charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);- return charCodeToGlyphId;+ for (var i = gidStart, ii = charsets.length; i < ii; i++) {+ var glyph = charsets[i];++ var code = inverseEncoding[i];+ if (!code || isSpecialUnicode(code)) {+ unassignedUnicodeItems.push(i);+ continue;+ }+ charstrings.push({+ unicode: code,+ code: code,+ gid: i,+ glyph: glyph+ });+ unicodeUsed[code] = true;+ }++ var nextUnusedUnicode = CMAP_GLYPH_OFFSET;+ for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; ++j) {+ var i = unassignedUnicodeItems[j];+ // giving unicode value anyway+ while (nextUnusedUnicode in unicodeUsed)+ nextUnusedUnicode++;+ var unicode = nextUnusedUnicode++;+ charstrings.push({+ unicode: unicode,+ code: inverseEncoding[i] || 0,+ gid: i,+ glyph: charsets[i]+ });+ }++ // sort the array by the unicode value (again)+ charstrings.sort(function getCharStringsSort(a, b) {+ return a.unicode - b.unicode;+ });+ return charstrings;}};@@ -24013,17 +23881,12 @@ var CFFParser = (function CFFParserClosure() {},parseHeader: function CFFParser_parseHeader() {var bytes = this.bytes;- var bytesLength = bytes.length;var offset = 0;- // Prevent an infinite loop, by checking that the offset is within the- // bounds of the bytes array. Necessary in empty, or invalid, font files.- while (offset < bytesLength && bytes[offset] !== 1) {+ while (bytes[offset] != 1)++offset;- }- if (offset >= bytesLength) {- error('Invalid CFF header');- } else if (offset !== 0) {++ if (offset !== 0) {info('cff data is shifted');bytes = bytes.subarray(offset);this.bytes = bytes;@@ -24033,7 +23896,7 @@ var CFFParser = (function CFFParserClosure() {var hdrSize = bytes[2];var offSize = bytes[3];var header = new CFFHeader(major, minor, hdrSize, offSize);- return { obj: header, endPos: hdrSize };+ return {obj: header, endPos: hdrSize};},parseDict: function CFFParser_parseDict(dict) {var pos = 0;@@ -24075,14 +23938,12 @@ var CFFParser = (function CFFParserClosure() {var b1 = b >> 4;var b2 = b & 15;- if (b1 == eof) {+ if (b1 == eof)break;- }str += lookup[b1];- if (b2 == eof) {+ if (b2 == eof)break;- }str += lookup[b2];}return parseFloat(str);@@ -24091,14 +23952,13 @@ var CFFParser = (function CFFParserClosure() {var operands = [];var entries = [];- pos = 0;+ var pos = 0;var end = dict.length;while (pos < end) {var b = dict[pos];if (b <= 21) {- if (b === 12) {+ if (b === 12)b = (b << 8) | dict[++pos];- }entries.push([b, operands]);operands = [];++pos;@@ -24115,14 +23975,13 @@ var CFFParser = (function CFFParserClosure() {var offsets = [];var start = pos;var end = pos;- var i, ii;if (count !== 0) {var offsetSize = bytes[pos++];// add 1 for offset to determine size of last objectvar startPos = pos + ((count + 1) * offsetSize) - 1;- for (i = 0, ii = count + 1; i < ii; ++i) {+ for (var i = 0, ii = count + 1; i < ii; ++i) {var offset = 0;for (var j = 0; j < offsetSize; ++j) {offset <<= 8;@@ -24132,7 +23991,7 @@ var CFFParser = (function CFFParserClosure() {}end = offsets[count];}- for (i = 0, ii = offsets.length - 1; i < ii; ++i) {+ for (var i = 0, ii = offsets.length - 1; i < ii; ++i) {var offsetStart = offsets[i];var offsetEnd = offsets[i + 1];cffIndex.add(bytes.subarray(offsetStart, offsetEnd));@@ -24162,7 +24021,7 @@ var CFFParser = (function CFFParserClosure() {}data[j] = c;}- names.push(bytesToString(data));+ names.push(String.fromCharCode.apply(null, data));}return names;},@@ -24170,7 +24029,7 @@ var CFFParser = (function CFFParserClosure() {var strings = new CFFStrings();for (var i = 0, ii = index.count; i < ii; ++i) {var data = index.get(i);- strings.add(bytesToString(data));+ strings.add(String.fromCharCode.apply(null, data));}return strings;},@@ -24233,14 +24092,14 @@ var CFFParser = (function CFFParserClosure() {stack[stackSize] = value - 139;stackSize++;} else if (value >= 247 && value <= 254) { // number (+1 bytes)- stack[stackSize] = (value < 251 ?- ((value - 247) << 8) + data[j] + 108 :- -((value - 251) << 8) - data[j] - 108);+ stack[stackSize] = value < 251 ?+ ((value - 247) << 8) + data[j] + 108 :+ -((value - 251) << 8) - data[j] - 108;j++;stackSize++;} else if (value == 255) { // number (32 bit)stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |- (data[j + 2] << 8) | data[j + 3]) / 65536;+ (data[j + 2] << 8) | data[j + 3]) / 65536;j += 4;stackSize++;} else if (value == 19 || value == 20) {@@ -24319,9 +24178,8 @@ var CFFParser = (function CFFParserClosure() {parentDict.privateDict = privateDict;// Parse the Subrs index also since it's relative to the private dict.- if (!privateDict.getByName('Subrs')) {+ if (!privateDict.getByName('Subrs'))return;- }var subrsOffset = privateDict.getByName('Subrs');var relativeOffset = offset + subrsOffset;// Validate the offset.@@ -24348,34 +24206,31 @@ var CFFParser = (function CFFParserClosure() {var start = pos;var format = bytes[pos++];var charset = ['.notdef'];- var id, count, i;// subtract 1 for the .notdef glyphlength -= 1;switch (format) {case 0:- for (i = 0; i < length; i++) {- id = (bytes[pos++] << 8) | bytes[pos++];+ for (var i = 0; i < length; i++) {+ var id = (bytes[pos++] << 8) | bytes[pos++];charset.push(cid ? id : strings.get(id));}break;case 1:while (charset.length <= length) {- id = (bytes[pos++] << 8) | bytes[pos++];- count = bytes[pos++];- for (i = 0; i <= count; i++) {+ var id = (bytes[pos++] << 8) | bytes[pos++];+ var count = bytes[pos++];+ for (var i = 0; i <= count; i++)charset.push(cid ? id++ : strings.get(id++));- }}break;case 2:while (charset.length <= length) {- id = (bytes[pos++] << 8) | bytes[pos++];- count = (bytes[pos++] << 8) | bytes[pos++];- for (i = 0; i <= count; i++) {+ var id = (bytes[pos++] << 8) | bytes[pos++];+ var count = (bytes[pos++] << 8) | bytes[pos++];+ for (var i = 0; i <= count; i++)charset.push(cid ? id++ : strings.get(id++));- }}break;default:@@ -24395,15 +24250,15 @@ var CFFParser = (function CFFParserClosure() {var bytes = this.bytes;var predefined = false;var hasSupplement = false;- var format, i, ii;+ var format;var raw = null;function readSupplement() {var supplementsCount = bytes[pos++];- for (i = 0; i < supplementsCount; i++) {+ for (var i = 0; i < supplementsCount; i++) {var code = bytes[pos++];var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);- encoding[code] = charset.indexOf(strings.get(sid));+ encoding[code] = properties.differences.indexOf(strings.get(sid));}}@@ -24412,7 +24267,7 @@ var CFFParser = (function CFFParserClosure() {format = pos;var baseEncoding = pos ? Encodings.ExpertEncoding :Encodings.StandardEncoding;- for (i = 0, ii = charset.length; i < ii; i++) {+ for (var i = 0, ii = charset.length; i < ii; i++) {var index = baseEncoding.indexOf(charset[i]);if (index != -1) {encoding[index] = i;@@ -24420,24 +24275,22 @@ var CFFParser = (function CFFParserClosure() {}} else {var dataStart = pos;- format = bytes[pos++];+ var format = bytes[pos++];switch (format & 0x7f) {case 0:var glyphsCount = bytes[pos++];- for (i = 1; i <= glyphsCount; i++) {+ for (var i = 1; i <= glyphsCount; i++)encoding[bytes[pos++]] = i;- }break;case 1:var rangesCount = bytes[pos++];var gid = 1;- for (i = 0; i < rangesCount; i++) {+ for (var i = 0; i < rangesCount; i++) {var start = bytes[pos++];var left = bytes[pos++];- for (var j = start; j <= start + left; j++) {+ for (var j = start; j <= start + left; j++)encoding[j] = gid++;- }}break;@@ -24466,24 +24319,21 @@ var CFFParser = (function CFFParserClosure() {var bytes = this.bytes;var format = bytes[pos++];var fdSelect = [];- var i;-switch (format) {case 0:- for (i = 0; i < length; ++i) {+ for (var i = 0; i < length; ++i) {var id = bytes[pos++];fdSelect.push(id);}break;case 3:var rangesCount = (bytes[pos++] << 8) | bytes[pos++];- for (i = 0; i < rangesCount; ++i) {+ for (var i = 0; i < rangesCount; ++i) {var first = (bytes[pos++] << 8) | bytes[pos++];var fdIndex = bytes[pos++];var next = (bytes[pos] << 8) | bytes[pos + 1];- for (var j = first; j < next; ++j) {+ for (var j = first; j < next; ++j)fdSelect.push(fdIndex);- }}// Advance past the sentinel(next).pos += 2;@@ -24537,12 +24387,10 @@ var CFFStrings = (function CFFStringsClosure() {}CFFStrings.prototype = {get: function CFFStrings_get(index) {- if (index >= 0 && index <= 390) {+ if (index >= 0 && index <= 390)return CFFStandardStrings[index];- }- if (index - 391 <= this.strings.length) {+ if (index - 391 <= this.strings.length)return this.strings[index - 391];- }return CFFStandardStrings[0];},add: function CFFStrings_add(value) {@@ -24593,18 +24441,15 @@ var CFFDict = (function CFFDictClosure() {CFFDict.prototype = {// value should always be an arraysetByKey: function CFFDict_setByKey(key, value) {- if (!(key in this.keyToNameMap)) {+ if (!(key in this.keyToNameMap))return false;- }// ignore empty values- if (value.length === 0) {+ if (value.length === 0)return true;- }var type = this.types[key];// remove the array wrapping these types of values- if (type === 'num' || type === 'sid' || type === 'offset') {+ if (type === 'num' || type === 'sid' || type === 'offset')value = value[0];- }this.values[key] = value;return true;},@@ -24618,13 +24463,11 @@ var CFFDict = (function CFFDictClosure() {return this.nameToKeyMap[name] in this.values;},getByName: function CFFDict_getByName(name) {- if (!(name in this.nameToKeyMap)) {+ if (!(name in this.nameToKeyMap))error('Invalid dictionary name "' + name + '"');- }var key = this.nameToKeyMap[name];- if (!(key in this.values)) {+ if (!(key in this.values))return this.defaults[key];- }return this.values[key];},removeByName: function CFFDict_removeByName(name) {@@ -24697,9 +24540,8 @@ var CFFTopDict = (function CFFTopDictClosure() {];var tables = null;function CFFTopDict(strings) {- if (tables === null) {+ if (tables === null)tables = CFFDict.createTables(layout);- }CFFDict.call(this, tables, strings);this.privateDict = null;}@@ -24730,9 +24572,8 @@ var CFFPrivateDict = (function CFFPrivateDictClosure() {];var tables = null;function CFFPrivateDict(strings) {- if (tables === null) {+ if (tables === null)tables = CFFDict.createTables(layout);- }CFFDict.call(this, tables, strings);this.subrsIndex = null;}@@ -24797,9 +24638,8 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {return key in this.offsets;},track: function CFFOffsetTracker_track(key, location) {- if (key in this.offsets) {+ if (key in this.offsets)error('Already tracking location of ' + key);- }this.offsets[key] = location;},offset: function CFFOffsetTracker_offset(value) {@@ -24810,9 +24650,8 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,values,output) {- if (!(key in this.offsets)) {+ if (!(key in this.offsets))error('Not tracking location of ' + key);- }var data = output.data;var dataOffset = this.offsets[key];var size = 5;@@ -24824,9 +24663,8 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {var offset4 = offset0 + 4;// It's easy to screw up offsets so perform this sanity check.if (data[offset0] !== 0x1d || data[offset1] !== 0 ||- data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {+ data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0)error('writing to an offset that is not empty');- }var value = values[i];data[offset0] = 0x1d;data[offset1] = (value >> 24) & 0xFF;@@ -24841,6 +24679,13 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {// Takes a CFF and converts it to the binary representation.var CFFCompiler = (function CFFCompilerClosure() {+ function stringToArray(str) {+ var array = [];+ for (var i = 0, ii = str.length; i < ii; ++i)+ array[i] = str.charCodeAt(i);++ return array;+ }function CFFCompiler(cff) {this.cff = cff;}@@ -24937,7 +24782,7 @@ var CFFCompiler = (function CFFCompilerClosure() {output.add(fdSelect);// It is unclear if the sub font dictionary can have CID related// dictionary keys, but the sanitizer doesn't like them so remove them.- compiled = this.compileTopDicts(cff.fdArray, output.length, true);+ var compiled = this.compileTopDicts(cff.fdArray, output.length, true);topDictTracker.setEntryLocation('FDArray', [output.length], output);output.add(compiled.output);var fontDictTrackers = compiled.trackers;@@ -24954,11 +24799,10 @@ var CFFCompiler = (function CFFCompilerClosure() {return output.data;},encodeNumber: function CFFCompiler_encodeNumber(value) {- if (parseFloat(value) == parseInt(value, 10) && !isNaN(value)) { // isInt+ if (parseFloat(value) == parseInt(value, 10) && !isNaN(value)) // isIntreturn this.encodeInteger(value);- } else {+ elsereturn this.encodeFloat(value);- }},encodeFloat: function CFFCompiler_encodeFloat(num) {var value = num.toString();@@ -24971,8 +24815,7 @@ var CFFCompiler = (function CFFCompilerClosure() {}var nibbles = '';- var i, ii;- for (i = 0, ii = value.length; i < ii; ++i) {+ for (var i = 0, ii = value.length; i < ii; ++i) {var a = value[i];if (a === 'e') {nibbles += value[++i] === '-' ? 'c' : 'b';@@ -24986,7 +24829,7 @@ var CFFCompiler = (function CFFCompilerClosure() {}nibbles += (nibbles.length & 1) ? 'f' : 'ff';var out = [30];- for (i = 0, ii = nibbles.length; i < ii; i += 2) {+ for (var i = 0, ii = nibbles.length; i < ii; i += 2) {out.push(parseInt(nibbles.substr(i, 2), 16));}return out;@@ -25022,9 +24865,8 @@ var CFFCompiler = (function CFFCompilerClosure() {},compileNameIndex: function CFFCompiler_compileNameIndex(names) {var nameIndex = new CFFIndex();- for (var i = 0, ii = names.length; i < ii; ++i) {+ for (var i = 0, ii = names.length; i < ii; ++i)nameIndex.add(stringToArray(names[i]));- }return this.compileIndex(nameIndex);},compileTopDicts: function CFFCompiler_compileTopDicts(dicts,@@ -25092,22 +24934,16 @@ var CFFCompiler = (function CFFCompilerClosure() {var order = dict.order;for (var i = 0; i < order.length; ++i) {var key = order[i];- if (!(key in dict.values)) {+ if (!(key in dict.values))continue;- }var values = dict.values[key];var types = dict.types[key];- if (!isArray(types)) {- types = [types];- }- if (!isArray(values)) {- values = [values];- }+ if (!isArray(types)) types = [types];+ if (!isArray(values)) values = [values];// Remove any empty dict values.- if (values.length === 0) {+ if (values.length === 0)continue;- }for (var j = 0, jj = types.length; j < jj; ++j) {var type = types[j];@@ -25124,17 +24960,15 @@ var CFFCompiler = (function CFFCompilerClosure() {var name = dict.keyToNameMap[key];// Some offsets have the offset and the length, so just record the// position of the first one.- if (!offsetTracker.isTracking(name)) {+ if (!offsetTracker.isTracking(name))offsetTracker.track(name, out.length);- }out = out.concat([0x1d, 0, 0, 0, 0]);break;case 'array':case 'delta':out = out.concat(this.encodeNumber(value));- for (var k = 1, kk = values.length; k < kk; ++k) {+ for (var k = 1, kk = values.length; k < kk; ++k)out = out.concat(this.encodeNumber(values[k]));- }break;default:error('Unknown data type of ' + type);@@ -25147,9 +24981,8 @@ var CFFCompiler = (function CFFCompilerClosure() {},compileStringIndex: function CFFCompiler_compileStringIndex(strings) {var stringIndex = new CFFIndex();- for (var i = 0, ii = strings.length; i < ii; ++i) {+ for (var i = 0, ii = strings.length; i < ii; ++i)stringIndex.add(stringToArray(strings[i]));- }return this.compileIndex(stringIndex);},compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {@@ -25170,9 +25003,8 @@ var CFFCompiler = (function CFFCompilerClosure() {},compileTypedArray: function CFFCompiler_compileTypedArray(data) {var out = [];- for (var i = 0, ii = data.length; i < ii; ++i) {+ for (var i = 0, ii = data.length; i < ii; ++i)out[i] = data[i];- }return out;},compileIndex: function CFFCompiler_compileIndex(index, trackers) {@@ -25183,34 +25015,31 @@ var CFFCompiler = (function CFFCompilerClosure() {// If there is no object, just create an index. This technically// should just be [0, 0] but OTS has an issue with that.- if (count === 0) {+ if (count === 0)return [0, 0, 0];- }var data = [(count >> 8) & 0xFF, count & 0xff];- var lastOffset = 1, i;- for (i = 0; i < count; ++i) {+ var lastOffset = 1;+ for (var i = 0; i < count; ++i)lastOffset += objects[i].length;- }var offsetSize;- if (lastOffset < 0x100) {+ if (lastOffset < 0x100)offsetSize = 1;- } else if (lastOffset < 0x10000) {+ else if (lastOffset < 0x10000)offsetSize = 2;- } else if (lastOffset < 0x1000000) {+ else if (lastOffset < 0x1000000)offsetSize = 3;- } else {+ elseoffsetSize = 4;- }// Next byte contains the offset size use to reference object in the filedata.push(offsetSize);// Add another offset after this one because we need a new offsetvar relativeOffset = 1;- for (i = 0; i < count + 1; i++) {+ for (var i = 0; i < count + 1; i++) {if (offsetSize === 1) {data.push(relativeOffset & 0xFF);} else if (offsetSize === 2) {@@ -25227,20 +25056,17 @@ var CFFCompiler = (function CFFCompilerClosure() {relativeOffset & 0xFF);}- if (objects[i]) {+ if (objects[i])relativeOffset += objects[i].length;- }}var offset = data.length;- for (i = 0; i < count; i++) {+ for (var i = 0; i < count; i++) {// Notify the tracker where the object will be offset in the data.- if (trackers[i]) {+ if (trackers[i])trackers[i].offset(data.length);- }- for (var j = 0, jj = objects[i].length; j < jj; j++) {+ for (var j = 0, jj = objects[i].length; j < jj; j++)data.push(objects[i][j]);- }}return data;}@@ -25260,7 +25086,7 @@ var CFFCompiler = (function CFFCompilerClosure() {// https://github.com/mozilla/pdf.js/issues/1689(function checkChromeWindows() {if (/Windows.*Chrome/.test(navigator.userAgent)) {- SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;+ SYMBOLIC_FONT_GLYPH_OFFSET = 0xF100;}})();@@ -25276,26 +25102,25 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}function parseCmap(data, start, end) {- var offset = (getUshort(data, start + 2) === 1 ?- getLong(data, start + 8) : getLong(data, start + 16));+ var offset = getUshort(data, start + 2) === 1 ? getLong(data, start + 8) :+ getLong(data, start + 16);var format = getUshort(data, start + offset);- var length, ranges, p, i;if (format === 4) {- length = getUshort(data, start + offset + 2);+ var length = getUshort(data, start + offset + 2);var segCount = getUshort(data, start + offset + 6) >> 1;- p = start + offset + 14;- ranges = [];- for (i = 0; i < segCount; i++, p += 2) {+ var p = start + offset + 14;+ var ranges = [];+ for (var i = 0; i < segCount; i++, p += 2) {ranges[i] = {end: getUshort(data, p)};}p += 2;- for (i = 0; i < segCount; i++, p += 2) {+ for (var i = 0; i < segCount; i++, p += 2) {ranges[i].start = getUshort(data, p);}- for (i = 0; i < segCount; i++, p += 2) {+ for (var i = 0; i < segCount; i++, p += 2) {ranges[i].idDelta = getUshort(data, p);}- for (i = 0; i < segCount; i++, p += 2) {+ for (var i = 0; i < segCount; i++, p += 2) {var idOffset = getUshort(data, p);if (idOffset === 0) {continue;@@ -25308,11 +25133,11 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}return ranges;} else if (format === 12) {- length = getLong(data, start + offset + 4);+ var length = getLong(data, start + offset + 4);var groups = getLong(data, start + offset + 12);- p = start + offset + 16;- ranges = [];- for (i = 0; i < groups; i++) {+ var p = start + offset + 16;+ var ranges = [];+ for (var i = 0; i < groups; i++) {ranges.push({start: getLong(data, p),end: getLong(data, p + 4),@@ -25327,13 +25152,13 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {function parseCff(data, start, end) {var properties = {};- var parser = new CFFParser(new Stream(data, start, end - start),- properties);+ var parser = new CFFParser(+ new Stream(data, start, end - start), properties);var cff = parser.parse();return {glyphs: cff.charStrings.objects,- subrs: (cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&- cff.topDict.privateDict.subrsIndex.objects),+ subrs: cff.topDict.privateDict && cff.topDict.privateDict.subrsIndex &&+ cff.topDict.privateDict.subrsIndex.objects,gsubrs: cff.globalSubrIndex && cff.globalSubrIndex.objects};}@@ -25398,13 +25223,12 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {var yMin = ((code[i + 4] << 24) | (code[i + 5] << 16)) >> 16;var xMax = ((code[i + 6] << 24) | (code[i + 7] << 16)) >> 16;var yMax = ((code[i + 8] << 24) | (code[i + 9] << 16)) >> 16;- var flags;- var x = 0, y = 0;i += 10;if (numberOfContours < 0) {// composite glyph+ var x = 0, y = 0;do {- flags = (code[i] << 8) | code[i + 1];+ var flags = (code[i] << 8) | code[i + 1];var glyphIndex = (code[i + 2] << 8) | code[i + 3];i += 4;var arg1, arg2;@@ -25449,8 +25273,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {} else {// simple glyphvar endPtsOfContours = [];- var j, jj;- for (j = 0; j < numberOfContours; j++) {+ for (var j = 0; j < numberOfContours; j++) {endPtsOfContours.push((code[i] << 8) | code[i + 1]);i += 2;}@@ -25459,8 +25282,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {var numberOfPoints = endPtsOfContours[endPtsOfContours.length - 1] + 1;var points = [];while (points.length < numberOfPoints) {- flags = code[i++];- var repeat = 1;+ var flags = code[i++], repeat = 1;if ((flags & 0x08)) {repeat += code[i++];}@@ -25468,7 +25290,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {points.push({flags: flags});}}- for (j = 0; j < numberOfPoints; j++) {+ var x = 0, y = 0;+ for (var j = 0; j < numberOfPoints; j++) {switch (points[j].flags & 0x12) {case 0x00:x += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;@@ -25483,7 +25306,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}points[j].x = x;}- for (j = 0; j < numberOfPoints; j++) {+ for (var j = 0; j < numberOfPoints; j++) {switch (points[j].flags & 0x24) {case 0x00:y += ((code[i] << 24) | (code[i + 1] << 16)) >> 16;@@ -25500,7 +25323,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}var startPoint = 0;- for (i = 0; i < numberOfContours; i++) {+ for (var i = 0; i < numberOfContours; i++) {var endPoint = endPtsOfContours[i];// contours might have implicit points, which is located in the middle// between two neighboring off-curve points@@ -25521,7 +25344,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {contour.push(p);}moveTo(contour[0].x, contour[0].y);- for (j = 1, jj = contour.length; j < jj; j++) {+ for (var j = 1, jj = contour.length; j < jj; j++) {if ((contour[j].flags & 1)) {lineTo(contour[j].x, contour[j].y);} else if ((contour[j + 1].flags & 1)){@@ -25560,7 +25383,6 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {while (i < code.length) {var stackClean = false;var v = code[i++];- var xa, xb, ya, yb, y1, y2, y3, n, subrCode;switch (v) {case 1: // hstemstems += stack.length >> 1;@@ -25606,15 +25428,15 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {break;case 8: // rrcurvetowhile (stack.length > 0) {- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);}break;case 10: // callsubr- n = stack.pop() + font.subrsBias;- subrCode = font.subrs[n];+ var n = stack.pop() + font.subrsBias;+ var subrCode = font.subrs[n];if (subrCode) {parse(subrCode);}@@ -25625,50 +25447,49 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {v = code[i++];switch (v) {case 34: // flex- xa = x + stack.shift();- xb = xa + stack.shift(); y1 = y + stack.shift();+ var xa = x + stack.shift();+ var xb = xa + stack.shift(), y1 = y + stack.shift();x = xb + stack.shift();bezierCurveTo(xa, y, xb, y1, x, y1);- xa = x + stack.shift();- xb = xa + stack.shift();+ var xa = x + stack.shift();+ var xb = xa + stack.shift();x = xb + stack.shift();bezierCurveTo(xa, y1, xb, y, x, y);break;case 35: // flex- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);stack.pop(); // fdbreak;case 36: // hflex1- xa = x + stack.shift(); y1 = y + stack.shift();- xb = xa + stack.shift(); y2 = y1 + stack.shift();+ var xa = x + stack.shift(), y1 = y + stack.shift();+ var xb = xa + stack.shift(), y2 = y1 + stack.shift();x = xb + stack.shift();bezierCurveTo(xa, y1, xb, y2, x, y2);- xa = x + stack.shift();- xb = xa + stack.shift(); y3 = y2 + stack.shift();+ var xa = x + stack.shift();+ var xb = xa + stack.shift(), y3 = y2 + stack.shift();x = xb + stack.shift();bezierCurveTo(xa, y2, xb, y3, x, y);break;case 37: // flex1var x0 = x, y0 = y;- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb; y = yb;- if (Math.abs(x - x0) > Math.abs(y - y0)) {+ if (Math.abs(x - x0) > Math.abs(y - y0))x += stack.shift();- } else {+ elsey += stack.shift();- }bezierCurveTo(xa, ya, xb, yb, x, y);break;default:@@ -25724,8 +25545,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {break;case 24: // rcurvelinewhile (stack.length > 2) {- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);}@@ -25739,8 +25560,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {y += stack.shift();lineTo(x, y);}- xa = x + stack.shift(); ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);break;@@ -25749,8 +25570,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {x += stack.shift();}while (stack.length > 0) {- xa = x; ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x, ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb; y = yb + stack.shift();bezierCurveTo(xa, ya, xb, yb, x, y);}@@ -25760,8 +25581,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {y += stack.shift();}while (stack.length > 0) {- xa = x + stack.shift(); ya = y;- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y;+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift(); y = yb;bezierCurveTo(xa, ya, xb, yb, x, y);}@@ -25771,16 +25592,16 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {i += 2;break;case 29: // callgsubr- n = stack.pop() + font.gsubrsBias;- subrCode = font.gsubrs[n];+ var n = stack.pop() + font.gsubrsBias;+ var subrCode = font.gsubrs[n];if (subrCode) {parse(subrCode);}break;case 30: // vhcurvetowhile (stack.length > 0) {- xa = x; ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x, ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift();y = yb + (stack.length === 1 ? stack.shift() : 0);bezierCurveTo(xa, ya, xb, yb, x, y);@@ -25788,8 +25609,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {break;}- xa = x + stack.shift(); ya = y;- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y;+ var xb = xa + stack.shift(), yb = ya + stack.shift();y = yb + stack.shift();x = xb + (stack.length === 1 ? stack.shift() : 0);bezierCurveTo(xa, ya, xb, yb, x, y);@@ -25797,8 +25618,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {break;case 31: // hvcurvetowhile (stack.length > 0) {- xa = x + stack.shift(); ya = y;- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x + stack.shift(), ya = y;+ var xb = xa + stack.shift(), yb = ya + stack.shift();y = yb + stack.shift();x = xb + (stack.length === 1 ? stack.shift() : 0);bezierCurveTo(xa, ya, xb, yb, x, y);@@ -25806,24 +25627,23 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {break;}- xa = x; ya = y + stack.shift();- xb = xa + stack.shift(); yb = ya + stack.shift();+ var xa = x, ya = y + stack.shift();+ var xb = xa + stack.shift(), yb = ya + stack.shift();x = xb + stack.shift();y = yb + (stack.length === 1 ? stack.shift() : 0);bezierCurveTo(xa, ya, xb, yb, x, y);}break;default:- if (v < 32) {+ if (v < 32)error('unknown operator: ' + v);- }- if (v < 247) {+ if (v < 247)stack.push(v - 139);- } else if (v < 251) {+ else if (v < 251)stack.push((v - 247) * 256 + code[i++] + 108);- } else if (v < 255) {+ else if (v < 255)stack.push(-(v - 251) * 256 - code[i++] - 108);- } else {+ else {stack.push(((code[i] << 24) | (code[i + 1] << 16) |(code[i + 2] << 8) | code[i + 3]) / 65536);i += 4;@@ -25838,14 +25658,18 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {parse(code);}- var noop = '';+ function TrueTypeCompiled(glyphs, cmap, fontMatrix) {+ this.glyphs = glyphs;+ this.cmap = cmap;+ this.fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];- function CompiledFont(fontMatrix) {- this.compiledGlyphs = {};- this.fontMatrix = fontMatrix;+ this.compiledGlyphs = [];}- CompiledFont.prototype = {- getPathJs: function (unicode) {++ var noop = function () {};++ TrueTypeCompiled.prototype = {+ getPathGenerator: function (unicode) {var gid = lookupCmap(this.cmap, unicode);var fn = this.compiledGlyphs[gid];if (!fn) {@@ -25853,7 +25677,6 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}return fn;},-compileGlyph: function (code) {if (!code || code.length === 0 || code[0] === 14) {return noop;@@ -25864,61 +25687,59 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {js.push('c.transform(' + this.fontMatrix.join(',') + ');');js.push('c.scale(size, -size);');- this.compileGlyphImpl(code, js);+ var stack = [], x = 0, y = 0;+ compileGlyf(code, js, this);js.push('c.restore();');- return js.join('\n');- },-- compileGlyphImpl: function () {- error('Children classes should implement this.');- },-- hasBuiltPath: function (unicode) {- var gid = lookupCmap(this.cmap, unicode);- return gid in this.compiledGlyphs;+ /*jshint -W054 */+ return new Function('c', 'size', js.join('\n'));}};- function TrueTypeCompiled(glyphs, cmap, fontMatrix) {- fontMatrix = fontMatrix || [0.000488, 0, 0, 0.000488, 0, 0];- CompiledFont.call(this, fontMatrix);-- this.glyphs = glyphs;- this.cmap = cmap;-- this.compiledGlyphs = [];- }-- Util.inherit(TrueTypeCompiled, CompiledFont, {- compileGlyphImpl: function (code, js) {- compileGlyf(code, js, this);- }- });-function Type2Compiled(cffInfo, cmap, fontMatrix, glyphNameMap) {- fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];- CompiledFont.call(this, fontMatrix);this.glyphs = cffInfo.glyphs;this.gsubrs = cffInfo.gsubrs || [];this.subrs = cffInfo.subrs || [];this.cmap = cmap;this.glyphNameMap = glyphNameMap || GlyphsUnicode;+ this.fontMatrix = fontMatrix || [0.001, 0, 0, 0.001, 0, 0];this.compiledGlyphs = [];- this.gsubrsBias = (this.gsubrs.length < 1240 ?- 107 : (this.gsubrs.length < 33900 ? 1131 : 32768));- this.subrsBias = (this.subrs.length < 1240 ?- 107 : (this.subrs.length < 33900 ? 1131 : 32768));+ this.gsubrsBias = this.gsubrs.length < 1240 ? 107 :+ this.gsubrs.length < 33900 ? 1131 : 32768;+ this.subrsBias = this.subrs.length < 1240 ? 107 :+ this.subrs.length < 33900 ? 1131 : 32768;}- Util.inherit(Type2Compiled, CompiledFont, {- compileGlyphImpl: function (code, js) {+ Type2Compiled.prototype = {+ getPathGenerator: function (unicode) {+ var gid = lookupCmap(this.cmap, unicode);+ var fn = this.compiledGlyphs[gid];+ if (!fn) {+ this.compiledGlyphs[gid] = fn = this.compileGlyph(this.glyphs[gid]);+ }+ return fn;+ },+ compileGlyph: function (code) {+ if (!code || code.length === 0 || code[0] === 14) {+ return noop;+ }++ var js = [];+ js.push('c.save();');+ js.push('c.transform(' + this.fontMatrix.join(',') + ');');+ js.push('c.scale(size, -size);');++ var stack = [], x = 0, y = 0;compileCharString(code, js, this);- }- });+ js.push('c.restore();');++ /*jshint -W054 */+ return new Function('c', 'size', js.join('\n'));+ }+ };return {create: function FontRendererFactory_create(font) {@@ -25926,7 +25747,7 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {var cmap, glyf, loca, cff, indexToLocFormat, unitsPerEm;var numTables = getUshort(data, 4);for (var i = 0, p = 12; i < numTables; i++, p += 16) {- var tag = bytesToString(data.subarray(p, p + 4));+ var tag = String.fromCharCode.apply(null, data.subarray(p, p + 4));var offset = getLong(data, p + 8);var length = getLong(data, p + 12);switch (tag) {@@ -25950,8 +25771,8 @@ var FontRendererFactory = (function FontRendererFactoryClosure() {}if (glyf) {- var fontMatrix = (!unitsPerEm ? font.fontMatrix :- [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0]);+ var fontMatrix = !unitsPerEm ? font.fontMatrix :+ [1 / unitsPerEm, 0, 0, 1 / unitsPerEm, 0, 0];return new TrueTypeCompiled(parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);} else {@@ -30177,24 +29998,20 @@ var PDFImage = (function PDFImageClosure() {* Decode the image in the main thread if it supported. Resovles the promise* when the image data is ready.*/- function handleImageData(handler, xref, res, image) {+ function handleImageData(handler, xref, res, image, promise) {if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) {// For natively supported jpegs send them to the main thread for decoding.var dict = image.dict;var colorSpace = dict.get('ColorSpace', 'CS');colorSpace = ColorSpace.parse(colorSpace, xref, res);var numComps = colorSpace.numComps;- var resolvePromise;handler.send('JpegDecode', [image.getIR(), numComps], function(message) {var data = message.data;var stream = new Stream(data, 0, data.length, image.dict);- resolvePromise(stream);- });- return new Promise(function (resolve) {- resolvePromise = resolve;+ promise.resolve(stream);});} else {- return Promise.resolve(image);+ promise.resolve(image);}}/**@@ -30204,48 +30021,38 @@ var PDFImage = (function PDFImageClosure() {function decodeAndClamp(value, addend, coefficient, max) {value = addend + value * coefficient;// Clamp the value to the range- return (value < 0 ? 0 : (value > max ? max : value));+ return value < 0 ? 0 : value > max ? max : value;}function PDFImage(xref, res, image, inline, smask, mask, isMask) {this.image = image;- var dict = image.dict;- if (dict.has('Filter')) {- var filter = dict.get('Filter').name;- if (filter === 'JPXDecode') {- info('get image params from JPX stream');- var jpxImage = new JpxImage();- jpxImage.parseImageProperties(image.stream);- image.stream.reset();- image.bitsPerComponent = jpxImage.bitsPerComponent;- image.numComps = jpxImage.componentsCount;- } else if (filter === 'JBIG2Decode') {- image.bitsPerComponent = 1;- image.numComps = 1;- }+ if (image.getParams) {+ // JPX/JPEG2000 streams directly contain bits per component+ // and color space mode information.+ TODO('get params from actual stream');+ // var bits = ...+ // var colorspace = ...}// TODO cache rendered images?+ var dict = image.dict;this.width = dict.get('Width', 'W');this.height = dict.get('Height', 'H');- if (this.width < 1 || this.height < 1) {+ if (this.width < 1 || this.height < 1)error('Invalid image width: ' + this.width + ' or height: ' +this.height);- }this.interpolate = dict.get('Interpolate', 'I') || false;this.imageMask = dict.get('ImageMask', 'IM') || false;- this.matte = dict.get('Matte') || false;var bitsPerComponent = image.bitsPerComponent;if (!bitsPerComponent) {bitsPerComponent = dict.get('BitsPerComponent', 'BPC');if (!bitsPerComponent) {- if (this.imageMask) {+ if (this.imageMask)bitsPerComponent = 1;- } else {+ elseerror('Bits per component missing in image: ' + this.imageMask);- }}}this.bpc = bitsPerComponent;@@ -30253,19 +30060,8 @@ var PDFImage = (function PDFImageClosure() {if (!this.imageMask) {var colorSpace = dict.get('ColorSpace', 'CS');if (!colorSpace) {- info('JPX images (which do not require color spaces)');- switch (image.numComps) {- case 1:- colorSpace = Name.get('DeviceGray');- break;- case 3:- colorSpace = Name.get('DeviceRGB');- break;- default:- // TODO: Find out how four color channels are handled. CMYK? Alpha?- error('JPX images with ' + this.numComps +- ' color components not supported.');- }+ TODO('JPX images (which don"t require color spaces');+ colorSpace = new Name('DeviceRGB');}this.colorSpace = ColorSpace.parse(colorSpace, xref, res);this.numComps = this.colorSpace.numComps;@@ -30301,47 +30097,51 @@ var PDFImage = (function PDFImageClosure() {}}/**- * Handles processing of image data and returns the Promise that is resolved- * with a PDFImage when the image is ready to be used.+ * Handles processing of image data and calls the callback with an argument+ * of a PDFImage when the image is ready to be used.*/- PDFImage.buildImage = function PDFImage_buildImage(handler, xref,+ PDFImage.buildImage = function PDFImage_buildImage(callback, handler, xref,res, image, inline) {- var imagePromise = handleImageData(handler, xref, res, image);- var smaskPromise;- var maskPromise;+ var imageDataPromise = new Promise();+ var smaskPromise = new Promise();+ var maskPromise = new Promise();+ // The image data and smask data may not be ready yet, wait till both are+ // resolved.+ Promise.all([imageDataPromise, smaskPromise, maskPromise]).then(+ function(results) {+ var imageData = results[0], smaskData = results[1], maskData = results[2];+ var image = new PDFImage(xref, res, imageData, inline, smaskData,+ maskData);+ callback(image);+ });++ handleImageData(handler, xref, res, image, imageDataPromise);var smask = image.dict.get('SMask');var mask = image.dict.get('Mask');if (smask) {- smaskPromise = handleImageData(handler, xref, res, smask);- maskPromise = Promise.resolve(null);+ handleImageData(handler, xref, res, smask, smaskPromise);+ maskPromise.resolve(null);} else {- smaskPromise = Promise.resolve(null);+ smaskPromise.resolve(null);if (mask) {if (isStream(mask)) {- maskPromise = handleImageData(handler, xref, res, mask);+ handleImageData(handler, xref, res, mask, maskPromise);} else if (isArray(mask)) {- maskPromise = Promise.resolve(mask);+ maskPromise.resolve(mask);} else {warn('Unsupported mask format.');- maskPromise = Promise.resolve(null);+ maskPromise.resolve(null);}} else {- maskPromise = Promise.resolve(null);+ maskPromise.resolve(null);}}- return Promise.all([imagePromise, smaskPromise, maskPromise]).then(- function(results) {- var imageData = results[0];- var smaskData = results[1];- var maskData = results[2];- return new PDFImage(xref, res, imageData, inline, smaskData, maskData);- });};/**- * Resize an image using the nearest neighbor algorithm. Currently only+ * Resize an image using the nearest neighbor algorithm. Currently only* supports one and three component images.* @param {TypedArray} pixels The original image with one component.* @param {Number} bpc Number of bits per component.@@ -30355,8 +30155,8 @@ var PDFImage = (function PDFImageClosure() {PDFImage.resize = function PDFImage_resize(pixels, bpc, components,w1, h1, w2, h2) {var length = w2 * h2 * components;- var temp = (bpc <= 8 ? new Uint8Array(length) :- (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));+ var temp = bpc <= 8 ? new Uint8Array(length) :+ bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);var xRatio = w1 / w2;var yRatio = h1 / h2;var px, py, newIndex, oldIndex;@@ -30380,64 +30180,63 @@ var PDFImage = (function PDFImageClosure() {return temp;};- PDFImage.createMask =- function PDFImage_createMask(imgArray, width, height, canTransfer,- inverseDecode) {- // If imgArray came from a DecodeStream, we're safe to transfer it.- // Otherwise, copy it.- var actualLength = imgArray.byteLength;- var data;- if (canTransfer) {- data = imgArray;- } else {- data = new Uint8Array(actualLength);- data.set(imgArray);- }- // Invert if necessary. It's safe to modify the array -- whether it's the- // original or a copy, we're about to transfer it anyway, so nothing else- // in this thread can be relying on its contents.- if (inverseDecode) {- for (var i = 0; i < actualLength; i++) {- data[i] = ~data[i];+ PDFImage.createMask = function PDFImage_createMask(imgArray, width, height,+ inverseDecode) {+ var buffer = new Uint8Array(width * height * 4);+ var imgArrayPos = 0;+ var i, j, mask, buf;+ // removing making non-masked pixels transparent+ var bufferPos = 3; // alpha component offset+ for (i = 0; i < height; i++) {+ mask = 0;+ for (j = 0; j < width; j++) {+ if (!mask) {+ buf = imgArray[imgArrayPos++];+ mask = 128;+ }+ if (!(buf & mask) !== inverseDecode) {+ buffer[bufferPos] = 255;+ }+ bufferPos += 4;+ mask >>= 1;}}-- return {data: data, width: width, height: height};+ return {data: buffer, width: width, height: height};};PDFImage.prototype = {get drawWidth() {- return Math.max(this.width,- this.smask && this.smask.width || 0,- this.mask && this.mask.width || 0);+ if (!this.smask)+ return this.width;+ return Math.max(this.width, this.smask.width);},get drawHeight() {- return Math.max(this.height,- this.smask && this.smask.height || 0,- this.mask && this.mask.height || 0);+ if (!this.smask)+ return this.height;+ return Math.max(this.height, this.smask.height);},decodeBuffer: function PDFImage_decodeBuffer(buffer) {var bpc = this.bpc;var decodeMap = this.decode;var numComps = this.numComps;+ var decodeAddends, decodeCoefficients;var decodeAddends = this.decodeAddends;var decodeCoefficients = this.decodeCoefficients;var max = (1 << bpc) - 1;- var i, ii;if (bpc === 1) {// If the buffer needed decode that means it just needs to be inverted.- for (i = 0, ii = buffer.length; i < ii; i++) {+ for (var i = 0, ii = buffer.length; i < ii; i++) {buffer[i] = +!(buffer[i]);}return;}var index = 0;- for (i = 0, ii = this.width * this.height; i < ii; i++) {+ for (var i = 0, ii = this.width * this.height; i < ii; i++) {for (var j = 0; j < numComps; j++) {buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j],- decodeCoefficients[j], max);+ decodeCoefficients[j], max);index++;}}@@ -30446,59 +30245,46 @@ var PDFImage = (function PDFImageClosure() {var bpc = this.bpc;// This image doesn't require any extra work.- if (bpc === 8) {+ if (bpc === 8)return buffer;- }+ var bufferLength = buffer.length;var width = this.width;var height = this.height;var numComps = this.numComps;var length = width * height * numComps;var bufferPos = 0;- var output = (bpc <= 8 ? new Uint8Array(length) :- (bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length)));+ var output = bpc <= 8 ? new Uint8Array(length) :+ bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);var rowComps = width * numComps;var max = (1 << bpc) - 1;- var i = 0, ii, buf;if (bpc === 1) {// Optimization for reading 1 bpc images.- var mask, loop1End, loop2End;- for (var j = 0; j < height; j++) {- loop1End = i + (rowComps & ~7);- loop2End = i + rowComps;+ var mask = 0;+ var buf = 0;- // unroll loop for all full bytes- while (i < loop1End) {- buf = buffer[bufferPos++];- output[i] = (buf >> 7) & 1;- output[i + 1] = (buf >> 6) & 1;- output[i + 2] = (buf >> 5) & 1;- output[i + 3] = (buf >> 4) & 1;- output[i + 4] = (buf >> 3) & 1;- output[i + 5] = (buf >> 2) & 1;- output[i + 6] = (buf >> 1) & 1;- output[i + 7] = buf & 1;- i += 8;+ for (var i = 0, ii = length; i < ii; ++i) {+ if (i % rowComps === 0) {+ mask = 0;+ buf = 0;+ } else {+ mask >>= 1;}- // handle remaing bits- if (i < loop2End) {+ if (mask <= 0) {buf = buffer[bufferPos++];mask = 128;- while (i < loop2End) {- output[i++] = +!!(buf & mask);- mask >>= 1;- }}++ output[i] = +!!(buf & mask);}} else {// The general case that handles all other bpc values.- var bits = 0;- buf = 0;- for (i = 0, ii = length; i < ii; ++i) {+ var bits = 0, buf = 0;+ for (var i = 0, ii = length; i < ii; ++i) {if (i % rowComps === 0) {buf = 0;bits = 0;@@ -30511,54 +30297,50 @@ var PDFImage = (function PDFImageClosure() {var remainingBits = bits - bpc;var value = buf >> remainingBits;- output[i] = (value < 0 ? 0 : (value > max ? max : value));+ output[i] = value < 0 ? 0 : value > max ? max : value;buf = buf & ((1 << remainingBits) - 1);bits = remainingBits;}}return output;},- fillOpacity: function PDFImage_fillOpacity(rgbaBuf, width, height,- actualHeight, image) {+ getOpacity: function PDFImage_getOpacity(width, height, image) {var smask = this.smask;var mask = this.mask;- var alphaBuf, sw, sh, i, ii, j;+ var originalWidth = this.width;+ var originalHeight = this.height;+ var buf;if (smask) {- sw = smask.width;- sh = smask.height;- alphaBuf = new Uint8Array(sw * sh);- smask.fillGrayBuffer(alphaBuf);- if (sw != width || sh != height) {- alphaBuf = PDFImage.resize(alphaBuf, smask.bpc, 1, sw, sh, width,- height);- }+ var sw = smask.width;+ var sh = smask.height;+ buf = new Uint8Array(sw * sh);+ smask.fillGrayBuffer(buf);+ if (sw != width || sh != height)+ buf = PDFImage.resize(buf, smask.bpc, 1, sw, sh, width, height);} else if (mask) {if (mask instanceof PDFImage) {- sw = mask.width;- sh = mask.height;- alphaBuf = new Uint8Array(sw * sh);+ var sw = mask.width;+ var sh = mask.height;+ buf = new Uint8Array(sw * sh);mask.numComps = 1;- mask.fillGrayBuffer(alphaBuf);+ mask.fillGrayBuffer(buf);- // Need to invert values in rgbaBuf- for (i = 0, ii = sw * sh; i < ii; ++i) {- alphaBuf[i] = 255 - alphaBuf[i];- }+ // Need to invert values in buffer+ for (var i = 0, ii = sw * sh; i < ii; ++i)+ buf[i] = 255 - buf[i];- if (sw != width || sh != height) {- alphaBuf = PDFImage.resize(alphaBuf, mask.bpc, 1, sw, sh, width,- height);- }+ if (sw != width || sh != height)+ buf = PDFImage.resize(buf, mask.bpc, 1, sw, sh, width, height);} else if (isArray(mask)) {// Color key mask: if any of the compontents are outside the range// then they should be painted.- alphaBuf = new Uint8Array(width * height);+ buf = new Uint8Array(width * height);var numComps = this.numComps;- for (i = 0, ii = width * height; i < ii; ++i) {+ for (var i = 0, ii = width * height; i < ii; ++i) {var opacity = 0;var imageOffset = i * numComps;- for (j = 0; j < numComps; ++j) {+ for (var j = 0; j < numComps; ++j) {var color = image[imageOffset + j];var maskOffset = j * 2;if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {@@ -30566,183 +30348,89 @@ var PDFImage = (function PDFImageClosure() {break;}}- alphaBuf[i] = opacity;+ buf[i] = opacity;}} else {error('Unknown mask format.');}- }-- if (alphaBuf) {- for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {- rgbaBuf[j] = alphaBuf[i];- }} else {- // No mask.- for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {- rgbaBuf[j] = 255;- }- }- },- undoPreblend: function PDFImage_undoPreblend(buffer, width, height) {- var matte = this.smask && this.smask.matte;- if (!matte) {- return;- }-- function clamp(value) {- return (value < 0 ? 0 : (value > 255 ? 255 : value)) | 0;- }-- var matteRgb = this.colorSpace.getRgb(matte, 0);- var length = width * height * 4;- for (var i = 0; i < length; i += 4) {- var alpha = buffer[i + 3];- if (alpha === 0) {- // according formula we have to get Infinity in all components- // making it as white (tipical paper color) should be okay- buffer[i] = 255;- buffer[i + 1] = 255;- buffer[i + 2] = 255;- continue;- }- var k = 255 / alpha;- buffer[i] = clamp((buffer[i] - matteRgb[0]) * k + matteRgb[0]);- buffer[i + 1] = clamp((buffer[i + 1] - matteRgb[1]) * k + matteRgb[1]);- buffer[i + 2] = clamp((buffer[i + 2] - matteRgb[2]) * k + matteRgb[2]);+ buf = new Uint8Array(width * height);+ for (var i = 0, ii = width * height; i < ii; ++i)+ buf[i] = 255;}+ return buf;},- createImageData: function PDFImage_createImageData(forceRGBA) {- var drawWidth = this.drawWidth;- var drawHeight = this.drawHeight;- var imgData = { // other fields are filled in below- width: drawWidth,- height: drawHeight- };-+ fillRgbaBuffer: function PDFImage_fillRgbaBuffer(buffer, width, height) {var numComps = this.numComps;var originalWidth = this.width;var originalHeight = this.height;var bpc = this.bpc;- // Rows start at byte boundary.+ // rows start at byte boundary;var rowBytes = (originalWidth * numComps * bpc + 7) >> 3;var imgArray = this.getImageBytes(originalHeight * rowBytes);- if (!forceRGBA) {- // If it is a 1-bit-per-pixel grayscale (i.e. black-and-white) image- // without any complications, we pass a same-sized copy to the main- // thread rather than expanding by 32x to RGBA form. This saves *lots*- // of memory for many scanned documents. It's also much faster.- //- // Similarly, if it is a 24-bit-per pixel RGB image without any- // complications, we avoid expanding by 1.333x to RGBA form.- var kind;- if (this.colorSpace.name === 'DeviceGray' && bpc === 1) {- kind = ImageKind.GRAYSCALE_1BPP;- } else if (this.colorSpace.name === 'DeviceRGB' && bpc === 8) {- kind = ImageKind.RGB_24BPP;- }- if (kind && !this.smask && !this.mask && !this.needsDecode &&- drawWidth === originalWidth && drawHeight === originalHeight) {- imgData.kind = kind;-- // If imgArray came from a DecodeStream, we're safe to transfer it- // (and thus neuter it) because it will constitute the entire- // DecodeStream's data. But if it came from a Stream, we need to- // copy it because it'll only be a portion of the Stream's data, and- // the rest will be read later on.- if (this.image instanceof DecodeStream) {- imgData.data = imgArray;- } else {- var newArray = new Uint8Array(imgArray.length);- newArray.set(imgArray);- imgData.data = newArray;- }- return imgData;- }- }-- // imgArray can be incomplete (e.g. after CCITT fax encoding).+ // imgArray can be incomplete (e.g. after CCITT fax encoding)var actualHeight = 0 | (imgArray.length / rowBytes *- drawHeight / originalHeight);-+ height / originalHeight);var comps = this.getComponents(imgArray);-- // If opacity data is present, use RGBA_32BPP form. Otherwise, use the- // more compact RGB_24BPP form if allowable.- var alpha01, maybeUndoPreblend;- if (!forceRGBA && !this.smask && !this.mask) {- imgData.kind = ImageKind.RGB_24BPP;- imgData.data = new Uint8Array(drawWidth * drawHeight * 3);- alpha01 = 0;- maybeUndoPreblend = false;- } else {- imgData.kind = ImageKind.RGBA_32BPP;- imgData.data = new Uint8Array(drawWidth * drawHeight * 4);- alpha01 = 1;- maybeUndoPreblend = true;-- // Color key masking (opacity) must be performed before decoding.- this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight,- comps);- }+ // Build opacity here since color key masking needs to be perormed on+ // undecoded values.+ var opacity = this.getOpacity(width, height, comps);if (this.needsDecode) {this.decodeBuffer(comps);}- this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight,- drawWidth, drawHeight, actualHeight, bpc, comps,- alpha01);- if (maybeUndoPreblend) {- this.undoPreblend(imgData.data, drawWidth, actualHeight);- }+ var rgbBuf = this.colorSpace.createRgbBuffer(comps, 0,+ originalWidth * originalHeight, bpc);+ if (originalWidth != width || originalHeight != height)+ rgbBuf = PDFImage.resize(rgbBuf, this.bpc, 3, originalWidth,+ originalHeight, width, height);+ var compsPos = 0;+ var opacityPos = 0;+ var length = width * actualHeight * 4;- return imgData;+ for (var i = 0; i < length; i += 4) {+ buffer[i] = rgbBuf[compsPos++];+ buffer[i + 1] = rgbBuf[compsPos++];+ buffer[i + 2] = rgbBuf[compsPos++];+ buffer[i + 3] = opacity[opacityPos++];+ }},fillGrayBuffer: function PDFImage_fillGrayBuffer(buffer) {var numComps = this.numComps;- if (numComps != 1) {+ if (numComps != 1)error('Reading gray scale from a color image: ' + numComps);- }var width = this.width;var height = this.height;var bpc = this.bpc;- // rows start at byte boundary+ // rows start at byte boundary;var rowBytes = (width * numComps * bpc + 7) >> 3;var imgArray = this.getImageBytes(height * rowBytes);var comps = this.getComponents(imgArray);- var i, length;-- if (bpc === 1) {- // inline decoding (= inversion) for 1 bpc images- length = width * height;- if (this.needsDecode) {- // invert and scale to {0, 255}- for (i = 0; i < length; ++i) {- buffer[i] = (comps[i] - 1) & 255;- }- } else {- // scale to {0, 255}- for (i = 0; i < length; ++i) {- buffer[i] = (-comps[i]) & 255;- }- }- return;- }-if (this.needsDecode) {this.decodeBuffer(comps);}- length = width * height;+ var length = width * height;// we aren't using a colorspace so we need to scale the valuevar scale = 255 / ((1 << bpc) - 1);- for (i = 0; i < length; ++i) {+ for (var i = 0; i < length; ++i)buffer[i] = (scale * comps[i]) | 0;- }+ },+ getImageData: function PDFImage_getImageData() {+ var drawWidth = this.drawWidth;+ var drawHeight = this.drawHeight;+ var imgData = {+ width: drawWidth,+ height: drawHeight,+ data: new Uint8Array(drawWidth * drawHeight * 4)+ };+ var pixels = imgData.data;+ this.fillRgbaBuffer(pixels, drawWidth, drawHeight);+ return imgData;},getImageBytes: function PDFImage_getImageBytes(length) {this.image.reset();@@ -30752,6 +30440,15 @@ var PDFImage = (function PDFImageClosure() {return PDFImage;})();+function loadJpegStream(id, imageData, objs) {+ var img = new Image();+ img.onload = (function loadJpegStream_onloadClosure() {+ objs.resolve(id, img);+ });+ img.src = 'data:image/jpeg;base64,' + window.btoa(imageData);+}++// The Metrics object contains glyph widths (in glyph space units).// As per PDF spec, for most fonts (Type 3 being an exception) a glyph@@ -33700,7 +33397,7 @@ var Metrics = {var EOF = {};function isEOF(v) {- return (v == EOF);+ return v == EOF;}var Parser = (function ParserClosure() {@@ -33708,15 +33405,25 @@ var Parser = (function ParserClosure() {this.lexer = lexer;this.allowStreams = allowStreams;this.xref = xref;- this.imageCache = {- length: 0,- adler32: 0,- stream: null- };this.refill();}- Parser.prototype = {+ Parser.prototype = {+ saveState: function Parser_saveState() {+ this.state = {+ buf1: this.buf1,+ buf2: this.buf2,+ streamPos: this.lexer.stream.pos+ };+ },++ restoreState: function Parser_restoreState() {+ var state = this.state;+ this.buf1 = state.buf1;+ this.buf2 = state.buf2;+ this.lexer.stream.pos = state.streamPos;+ },+refill: function Parser_refill() {this.buf1 = this.lexer.getObj();this.buf2 = this.lexer.getObj();@@ -33725,6 +33432,8 @@ var Parser = (function ParserClosure() {if (isCmd(this.buf2, 'ID')) {this.buf1 = this.buf2;this.buf2 = null;+ // skip byte after ID+ this.lexer.skip();} else {this.buf1 = this.buf2;this.buf2 = this.lexer.getObj();@@ -33738,12 +33447,10 @@ var Parser = (function ParserClosure() {if (isCmd(this.buf1, '[')) { // arraythis.shift();var array = [];- while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {+ while (!isCmd(this.buf1, ']') && !isEOF(this.buf1))array.push(this.getObj(cipherTransform));- }- if (isEOF(this.buf1)) {+ if (isEOF(this.buf1))error('End of file inside array');- }this.shift();return array;}@@ -33752,27 +33459,25 @@ var Parser = (function ParserClosure() {var dict = new Dict(this.xref);while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {if (!isName(this.buf1)) {- info('Malformed dictionary: key must be a name object');+ info('Malformed dictionary, key must be a name object');this.shift();continue;}var key = this.buf1.name;this.shift();- if (isEOF(this.buf1)) {+ if (isEOF(this.buf1))break;- }dict.set(key, this.getObj(cipherTransform));}- if (isEOF(this.buf1)) {+ if (isEOF(this.buf1))error('End of file inside dictionary');- }- // Stream objects are not allowed inside content streams or- // object streams.+ // stream objects are not allowed inside content streams or+ // object streamsif (isCmd(this.buf2, 'stream')) {- return (this.allowStreams ?- this.makeStream(dict, cipherTransform) : dict);+ return this.allowStreams ?+ this.makeStream(dict, cipherTransform) : dict;}this.shift();return dict;@@ -33791,9 +33496,8 @@ var Parser = (function ParserClosure() {if (isString(this.buf1)) { // stringvar str = this.buf1;this.shift();- if (cipherTransform) {+ if (cipherTransform)str = cipherTransform.decryptString(str);- }return str;}@@ -33807,17 +33511,15 @@ var Parser = (function ParserClosure() {var stream = lexer.stream;// parse dictionary- var dict = new Dict(null);+ var dict = new Dict();while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {- if (!isName(this.buf1)) {+ if (!isName(this.buf1))error('Dictionary key must be a name object');- }var key = this.buf1.name;this.shift();- if (isEOF(this.buf1)) {+ if (isEOF(this.buf1))break;- }dict.set(key, this.getObj(cipherTransform));}@@ -33826,8 +33528,9 @@ var Parser = (function ParserClosure() {// searching for the /EI\s/var state = 0, ch, i, ii;- while (state != 4 && (ch = stream.getByte()) !== -1) {- switch (ch | 0) {+ while (state != 4 &&+ (ch = stream.getByte()) !== null && ch !== undefined) {+ switch (ch) {case 0x20:case 0x0D:case 0x0A:@@ -33835,19 +33538,18 @@ var Parser = (function ParserClosure() {var followingBytes = stream.peekBytes(5);for (i = 0, ii = followingBytes.length; i < ii; i++) {ch = followingBytes[i];- if (ch !== 0x0A && ch !== 0x0D && (ch < 0x20 || ch > 0x7F)) {- // not a LF, CR, SPACE or any visible ASCII character+ if (ch !== 0x0A && ch != 0x0D && (ch < 0x20 || ch > 0x7F)) {state = 0;break; // some binary stuff found, resetting the state}}- state = (state === 3 ? 4 : 0);+ state = state === 3 ? 4 : 0;break;case 0x45:state = 2;break;case 0x49:- state = (state === 2 ? 3 : 0);+ state = state === 2 ? 3 : 0;break;default:state = 0;@@ -33857,48 +33559,10 @@ var Parser = (function ParserClosure() {var length = (stream.pos - 4) - startPos;var imageStream = stream.makeSubStream(startPos, length, dict);-- // trying to cache repeat images, first we are trying to "warm up" caching- // using length, then comparing adler32- var MAX_LENGTH_TO_CACHE = 1000;- var cacheImage = false, adler32;- if (length < MAX_LENGTH_TO_CACHE && this.imageCache.length === length) {- var imageBytes = imageStream.getBytes();- imageStream.reset();-- var a = 1;- var b = 0;- for (i = 0, ii = imageBytes.length; i < ii; ++i) {- a = (a + (imageBytes[i] & 0xff)) % 65521;- b = (b + a) % 65521;- }- adler32 = (b << 16) | a;-- if (this.imageCache.stream && this.imageCache.adler32 === adler32) {- this.buf2 = Cmd.get('EI');- this.shift();-- this.imageCache.stream.reset();- return this.imageCache.stream;- }- cacheImage = true;- }- if (!cacheImage && !this.imageCache.stream) {- this.imageCache.length = length;- this.imageCache.stream = null;- }-- if (cipherTransform) {- imageStream = cipherTransform.createStream(imageStream, length);- }-+ if (cipherTransform)+ imageStream = cipherTransform.createStream(imageStream);imageStream = this.filter(imageStream, dict, length);imageStream.dict = dict;- if (cacheImage) {- imageStream.cacheKey = 'inline_' + length + '_' + adler32;- this.imageCache.adler32 = adler32;- this.imageCache.stream = imageStream;- }this.buf2 = Cmd.get('EI');this.shift();@@ -33907,7 +33571,7 @@ var Parser = (function ParserClosure() {},fetchIfRef: function Parser_fetchIfRef(obj) {// not relying on the xref.fetchIfRef -- xref might not be set- return (isRef(obj) ? this.xref.fetch(obj) : obj);+ return isRef(obj) ? this.xref.fetch(obj) : obj;},makeStream: function Parser_makeStream(dict, cipherTransform) {var lexer = this.lexer;@@ -33915,19 +33579,15 @@ var Parser = (function ParserClosure() {// get stream start positionlexer.skipToNextLine();- var pos = stream.pos - 1;+ var pos = stream.pos;// get lengthvar length = this.fetchIfRef(dict.get('Length'));- if (!isInt(length)) {- info('Bad ' + length + ' attribute in stream');- length = 0;- }+ if (!isInt(length))+ error('Bad ' + length + ' attribute in stream');// skip over the stream datastream.pos = pos + length;- lexer.nextChar();-this.shift(); // '>>'this.shift(); // 'stream'if (!isCmd(this.buf1, 'endstream')) {@@ -33937,11 +33597,11 @@ var Parser = (function ParserClosure() {var ENDSTREAM_SIGNATURE_LENGTH = 9;var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,0x61, 0x6D];- var skipped = 0, found = false, i, j;+ var skipped = 0, found = false;while (stream.pos < stream.end) {var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;- found = false;+ var found = false, i, ii, j;for (i = 0, j = 0; i < scanLength; i++) {var b = scanBytes[i];if (b !== ENDSTREAM_SIGNATURE[j]) {@@ -33950,7 +33610,6 @@ var Parser = (function ParserClosure() {} else {j++;if (j >= ENDSTREAM_SIGNATURE_LENGTH) {- i++;found = true;break;}@@ -33968,17 +33627,14 @@ var Parser = (function ParserClosure() {error('Missing endstream');}length = skipped;-- lexer.nextChar();this.shift();this.shift();}this.shift(); // 'endstream'stream = stream.makeSubStream(pos, length, dict);- if (cipherTransform) {- stream = cipherTransform.createStream(stream, length);- }+ if (cipherTransform)+ stream = cipherTransform.createStream(stream);stream = this.filter(stream, dict, length);stream.dict = dict;return stream;@@ -33986,74 +33642,69 @@ var Parser = (function ParserClosure() {filter: function Parser_filter(stream, dict, length) {var filter = this.fetchIfRef(dict.get('Filter', 'F'));var params = this.fetchIfRef(dict.get('DecodeParms', 'DP'));- if (isName(filter)) {+ if (isName(filter))return this.makeFilter(stream, filter.name, length, params);- }-- var maybeLength = length;if (isArray(filter)) {var filterArray = filter;var paramsArray = params;for (var i = 0, ii = filterArray.length; i < ii; ++i) {filter = filterArray[i];- if (!isName(filter)) {+ if (!isName(filter))error('Bad filter name: ' + filter);- }params = null;- if (isArray(paramsArray) && (i in paramsArray)) {+ if (isArray(paramsArray) && (i in paramsArray))params = paramsArray[i];- }- stream = this.makeFilter(stream, filter.name, maybeLength, params);+ stream = this.makeFilter(stream, filter.name, length, params);// after the first stream the length variable is invalid- maybeLength = null;+ length = null;}}return stream;},- makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {+ makeFilter: function Parser_makeFilter(stream, name, length, params) {if (stream.dict.get('Length') === 0) {return new NullStream(stream);}if (name == 'FlateDecode' || name == 'Fl') {if (params) {- return new PredictorStream(new FlateStream(stream, maybeLength),- maybeLength, params);+ return new PredictorStream(new FlateStream(stream), params);}- return new FlateStream(stream, maybeLength);+ return new FlateStream(stream);}if (name == 'LZWDecode' || name == 'LZW') {var earlyChange = 1;if (params) {- if (params.has('EarlyChange')) {+ if (params.has('EarlyChange'))earlyChange = params.get('EarlyChange');- }return new PredictorStream(- new LZWStream(stream, maybeLength, earlyChange),- maybeLength, params);+ new LZWStream(stream, earlyChange), params);}- return new LZWStream(stream, maybeLength, earlyChange);+ return new LZWStream(stream, earlyChange);}if (name == 'DCTDecode' || name == 'DCT') {- return new JpegStream(stream, maybeLength, stream.dict, this.xref);+ var bytes = stream.getBytes(length);+ return new JpegStream(bytes, stream.dict, this.xref);}if (name == 'JPXDecode' || name == 'JPX') {- return new JpxStream(stream, maybeLength, stream.dict);+ var bytes = stream.getBytes(length);+ return new JpxStream(bytes, stream.dict);}if (name == 'ASCII85Decode' || name == 'A85') {- return new Ascii85Stream(stream, maybeLength);+ return new Ascii85Stream(stream);}if (name == 'ASCIIHexDecode' || name == 'AHx') {- return new AsciiHexStream(stream, maybeLength);+ return new AsciiHexStream(stream);}if (name == 'CCITTFaxDecode' || name == 'CCF') {- return new CCITTFaxStream(stream, maybeLength, params);+ return new CCITTFaxStream(stream, params);}if (name == 'RunLengthDecode' || name == 'RL') {- return new RunLengthStream(stream, maybeLength);+ return new RunLengthStream(stream);}if (name == 'JBIG2Decode') {- return new Jbig2Stream(stream, maybeLength, stream.dict);+ var bytes = stream.getBytes(length);+ return new Jbig2Stream(bytes, stream.dict);}warn('filter "' + name + '" not supported yet');return stream;@@ -34066,15 +33717,6 @@ var Parser = (function ParserClosure() {var Lexer = (function LexerClosure() {function Lexer(stream, knownCommands) {this.stream = stream;- this.nextChar();-- // While lexing, we build up many strings one char at a time. Using += for- // this can result in lots of garbage strings. It's better to build an- // array of single-char strings and then join() them together at the end.- // And reusing a single array (i.e. |this.strBuf|) over and over for this- // purpose uses less memory than using a new array for each string.- this.strBuf = [];-// The PDFs might have "glued" commands with other commands, operands or// literals, e.g. "q1". The knownCommands is a dictionary of the valid// commands and their prefixes. The prefixes are built the following way:@@ -34086,392 +33728,312 @@ var Lexer = (function LexerClosure() {}Lexer.isSpace = function Lexer_isSpace(ch) {- // Space is one of the following characters: SPACE, TAB, CR or LF.- return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);+ return ch == ' ' || ch == '\t' || ch == '\x0d' || ch == '\x0a';};- // A '1' in this array means the character is white space. A '1' or+ // A '1' in this array means the character is white space. A '1' or// '2' means the character ends a name or command.var specialChars = [- 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x- 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x+ 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // fx];function toHexDigit(ch) {- if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'- return ch & 0x0F;- }- if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {- // 'A'-'F', 'a'-'f'- return (ch & 0x0F) + 9;- }+ if (ch >= '0' && ch <= '9')+ return ch.charCodeAt(0) - 48;+ ch = ch.toUpperCase();+ if (ch >= 'A' && ch <= 'F')+ return ch.charCodeAt(0) - 55;return -1;}Lexer.prototype = {- nextChar: function Lexer_nextChar() {- return (this.currentChar = this.stream.getByte());- },- peekChar: function Lexer_peekChar() {- return this.stream.peekBytes(1)[0];- },- getNumber: function Lexer_getNumber() {- var ch = this.currentChar;- var eNotation = false;- var divideBy = 0; // different from 0 if it's a floating point value- var sign = 1;-- if (ch === 0x2D) { // '-'- sign = -1;- ch = this.nextChar();- } else if (ch === 0x2B) { // '+'- ch = this.nextChar();- }- if (ch === 0x2E) { // '.'- divideBy = 10;- ch = this.nextChar();- }- if (ch < 0x30 || ch > 0x39) { // '0' - '9'- error('Invalid number: ' + String.fromCharCode(ch));- return 0;- }-- var baseValue = ch - 0x30; // '0'- var powerValue = 0;- var powerValueSign = 1;-- while ((ch = this.nextChar()) >= 0) {- if (0x30 <= ch && ch <= 0x39) { // '0' - '9'- var currentDigit = ch - 0x30; // '0'- if (eNotation) { // We are after an 'e' or 'E'- powerValue = powerValue * 10 + currentDigit;- } else {- if (divideBy !== 0) { // We are after a point- divideBy *= 10;- }- baseValue = baseValue * 10 + currentDigit;- }- } else if (ch === 0x2E) { // '.'- if (divideBy === 0) {- divideBy = 1;- } else {- // A number can have only one '.'- break;- }- } else if (ch === 0x2D) { // '-'+ getNumber: function Lexer_getNumber(ch) {+ var floating = false;+ var str = ch;+ var stream = this.stream;+ while ((ch = stream.lookChar())) {+ if (ch == '.' && !floating) {+ str += ch;+ floating = true;+ } else if (ch == '-') {// ignore minus signs in the middle of numbers to match// Adobe's behaviorwarn('Badly formated number');- } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'- // 'E' can be either a scientific notation or the beginning of a new- // operator- var hasE = true;- ch = this.peekChar();- if (ch === 0x2B || ch === 0x2D) { // '+', '-'- powerValueSign = (ch === 0x2D) ? -1 : 1;- this.nextChar(); // Consume the sign character- } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'- // The 'E' must be the beginning of a new operator- break;- }- eNotation = true;+ } else if (ch >= '0' && ch <= '9') {+ str += ch;+ } else if (ch == 'e' || ch == 'E') {+ floating = true;} else {// the last character doesn't belong to usbreak;}+ stream.skip();}-- if (divideBy !== 0) {- baseValue /= divideBy;- }- if (eNotation) {- baseValue *= Math.pow(10, powerValueSign * powerValue);- }- return sign * baseValue;+ var value = parseFloat(str);+ if (isNaN(value))+ error('Invalid floating point number: ' + value);+ return value;},getString: function Lexer_getString() {var numParen = 1;var done = false;- var strBuf = this.strBuf;- strBuf.length = 0;-- var ch = this.nextChar();- while (true) {- var charBuffered = false;- switch (ch | 0) {- case -1:+ var str = '';+ var stream = this.stream;+ var ch;+ do {+ ch = stream.getChar();+ switch (ch) {+ case null:+ case undefined:warn('Unterminated string');done = true;break;- case 0x28: // '('+ case '(':++numParen;- strBuf.push('(');+ str += ch;break;- case 0x29: // ')'+ case ')':if (--numParen === 0) {- this.nextChar(); // consume strings ')'done = true;} else {- strBuf.push(')');+ str += ch;}break;- case 0x5C: // '\\'- ch = this.nextChar();+ case '\\':+ ch = stream.getChar();switch (ch) {- case -1:+ case null:+ case undefined:warn('Unterminated string');done = true;break;- case 0x6E: // 'n'- strBuf.push('\n');+ case 'n':+ str += '\n';break;- case 0x72: // 'r'- strBuf.push('\r');+ case 'r':+ str += '\r';break;- case 0x74: // 't'- strBuf.push('\t');+ case 't':+ str += '\t';break;- case 0x62: // 'b'- strBuf.push('\b');+ case 'b':+ str += '\b';break;- case 0x66: // 'f'- strBuf.push('\f');+ case 'f':+ str += '\f';break;- case 0x5C: // '\'- case 0x28: // '('- case 0x29: // ')'- strBuf.push(String.fromCharCode(ch));+ case '\\':+ case '(':+ case ')':+ str += ch;break;- case 0x30: case 0x31: case 0x32: case 0x33: // '0'-'3'- case 0x34: case 0x35: case 0x36: case 0x37: // '4'-'7'- var x = ch & 0x0F;- ch = this.nextChar();- charBuffered = true;- if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'- x = (x << 3) + (ch & 0x0F);- ch = this.nextChar();- if (ch >= 0x30 && ch <= 0x37) { // '0'-'7'- charBuffered = false;- x = (x << 3) + (ch & 0x0F);+ case '0': case '1': case '2': case '3':+ case '4': case '5': case '6': case '7':+ var x = ch - '0';+ ch = stream.lookChar();+ if (ch >= '0' && ch <= '7') {+ stream.skip();+ x = (x << 3) + (ch - '0');+ ch = stream.lookChar();+ if (ch >= '0' && ch <= '7') {+ stream.skip();+ x = (x << 3) + (ch - '0');}}- strBuf.push(String.fromCharCode(x));++ str += String.fromCharCode(x);break;- case 0x0D: // CR- if (this.peekChar() === 0x0A) { // LF- this.nextChar();- }+ case '\r':+ ch = stream.lookChar();+ if (ch == '\n')+ stream.skip();break;- case 0x0A: // LF+ case '\n':break;default:- strBuf.push(String.fromCharCode(ch));+ str += ch;break;}break;default:- strBuf.push(String.fromCharCode(ch));+ str += ch;break;}- if (done) {- break;- }- if (!charBuffered) {- ch = this.nextChar();- }- }- return strBuf.join('');+ } while (!done);+ return str;},- getName: function Lexer_getName() {- var ch;- var strBuf = this.strBuf;- strBuf.length = 0;- while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {- if (ch === 0x23) { // '#'- ch = this.nextChar();+ getName: function Lexer_getName(ch) {+ var str = '';+ var stream = this.stream;+ while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {+ stream.skip();+ if (ch == '#') {+ ch = stream.lookChar();var x = toHexDigit(ch);if (x != -1) {- var x2 = toHexDigit(this.nextChar());- if (x2 == -1) {+ stream.skip();+ var x2 = toHexDigit(stream.getChar());+ if (x2 == -1)error('Illegal digit in hex char in name: ' + x2);- }- strBuf.push(String.fromCharCode((x << 4) | x2));+ str += String.fromCharCode((x << 4) | x2);} else {- strBuf.push('#', String.fromCharCode(ch));+ str += '#';+ str += ch;}} else {- strBuf.push(String.fromCharCode(ch));+ str += ch;}}- if (strBuf.length > 128) {+ if (str.length > 128)error('Warning: name token is longer than allowed by the spec: ' +- strBuf.length);- }- return Name.get(strBuf.join(''));+ str.length);+ return new Name(str);},- getHexString: function Lexer_getHexString() {- var strBuf = this.strBuf;- strBuf.length = 0;- var ch = this.currentChar;+ getHexString: function Lexer_getHexString(ch) {+ var str = '';+ var stream = this.stream;var isFirstHex = true;var firstDigit;var secondDigit;while (true) {- if (ch < 0) {+ ch = stream.getChar();+ if (!ch) {warn('Unterminated hex string');break;- } else if (ch === 0x3E) { // '>'- this.nextChar();+ } else if (ch === '>') {break;- } else if (specialChars[ch] === 1) {- ch = this.nextChar();+ } else if (specialChars[ch.charCodeAt(0)] === 1) {continue;} else {if (isFirstHex) {firstDigit = toHexDigit(ch);if (firstDigit === -1) {warn('Ignoring invalid character "' + ch + '" in hex string');- ch = this.nextChar();continue;}} else {secondDigit = toHexDigit(ch);if (secondDigit === -1) {warn('Ignoring invalid character "' + ch + '" in hex string');- ch = this.nextChar();continue;}- strBuf.push(String.fromCharCode((firstDigit << 4) | secondDigit));+ str += String.fromCharCode((firstDigit << 4) | secondDigit);}isFirstHex = !isFirstHex;- ch = this.nextChar();}}- return strBuf.join('');+ return str;},getObj: function Lexer_getObj() {// skip whitespace and commentsvar comment = false;- var ch = this.currentChar;+ var stream = this.stream;+ var ch;while (true) {- if (ch < 0) {+ if (!(ch = stream.getChar()))return EOF;- }if (comment) {- if (ch === 0x0A || ch == 0x0D) { // LF, CR+ if (ch == '\r' || ch == '\n')comment = false;- }- } else if (ch === 0x25) { // '%'+ } else if (ch == '%') {comment = true;- } else if (specialChars[ch] !== 1) {+ } else if (specialChars[ch.charCodeAt(0)] != 1) {break;}- ch = this.nextChar();}// start reading token- switch (ch | 0) {- case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'- case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'- case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'- return this.getNumber();- case 0x28: // '('+ switch (ch) {+ case '0': case '1': case '2': case '3': case '4':+ case '5': case '6': case '7': case '8': case '9':+ case '+': case '-': case '.':+ return this.getNumber(ch);+ case '(':return this.getString();- case 0x2F: // '/'- return this.getName();+ case '/':+ return this.getName(ch);// array punctuation- case 0x5B: // '['- this.nextChar();- return Cmd.get('[');- case 0x5D: // ']'- this.nextChar();- return Cmd.get(']');+ case '[':+ case ']':+ return Cmd.get(ch);// hex string or dict punctuation- case 0x3C: // '<'- ch = this.nextChar();- if (ch === 0x3C) {+ case '<':+ ch = stream.lookChar();+ if (ch == '<') {// dict punctuation- this.nextChar();+ stream.skip();return Cmd.get('<<');}- return this.getHexString();+ return this.getHexString(ch);// dict punctuation- case 0x3E: // '>'- ch = this.nextChar();- if (ch === 0x3E) {- this.nextChar();+ case '>':+ ch = stream.lookChar();+ if (ch == '>') {+ stream.skip();return Cmd.get('>>');}- return Cmd.get('>');- case 0x7B: // '{'- this.nextChar();- return Cmd.get('{');- case 0x7D: // '}'- this.nextChar();- return Cmd.get('}');- case 0x29: // ')'+ return Cmd.get(ch);+ case '{':+ case '}':+ return Cmd.get(ch);+ // fall through+ case ')':error('Illegal character: ' + ch);- break;}// command- var str = String.fromCharCode(ch);+ var str = ch;var knownCommands = this.knownCommands;var knownCommandFound = knownCommands && (str in knownCommands);- while ((ch = this.nextChar()) >= 0 && !specialChars[ch]) {+ while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {// stop if known command is found and next character does not make// the str a command- var possibleCommand = str + String.fromCharCode(ch);- if (knownCommandFound && !(possibleCommand in knownCommands)) {+ if (knownCommandFound && !((str + ch) in knownCommands))break;- }- if (str.length == 128) {+ stream.skip();+ if (str.length == 128)error('Command token too long: ' + str.length);- }- str = possibleCommand;+ str += ch;knownCommandFound = knownCommands && (str in knownCommands);}- if (str == 'true') {+ if (str == 'true')return true;- }- if (str == 'false') {+ if (str == 'false')return false;- }- if (str == 'null') {+ if (str == 'null')return null;- }return Cmd.get(str);},skipToNextLine: function Lexer_skipToNextLine() {var stream = this.stream;- var ch = this.currentChar;- while (ch >= 0) {- if (ch === 0x0D) { // CR- ch = this.nextChar();- if (ch === 0x0A) { // LF- this.nextChar();- }- break;- } else if (ch === 0x0A) { // LF- this.nextChar();- break;+ while (true) {+ var ch = stream.getChar();+ if (!ch || ch == '\n')+ return;+ if (ch == '\r') {+ if ((ch = stream.lookChar()) == '\n')+ stream.skip();+ return;}- ch = this.nextChar();}+ },+ skip: function Lexer_skip() {+ this.stream.skip();}};@@ -34488,9 +34050,8 @@ var Linearization = (function LinearizationClosure() {if (isInt(obj1) && isInt(obj2) && isCmd(obj3, 'obj') &&isDict(this.linDict)) {var obj = this.linDict.get('Linearized');- if (!(isNum(obj) && obj > 0)) {+ if (!(isNum(obj) && obj > 0))this.linDict = null;- }}}@@ -34498,7 +34059,9 @@ var Linearization = (function LinearizationClosure() {getInt: function Linearization_getInt(name) {var linDict = this.linDict;var obj;- if (isDict(linDict) && isInt(obj = linDict.get(name)) && obj > 0) {+ if (isDict(linDict) &&+ isInt(obj = linDict.get(name)) &&+ obj > 0) {return obj;}error('"' + name + '" field in linearization table is invalid');@@ -34506,16 +34069,18 @@ var Linearization = (function LinearizationClosure() {getHint: function Linearization_getHint(index) {var linDict = this.linDict;var obj1, obj2;- if (isDict(linDict) && isArray(obj1 = linDict.get('H')) &&- obj1.length >= 2 && isInt(obj2 = obj1[index]) && obj2 > 0) {+ if (isDict(linDict) &&+ isArray(obj1 = linDict.get('H')) &&+ obj1.length >= 2 &&+ isInt(obj2 = obj1[index]) &&+ obj2 > 0) {return obj2;}error('Hints table in linearization table is invalid: ' + index);},get length() {- if (!isDict(this.linDict)) {+ if (!isDict(this.linDict))return 0;- }return this.getInt('L');},get hintsOffset() {@@ -34552,206 +34117,415 @@ var Linearization = (function LinearizationClosure() {-var PostScriptParser = (function PostScriptParserClosure() {- function PostScriptParser(lexer) {- this.lexer = lexer;- this.operators = [];- this.token = null;- this.prev = null;+var PatternType = {+ AXIAL: 2,+ RADIAL: 3+};++var Pattern = (function PatternClosure() {+ // Constructor should define this.getPattern+ function Pattern() {+ error('should not call Pattern constructor');}- PostScriptParser.prototype = {- nextToken: function PostScriptParser_nextToken() {- this.prev = this.token;- this.token = this.lexer.getToken();- },- accept: function PostScriptParser_accept(type) {- if (this.token.type == type) {- this.nextToken();- return true;++ Pattern.prototype = {+ // Input: current Canvas context+ // Output: the appropriate fillStyle or strokeStyle+ getPattern: function Pattern_getPattern(ctx) {+ error('Should not call Pattern.getStyle: ' + ctx);+ }+ };++ Pattern.shadingFromIR = function Pattern_shadingFromIR(raw) {+ return Shadings[raw[0]].fromIR(raw);+ };++ Pattern.parseShading = function Pattern_parseShading(shading, matrix, xref,+ res) {++ var dict = isStream(shading) ? shading.dict : shading;+ var type = dict.get('ShadingType');++ switch (type) {+ case PatternType.AXIAL:+ case PatternType.RADIAL:+ // Both radial and axial shadings are handled by RadialAxial shading.+ return new Shadings.RadialAxial(dict, matrix, xref, res);+ default:+ TODO('Unsupported shading type: ' + type);+ return new Shadings.Dummy();+ }+ };+ return Pattern;+})();++var Shadings = {};++// A small number to offset the first/last color stops so we can insert ones to+// support extend. Number.MIN_VALUE appears to be too small and breaks the+// extend. 1e-7 works in FF but chrome seems to use an even smaller sized number+// internally so we have to go bigger.+Shadings.SMALL_NUMBER = 1e-2;++// Radial and axial shading have very similar implementations+// If needed, the implementations can be broken into two classes+Shadings.RadialAxial = (function RadialAxialClosure() {+ function RadialAxial(dict, matrix, xref, res, ctx) {+ this.matrix = matrix;+ this.coordsArr = dict.get('Coords');+ this.shadingType = dict.get('ShadingType');+ this.type = 'Pattern';+ this.ctx = ctx;+ var cs = dict.get('ColorSpace', 'CS');+ cs = ColorSpace.parse(cs, xref, res);+ this.cs = cs;++ var t0 = 0.0, t1 = 1.0;+ if (dict.has('Domain')) {+ var domainArr = dict.get('Domain');+ t0 = domainArr[0];+ t1 = domainArr[1];+ }++ var extendStart = false, extendEnd = false;+ if (dict.has('Extend')) {+ var extendArr = dict.get('Extend');+ extendStart = extendArr[0];+ extendEnd = extendArr[1];+ }++ if (this.shadingType === PatternType.RADIAL &&+ (!extendStart || !extendEnd)) {+ // Radial gradient only currently works if either circle is fully within+ // the other circle.+ var x1 = this.coordsArr[0];+ var y1 = this.coordsArr[1];+ var r1 = this.coordsArr[2];+ var x2 = this.coordsArr[3];+ var y2 = this.coordsArr[4];+ var r2 = this.coordsArr[5];+ var distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));+ if (r1 <= r2 + distance &&+ r2 <= r1 + distance) {+ warn('Unsupported radial gradient.');}- return false;- },- expect: function PostScriptParser_expect(type) {- if (this.accept(type)) {- return true;+ }++ this.extendStart = extendStart;+ this.extendEnd = extendEnd;++ var fnObj = dict.get('Function');+ var fn;+ if (isArray(fnObj)) {+ var fnArray = [];+ for (var j = 0, jj = fnObj.length; j < jj; j++) {+ var obj = xref.fetchIfRef(fnObj[j]);+ if (!isPDFFunction(obj)) {+ error('Invalid function');+ }+ fnArray.push(PDFFunction.parse(xref, obj));}- error('Unexpected symbol: found ' + this.token.type + ' expected ' +- type + '.');- },- parse: function PostScriptParser_parse() {- this.nextToken();- this.expect(PostScriptTokenTypes.LBRACE);- this.parseBlock();- this.expect(PostScriptTokenTypes.RBRACE);- return this.operators;- },- parseBlock: function PostScriptParser_parseBlock() {- while (true) {- if (this.accept(PostScriptTokenTypes.NUMBER)) {- this.operators.push(this.prev.value);- } else if (this.accept(PostScriptTokenTypes.OPERATOR)) {- this.operators.push(this.prev.value);- } else if (this.accept(PostScriptTokenTypes.LBRACE)) {- this.parseCondition();- } else {- return;+ fn = function radialAxialColorFunction(arg) {+ var out = [];+ for (var i = 0, ii = fnArray.length; i < ii; i++) {+ out.push(fnArray[i](arg)[0]);}+ return out;+ };+ } else {+ if (!isPDFFunction(fnObj)) {+ error('Invalid function');}- },- parseCondition: function PostScriptParser_parseCondition() {- // Add two place holders that will be updated later- var conditionLocation = this.operators.length;- this.operators.push(null, null);+ fn = PDFFunction.parse(xref, fnObj);+ }- this.parseBlock();- this.expect(PostScriptTokenTypes.RBRACE);- if (this.accept(PostScriptTokenTypes.IF)) {- // The true block is right after the 'if' so it just falls through on- // true else it jumps and skips the true block.- this.operators[conditionLocation] = this.operators.length;- this.operators[conditionLocation + 1] = 'jz';- } else if (this.accept(PostScriptTokenTypes.LBRACE)) {- var jumpLocation = this.operators.length;- this.operators.push(null, null);- var endOfTrue = this.operators.length;- this.parseBlock();- this.expect(PostScriptTokenTypes.RBRACE);- this.expect(PostScriptTokenTypes.IFELSE);- // The jump is added at the end of the true block to skip the false- // block.- this.operators[jumpLocation] = this.operators.length;- this.operators[jumpLocation + 1] = 'j';+ // 10 samples seems good enough for now, but probably won't work+ // if there are sharp color changes. Ideally, we would implement+ // the spec faithfully and add lossless optimizations.+ var diff = t1 - t0;+ var step = diff / 10;- this.operators[conditionLocation] = endOfTrue;- this.operators[conditionLocation + 1] = 'jz';+ var colorStops = this.colorStops = [];++ // Protect against bad domains so we don't end up in an infinte loop below.+ if (t0 >= t1 || step <= 0) {+ // Acrobat doesn't seem to handle these cases so we'll ignore for+ // now.+ info('Bad shading domain.');+ return;+ }++ for (var i = t0; i <= t1; i += step) {+ var rgbColor = cs.getRgb(fn([i]), 0);+ var cssColor = Util.makeCssRgb(rgbColor);+ colorStops.push([(i - t0) / diff, cssColor]);+ }++ var background = 'transparent';+ if (dict.has('Background')) {+ var rgbColor = cs.getRgb(dict.get('Background'), 0);+ background = Util.makeCssRgb(rgbColor);+ }++ if (!extendStart) {+ // Insert a color stop at the front and offset the first real color stop+ // so it doesn't conflict with the one we insert.+ colorStops.unshift([0, background]);+ colorStops[1][0] += Shadings.SMALL_NUMBER;+ }+ if (!extendEnd) {+ // Same idea as above in extendStart but for the end.+ colorStops[colorStops.length - 1][0] -= Shadings.SMALL_NUMBER;+ colorStops.push([1, background]);+ }++ this.colorStops = colorStops;+ }++ RadialAxial.fromIR = function RadialAxial_fromIR(raw) {+ var type = raw[1];+ var colorStops = raw[2];+ var p0 = raw[3];+ var p1 = raw[4];+ var r0 = raw[5];+ var r1 = raw[6];+ return {+ type: 'Pattern',+ getPattern: function RadialAxial_getPattern(ctx) {+ var grad;+ if (type == PatternType.AXIAL)+ grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);+ else if (type == PatternType.RADIAL)+ grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);++ for (var i = 0, ii = colorStops.length; i < ii; ++i) {+ var c = colorStops[i];+ grad.addColorStop(c[0], c[1]);+ }+ return grad;+ }+ };+ };++ RadialAxial.prototype = {+ getIR: function RadialAxial_getIR() {+ var coordsArr = this.coordsArr;+ var type = this.shadingType;+ if (type == PatternType.AXIAL) {+ var p0 = [coordsArr[0], coordsArr[1]];+ var p1 = [coordsArr[2], coordsArr[3]];+ var r0 = null;+ var r1 = null;+ } else if (type == PatternType.RADIAL) {+ var p0 = [coordsArr[0], coordsArr[1]];+ var p1 = [coordsArr[3], coordsArr[4]];+ var r0 = coordsArr[2];+ var r1 = coordsArr[5];} else {- error('PS Function: error parsing conditional.');+ error('getPattern type unknown: ' + type);+ }++ var matrix = this.matrix;+ if (matrix) {+ p0 = Util.applyTransform(p0, matrix);+ p1 = Util.applyTransform(p1, matrix);}++ return ['RadialAxial', type, this.colorStops, p0, p1, r0, r1];}};- return PostScriptParser;-})();-var PostScriptTokenTypes = {- LBRACE: 0,- RBRACE: 1,- NUMBER: 2,- OPERATOR: 3,- IF: 4,- IFELSE: 5-};+ return RadialAxial;+})();-var PostScriptToken = (function PostScriptTokenClosure() {- function PostScriptToken(type, value) {- this.type = type;- this.value = value;+Shadings.Dummy = (function DummyClosure() {+ function Dummy() {+ this.type = 'Pattern';}- var opCache = {};+ Dummy.fromIR = function Dummy_fromIR() {+ return {+ type: 'Pattern',+ getPattern: function Dummy_fromIR_getPattern() {+ return 'hotpink';+ }+ };+ };- PostScriptToken.getOperator = function PostScriptToken_getOperator(op) {- var opValue = opCache[op];- if (opValue) {- return opValue;+ Dummy.prototype = {+ getIR: function Dummy_getIR() {+ return ['Dummy'];}- return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op);};-- PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE,- '{');- PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE,- '}');- PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF');- PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE,- 'IFELSE');- return PostScriptToken;+ return Dummy;})();-var PostScriptLexer = (function PostScriptLexerClosure() {- function PostScriptLexer(stream) {- this.stream = stream;- this.nextChar();+var TilingPattern = (function TilingPatternClosure() {+ var PaintType = {+ COLORED: 1,+ UNCOLORED: 2+ };++ var MAX_PATTERN_SIZE = 8192;++ function TilingPattern(IR, color, ctx, objs, commonObjs) {+ this.name = IR[1][0].name;+ this.operatorList = IR[2];+ this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];+ this.bbox = IR[4];+ this.xstep = IR[5];+ this.ystep = IR[6];+ this.paintType = IR[7];+ this.tilingType = IR[8];+ this.color = color;+ this.objs = objs;+ this.commonObjs = commonObjs;+ this.curMatrix = ctx.mozCurrentTransform;+ this.type = 'Pattern';+ this.ctx = ctx;}- PostScriptLexer.prototype = {- nextChar: function PostScriptLexer_nextChar() {- return (this.currentChar = this.stream.getByte());++ TilingPattern.getIR = function TilingPattern_getIR(operatorList, dict, args) {+ var matrix = dict.get('Matrix');+ var bbox = dict.get('BBox');+ var xstep = dict.get('XStep');+ var ystep = dict.get('YStep');+ var paintType = dict.get('PaintType');+ var tilingType = dict.get('TilingType');++ return [+ 'TilingPattern', args, operatorList, matrix, bbox, xstep, ystep,+ paintType, tilingType+ ];+ };++ TilingPattern.prototype = {+ createPatternCanvas: function TilinPattern_createPatternCanvas(tmpCanvas) {+ var operatorList = this.operatorList;+ var bbox = this.bbox;+ var xstep = this.xstep;+ var ystep = this.ystep;+ var paintType = this.paintType;+ var tilingType = this.tilingType;+ var color = this.color;+ var objs = this.objs;+ var commonObjs = this.commonObjs;+ var ctx = this.ctx;++ TODO('TilingType: ' + tilingType);++ var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];++ var topLeft = [x0, y0];+ // we want the canvas to be as large as the step size+ var botRight = [x0 + xstep, y0 + ystep];++ var width = botRight[0] - topLeft[0];+ var height = botRight[1] - topLeft[1];++ // Obtain scale from matrix and current transformation matrix.+ var matrixScale = Util.singularValueDecompose2dScale(this.matrix);+ var curMatrixScale = Util.singularValueDecompose2dScale(this.curMatrix);+ var combinedScale = [matrixScale[0] * curMatrixScale[0],+ matrixScale[1] * curMatrixScale[1]];++ // MAX_PATTERN_SIZE is used to avoid OOM situation.+ // Use width and height values that are as close as possible to the end+ // result when the pattern is used. Too low value makes the pattern look+ // blurry. Too large value makes it look too crispy.+ width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),+ MAX_PATTERN_SIZE);++ height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),+ MAX_PATTERN_SIZE);++ tmpCanvas.width = width;+ tmpCanvas.height = height;++ // set the new canvas element context as the graphics context+ var tmpCtx = tmpCanvas.getContext('2d');+ var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);++ this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);++ this.setScale(width, height, xstep, ystep);+ this.transformToScale(graphics);++ // transform coordinates to pattern space+ var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];+ graphics.transform.apply(graphics, tmpTranslate);++ this.clipBbox(graphics, bbox, x0, y0, x1, y1);++ graphics.executeOperatorList(operatorList);},- getToken: function PostScriptLexer_getToken() {- var s = '';- var comment = false;- var ch = this.currentChar;- // skip comments- while (true) {- if (ch < 0) {- return EOF;- }+ setScale: function TilingPattern_setScale(width, height, xstep, ystep) {+ this.scale = [width / xstep, height / ystep];+ },- if (comment) {- if (ch === 0x0A || ch === 0x0D) {- comment = false;- }- } else if (ch == 0x25) { // '%'- comment = true;- } else if (!Lexer.isSpace(ch)) {- break;- }- ch = this.nextChar();- }- switch (ch | 0) {- case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4'- case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9'- case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.'- return new PostScriptToken(PostScriptTokenTypes.NUMBER,- this.getNumber());- case 0x7B: // '{'- this.nextChar();- return PostScriptToken.LBRACE;- case 0x7D: // '}'- this.nextChar();- return PostScriptToken.RBRACE;- }- // operator- var str = String.fromCharCode(ch);- while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z'- ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) {- str += String.fromCharCode(ch);- }- switch (str.toLowerCase()) {- case 'if':- return PostScriptToken.IF;- case 'ifelse':- return PostScriptToken.IFELSE;- default:- return PostScriptToken.getOperator(str);+ transformToScale: function TilingPattern_transformToScale(graphics) {+ var scale = this.scale;+ var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];+ graphics.transform.apply(graphics, tmpScale);+ },++ scaleToContext: function TilingPattern_scaleToContext() {+ var scale = this.scale;+ this.ctx.scale(1 / scale[0], 1 / scale[1]);+ },++ clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {+ if (bbox && isArray(bbox) && 4 == bbox.length) {+ var bboxWidth = x1 - x0;+ var bboxHeight = y1 - y0;+ graphics.rectangle(x0, y0, bboxWidth, bboxHeight);+ graphics.clip();+ graphics.endPath();}},- getNumber: function PostScriptLexer_getNumber() {- var ch = this.currentChar;- var str = String.fromCharCode(ch);- while ((ch = this.nextChar()) >= 0) {- if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9'- ch === 0x2D || ch === 0x2E) { // '-', '.'- str += String.fromCharCode(ch);- } else {++ setFillAndStrokeStyleToContext:+ function setFillAndStrokeStyleToContext(context, paintType, color) {+ switch (paintType) {+ case PaintType.COLORED:+ var ctx = this.ctx;+ context.fillStyle = ctx.fillStyle;+ context.strokeStyle = ctx.strokeStyle;break;- }- }- var value = parseFloat(str);- if (isNaN(value)) {- error('Invalid floating point number: ' + value);+ case PaintType.UNCOLORED:+ var rgbColor = new DeviceRgbCS().getRgb(color, 0);+ var cssColor = Util.makeCssRgb(rgbColor);+ context.fillStyle = cssColor;+ context.strokeStyle = cssColor;+ break;+ default:+ error('Unsupported paint type: ' + paintType);}- return value;+ },++ getPattern: function TilingPattern_getPattern() {+ var temporaryPatternCanvas = CachedCanvases.getCanvas('pattern');+ this.createPatternCanvas(temporaryPatternCanvas);++ var ctx = this.ctx;+ ctx.setTransform.apply(ctx, this.curMatrix);+ ctx.transform.apply(ctx, this.matrix);+ this.scaleToContext();++ return ctx.createPattern(temporaryPatternCanvas, 'repeat');}};- return PostScriptLexer;++ return TilingPattern;})();+var Stream = (function StreamClosure() {function Stream(arrayBuffer, start, length, dict) {- this.bytes = (arrayBuffer instanceof Uint8Array ?- arrayBuffer : new Uint8Array(arrayBuffer));+ this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer :+ new Uint8Array(arrayBuffer);this.start = start || 0;this.pos = this.start;this.end = (start + length) || this.bytes.length;@@ -34765,23 +34539,10 @@ var Stream = (function StreamClosure() {return this.end - this.start;},getByte: function Stream_getByte() {- if (this.pos >= this.end) {- return -1;- }+ if (this.pos >= this.end)+ return null;return this.bytes[this.pos++];},- getUint16: function Stream_getUint16() {- var b0 = this.getByte();- var b1 = this.getByte();- return (b0 << 8) + b1;- },- getUint32: function Stream_getUint32() {- var b0 = this.getByte();- var b1 = this.getByte();- var b2 = this.getByte();- var b3 = this.getByte();- return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;- },// returns subarray of original buffer// should only be readgetBytes: function Stream_getBytes(length) {@@ -34789,13 +34550,13 @@ var Stream = (function StreamClosure() {var pos = this.pos;var strEnd = this.end;- if (!length) {+ if (!length)return bytes.subarray(pos, strEnd);- }+var end = pos + length;- if (end > strEnd) {+ if (end > strEnd)end = strEnd;- }+this.pos = end;return bytes.subarray(pos, end);},@@ -34804,10 +34565,19 @@ var Stream = (function StreamClosure() {this.pos -= bytes.length;return bytes;},+ lookChar: function Stream_lookChar() {+ if (this.pos >= this.end)+ return null;+ return String.fromCharCode(this.bytes[this.pos]);+ },+ getChar: function Stream_getChar() {+ if (this.pos >= this.end)+ return null;+ return String.fromCharCode(this.bytes[this.pos++]);+ },skip: function Stream_skip(n) {- if (!n) {+ if (!n)n = 1;- }this.pos += n;},reset: function Stream_reset() {@@ -34829,9 +34599,8 @@ var StringStream = (function StringStreamClosure() {function StringStream(str) {var length = str.length;var bytes = new Uint8Array(length);- for (var n = 0; n < length; ++n) {+ for (var n = 0; n < length; ++n)bytes[n] = str.charCodeAt(n);- }Stream.call(this, bytes);}@@ -34842,64 +34611,36 @@ var StringStream = (function StringStreamClosure() {// super class for the decoding streamsvar DecodeStream = (function DecodeStreamClosure() {- function DecodeStream(maybeMinBufferLength) {+ function DecodeStream() {this.pos = 0;this.bufferLength = 0;this.eof = false;this.buffer = null;- this.minBufferLength = 512;- if (maybeMinBufferLength) {- // Compute the first power of two that is as big as maybeMinBufferLength.- while (this.minBufferLength < maybeMinBufferLength) {- this.minBufferLength *= 2;- }- }}DecodeStream.prototype = {ensureBuffer: function DecodeStream_ensureBuffer(requested) {var buffer = this.buffer;- var current;- if (buffer) {- current = buffer.byteLength;- if (requested <= current) {- return buffer;- }- } else {- current = 0;- }- var size = this.minBufferLength;- while (size < requested) {- size *= 2;- }+ var current = buffer ? buffer.byteLength : 0;+ if (requested < current)+ return buffer;+ var size = 512;+ while (size < requested)+ size <<= 1;var buffer2 = new Uint8Array(size);- for (var i = 0; i < current; ++i) {+ for (var i = 0; i < current; ++i)buffer2[i] = buffer[i];- }return (this.buffer = buffer2);},getByte: function DecodeStream_getByte() {var pos = this.pos;while (this.bufferLength <= pos) {- if (this.eof) {- return -1;- }+ if (this.eof)+ return null;this.readBlock();}return this.buffer[this.pos++];},- getUint16: function DecodeStream_getUint16() {- var b0 = this.getByte();- var b1 = this.getByte();- return (b0 << 8) + b1;- },- getUint32: function DecodeStream_getUint32() {- var b0 = this.getByte();- var b1 = this.getByte();- var b2 = this.getByte();- var b3 = this.getByte();- return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;- },getBytes: function DecodeStream_getBytes(length) {var end, pos = this.pos;@@ -34907,24 +34648,22 @@ var DecodeStream = (function DecodeStreamClosure() {this.ensureBuffer(pos + length);end = pos + length;- while (!this.eof && this.bufferLength < end) {+ while (!this.eof && this.bufferLength < end)this.readBlock();- }+var bufEnd = this.bufferLength;- if (end > bufEnd) {+ if (end > bufEnd)end = bufEnd;- }} else {- while (!this.eof) {+ while (!this.eof)this.readBlock();- }+end = this.bufferLength;// checking if bufferLength is still 0 then// the buffer has to be initialized- if (!end) {+ if (!end)this.buffer = new Uint8Array(0);- }}this.pos = end;@@ -34935,43 +34674,92 @@ var DecodeStream = (function DecodeStreamClosure() {this.pos -= bytes.length;return bytes;},+ lookChar: function DecodeStream_lookChar() {+ var pos = this.pos;+ while (this.bufferLength <= pos) {+ if (this.eof)+ return null;+ this.readBlock();+ }+ return String.fromCharCode(this.buffer[this.pos]);+ },+ getChar: function DecodeStream_getChar() {+ var pos = this.pos;+ while (this.bufferLength <= pos) {+ if (this.eof)+ return null;+ this.readBlock();+ }+ return String.fromCharCode(this.buffer[this.pos++]);+ },makeSubStream: function DecodeStream_makeSubStream(start, length, dict) {var end = start + length;- while (this.bufferLength <= end && !this.eof) {+ while (this.bufferLength <= end && !this.eof)this.readBlock();- }return new Stream(this.buffer, start, length, dict);},- skip: function Stream_skip(n) {- if (!n) {+ skip: function DecodeStream_skip(n) {+ if (!n)n = 1;- }this.pos += n;},reset: function DecodeStream_reset() {this.pos = 0;- },- getBaseStreams: function DecodeStream_getBaseStreams() {- if (this.str && this.str.getBaseStreams) {- return this.str.getBaseStreams();- }- return [];}};return DecodeStream;})();+var FakeStream = (function FakeStreamClosure() {+ function FakeStream(stream) {+ this.dict = stream.dict;+ DecodeStream.call(this);+ }++ FakeStream.prototype = Object.create(DecodeStream.prototype);+ FakeStream.prototype.readBlock = function FakeStream_readBlock() {+ var bufferLength = this.bufferLength;+ bufferLength += 1024;+ var buffer = this.ensureBuffer(bufferLength);+ this.bufferLength = bufferLength;+ };++ FakeStream.prototype.getBytes = function FakeStream_getBytes(length) {+ var end, pos = this.pos;++ if (length) {+ this.ensureBuffer(pos + length);+ end = pos + length;++ while (!this.eof && this.bufferLength < end)+ this.readBlock();++ var bufEnd = this.bufferLength;+ if (end > bufEnd)+ end = bufEnd;+ } else {+ this.eof = true;+ end = this.bufferLength;+ }++ this.pos = end;+ return this.buffer.subarray(pos, end);+ };++ return FakeStream;+})();+var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {function StreamsSequenceStream(streams) {this.streams = streams;- DecodeStream.call(this, /* maybeLength = */ null);+ DecodeStream.call(this);}StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);StreamsSequenceStream.prototype.readBlock =- function streamSequenceStreamReadBlock() {+ function streamSequenceStreamReadBlock() {var streams = this.streams;if (streams.length === 0) {@@ -34987,19 +34775,6 @@ var StreamsSequenceStream = (function StreamsSequenceStreamClosure() {this.bufferLength = newLength;};- StreamsSequenceStream.prototype.getBaseStreams =- function StreamsSequenceStream_getBaseStreams() {-- var baseStreams = [];- for (var i = 0, ii = this.streams.length; i < ii; i++) {- var stream = this.streams[i];- if (stream.getBaseStreams) {- Util.concatenateToArray(baseStreams, stream.getBaseStreams());- }- }- return baseStreams;- };-return StreamsSequenceStream;})();@@ -35096,76 +34871,76 @@ var FlateStream = (function FlateStreamClosure() {0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000]), 5];- function FlateStream(str, maybeLength) {- this.str = str;- this.dict = str.dict;+ function FlateStream(stream) {+ var bytes = stream.getBytes();+ var bytesPos = 0;- var cmf = str.getByte();- var flg = str.getByte();- if (cmf == -1 || flg == -1) {+ this.dict = stream.dict;+ var cmf = bytes[bytesPos++];+ var flg = bytes[bytesPos++];+ if (cmf == -1 || flg == -1)error('Invalid header in flate stream: ' + cmf + ', ' + flg);- }- if ((cmf & 0x0f) != 0x08) {+ if ((cmf & 0x0f) != 0x08)error('Unknown compression method in flate stream: ' + cmf + ', ' + flg);- }- if ((((cmf << 8) + flg) % 31) !== 0) {+ if ((((cmf << 8) + flg) % 31) !== 0)error('Bad FCHECK in flate stream: ' + cmf + ', ' + flg);- }- if (flg & 0x20) {+ if (flg & 0x20)error('FDICT bit set in flate stream: ' + cmf + ', ' + flg);- }++ this.bytes = bytes;+ this.bytesPos = bytesPos;this.codeSize = 0;this.codeBuf = 0;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}FlateStream.prototype = Object.create(DecodeStream.prototype);FlateStream.prototype.getBits = function FlateStream_getBits(bits) {- var str = this.str;var codeSize = this.codeSize;var codeBuf = this.codeBuf;+ var bytes = this.bytes;+ var bytesPos = this.bytesPos;var b;while (codeSize < bits) {- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad encoding in flate stream');- }codeBuf |= b << codeSize;codeSize += 8;}b = codeBuf & ((1 << bits) - 1);this.codeBuf = codeBuf >> bits;this.codeSize = codeSize -= bits;-+ this.bytesPos = bytesPos;return b;};FlateStream.prototype.getCode = function FlateStream_getCode(table) {- var str = this.str;var codes = table[0];var maxLen = table[1];var codeSize = this.codeSize;var codeBuf = this.codeBuf;+ var bytes = this.bytes;+ var bytesPos = this.bytesPos;while (codeSize < maxLen) {var b;- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad encoding in flate stream');- }codeBuf |= (b << codeSize);codeSize += 8;}var code = codes[codeBuf & ((1 << maxLen) - 1)];var codeLen = code >> 16;var codeVal = code & 0xffff;- if (codeSize === 0 || codeSize < codeLen || codeLen === 0) {+ if (codeSize === 0 || codeSize < codeLen || codeLen === 0)error('Bad encoding in flate stream');- }this.codeBuf = (codeBuf >> codeLen);this.codeSize = (codeSize - codeLen);+ this.bytesPos = bytesPos;return codeVal;};@@ -35175,11 +34950,9 @@ var FlateStream = (function FlateStreamClosure() {// find max code lengthvar maxLen = 0;- var i;- for (i = 0; i < n; ++i) {- if (lengths[i] > maxLen) {+ for (var i = 0; i < n; ++i) {+ if (lengths[i] > maxLen)maxLen = lengths[i];- }}// build the table@@ -35193,15 +34966,15 @@ var FlateStream = (function FlateStreamClosure() {// bit-reverse the codevar code2 = 0;var t = code;- for (i = 0; i < len; ++i) {+ for (var i = 0; i < len; ++i) {code2 = (code2 << 1) | (t & 1);t >>= 1;}// fill the table entries- for (i = code2; i < size; i += skip) {+ for (var i = code2; i < size; i += skip)codes[i] = (len << 16) | val;- }+++code;}}@@ -35211,33 +34984,28 @@ var FlateStream = (function FlateStreamClosure() {};FlateStream.prototype.readBlock = function FlateStream_readBlock() {- var buffer, len;- var str = this.str;// read block headervar hdr = this.getBits(3);- if (hdr & 1) {+ if (hdr & 1)this.eof = true;- }hdr >>= 1;if (hdr === 0) { // uncompressed block+ var bytes = this.bytes;+ var bytesPos = this.bytesPos;var b;- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad block header in flate stream');- }var blockLen = b;- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad block header in flate stream');- }blockLen |= (b << 8);- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad block header in flate stream');- }var check = b;- if ((b = str.getByte()) === -1) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined')error('Bad block header in flate stream');- }check |= (b << 8);if (check != (~blockLen & 0xffff) &&(blockLen !== 0 || check !== 0)) {@@ -35249,22 +35017,17 @@ var FlateStream = (function FlateStreamClosure() {this.codeSize = 0;var bufferLength = this.bufferLength;- buffer = this.ensureBuffer(bufferLength + blockLen);+ var buffer = this.ensureBuffer(bufferLength + blockLen);var end = bufferLength + blockLen;this.bufferLength = end;- if (blockLen === 0) {- if (str.peekBytes(1).length === 0) {+ for (var n = bufferLength; n < end; ++n) {+ if (typeof (b = bytes[bytesPos++]) == 'undefined') {this.eof = true;+ break;}- } else {- for (var n = bufferLength; n < end; ++n) {- if ((b = str.getByte()) === -1) {- this.eof = true;- break;- }- buffer[n] = b;- }+ buffer[n] = b;}+ this.bytesPos = bytesPos;return;}@@ -35281,35 +35044,31 @@ var FlateStream = (function FlateStreamClosure() {// build the code lengths code tablevar codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);- var i;- for (i = 0; i < numCodeLenCodes; ++i) {+ for (var i = 0; i < numCodeLenCodes; ++i)codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);- }var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);// build the literal and distance code tables- len = 0;- i = 0;+ var len = 0;+ var i = 0;var codes = numLitCodes + numDistCodes;var codeLengths = new Uint8Array(codes);- var bitsLength, bitsOffset, what;while (i < codes) {var code = this.getCode(codeLenCodeTab);if (code == 16) {- bitsLength = 2; bitsOffset = 3; what = len;+ var bitsLength = 2, bitsOffset = 3, what = len;} else if (code == 17) {- bitsLength = 3; bitsOffset = 3; what = (len = 0);+ var bitsLength = 3, bitsOffset = 3, what = (len = 0);} else if (code == 18) {- bitsLength = 7; bitsOffset = 11; what = (len = 0);+ var bitsLength = 7, bitsOffset = 11, what = (len = 0);} else {codeLengths[i++] = len = code;continue;}var repeatLength = this.getBits(bitsLength) + bitsOffset;- while (repeatLength-- > 0) {+ while (repeatLength-- > 0)codeLengths[i++] = what;- }}litCodeTable =@@ -35320,7 +35079,7 @@ var FlateStream = (function FlateStreamClosure() {error('Unknown block type in flate stream');}- buffer = this.buffer;+ var buffer = this.buffer;var limit = buffer ? buffer.length : 0;var pos = this.bufferLength;while (true) {@@ -35340,24 +35099,21 @@ var FlateStream = (function FlateStreamClosure() {code1 -= 257;code1 = lengthDecode[code1];var code2 = code1 >> 16;- if (code2 > 0) {+ if (code2 > 0)code2 = this.getBits(code2);- }- len = (code1 & 0xffff) + code2;+ var len = (code1 & 0xffff) + code2;code1 = this.getCode(distCodeTable);code1 = distDecode[code1];code2 = code1 >> 16;- if (code2 > 0) {+ if (code2 > 0)code2 = this.getBits(code2);- }var dist = (code1 & 0xffff) + code2;if (pos + len >= limit) {buffer = this.ensureBuffer(pos + len);limit = buffer.length;}- for (var k = 0; k < len; ++k, ++pos) {+ for (var k = 0; k < len; ++k, ++pos)buffer[pos] = buffer[pos - dist];- }}};@@ -35365,24 +35121,21 @@ var FlateStream = (function FlateStreamClosure() {})();var PredictorStream = (function PredictorStreamClosure() {- function PredictorStream(str, maybeLength, params) {+ function PredictorStream(stream, params) {var predictor = this.predictor = params.get('Predictor') || 1;- if (predictor <= 1) {- return str; // no prediction- }- if (predictor !== 2 && (predictor < 10 || predictor > 15)) {+ if (predictor <= 1)+ return stream; // no prediction+ if (predictor !== 2 && (predictor < 10 || predictor > 15))error('Unsupported predictor: ' + predictor);- }- if (predictor === 2) {+ if (predictor === 2)this.readBlock = this.readBlockTiff;- } else {+ elsethis.readBlock = this.readBlockPng;- }- this.str = str;- this.dict = str.dict;+ this.stream = stream;+ this.dict = stream.dict;var colors = this.colors = params.get('Colors') || 1;var bits = this.bits = params.get('BitsPerComponent') || 8;@@ -35391,14 +35144,14 @@ var PredictorStream = (function PredictorStreamClosure() {this.pixBytes = (colors * bits + 7) >> 3;this.rowBytes = (columns * colors * bits + 7) >> 3;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);return this;}PredictorStream.prototype = Object.create(DecodeStream.prototype);PredictorStream.prototype.readBlockTiff =- function predictorStreamReadBlockTiff() {+ function predictorStreamReadBlockTiff() {var rowBytes = this.rowBytes;var bufferLength = this.bufferLength;@@ -35407,7 +35160,7 @@ var PredictorStream = (function PredictorStreamClosure() {var bits = this.bits;var colors = this.colors;- var rawBytes = this.str.getBytes(rowBytes);+ var rawBytes = this.stream.getBytes(rowBytes);this.eof = !rawBytes.length;if (this.eof) {return;@@ -35416,10 +35169,9 @@ var PredictorStream = (function PredictorStreamClosure() {var inbuf = 0, outbuf = 0;var inbits = 0, outbits = 0;var pos = bufferLength;- var i;if (bits === 1) {- for (i = 0; i < rowBytes; ++i) {+ for (var i = 0; i < rowBytes; ++i) {var c = rawBytes[i];inbuf = (inbuf << 8) | c;// bitwise addition is exclusive or@@ -35429,9 +35181,8 @@ var PredictorStream = (function PredictorStreamClosure() {inbuf &= 0xFFFF;}} else if (bits === 8) {- for (i = 0; i < colors; ++i) {+ for (var i = 0; i < colors; ++i)buffer[pos++] = rawBytes[i];- }for (; i < rowBytes; ++i) {buffer[pos] = buffer[pos - colors] + rawBytes[i];pos++;@@ -35441,7 +35192,7 @@ var PredictorStream = (function PredictorStreamClosure() {var bitMask = (1 << bits) - 1;var j = 0, k = bufferLength;var columns = this.columns;- for (i = 0; i < columns; ++i) {+ for (var i = 0; i < columns; ++i) {for (var kk = 0; kk < colors; ++kk) {if (inbits < bits) {inbuf = (inbuf << 8) | (rawBytes[j++] & 0xFF);@@ -35460,20 +35211,20 @@ var PredictorStream = (function PredictorStreamClosure() {}if (outbits > 0) {buffer[k++] = (outbuf << (8 - outbits)) +- (inbuf & ((1 << (8 - outbits)) - 1));+ (inbuf & ((1 << (8 - outbits)) - 1));}}this.bufferLength += rowBytes;};PredictorStream.prototype.readBlockPng =- function predictorStreamReadBlockPng() {+ function predictorStreamReadBlockPng() {var rowBytes = this.rowBytes;var pixBytes = this.pixBytes;- var predictor = this.str.getByte();- var rawBytes = this.str.getBytes(rowBytes);+ var predictor = this.stream.getByte();+ var rawBytes = this.stream.getBytes(rowBytes);this.eof = !rawBytes.length;if (this.eof) {return;@@ -35483,35 +35234,30 @@ var PredictorStream = (function PredictorStreamClosure() {var buffer = this.ensureBuffer(bufferLength + rowBytes);var prevRow = buffer.subarray(bufferLength - rowBytes, bufferLength);- if (prevRow.length === 0) {+ if (prevRow.length === 0)prevRow = new Uint8Array(rowBytes);- }- var i, j = bufferLength, up, c;+ var j = bufferLength;switch (predictor) {case 0:- for (i = 0; i < rowBytes; ++i) {+ for (var i = 0; i < rowBytes; ++i)buffer[j++] = rawBytes[i];- }break;case 1:- for (i = 0; i < pixBytes; ++i) {+ for (var i = 0; i < pixBytes; ++i)buffer[j++] = rawBytes[i];- }for (; i < rowBytes; ++i) {buffer[j] = (buffer[j - pixBytes] + rawBytes[i]) & 0xFF;j++;}break;case 2:- for (i = 0; i < rowBytes; ++i) {+ for (var i = 0; i < rowBytes; ++i)buffer[j++] = (prevRow[i] + rawBytes[i]) & 0xFF;- }break;case 3:- for (i = 0; i < pixBytes; ++i) {+ for (var i = 0; i < pixBytes; ++i)buffer[j++] = (prevRow[i] >> 1) + rawBytes[i];- }for (; i < rowBytes; ++i) {buffer[j] = (((prevRow[i] + buffer[j - pixBytes]) >> 1) +rawBytes[i]) & 0xFF;@@ -35521,38 +35267,34 @@ var PredictorStream = (function PredictorStreamClosure() {case 4:// we need to save the up left pixels values. the simplest way// is to create a new buffer- for (i = 0; i < pixBytes; ++i) {- up = prevRow[i];- c = rawBytes[i];+ for (var i = 0; i < pixBytes; ++i) {+ var up = prevRow[i];+ var c = rawBytes[i];buffer[j++] = up + c;}for (; i < rowBytes; ++i) {- up = prevRow[i];+ var up = prevRow[i];var upLeft = prevRow[i - pixBytes];var left = buffer[j - pixBytes];var p = left + up - upLeft;var pa = p - left;- if (pa < 0) {+ if (pa < 0)pa = -pa;- }var pb = p - up;- if (pb < 0) {+ if (pb < 0)pb = -pb;- }var pc = p - upLeft;- if (pc < 0) {+ if (pc < 0)pc = -pc;- }- c = rawBytes[i];- if (pa <= pb && pa <= pc) {+ var c = rawBytes[i];+ if (pa <= pb && pa <= pc)buffer[j++] = left + c;- } else if (pb <= pc) {+ else if (pb <= pc)buffer[j++] = up + c;- } else {+ elsebuffer[j++] = upLeft + c;- }}break;default:@@ -35572,35 +35314,63 @@ var PredictorStream = (function PredictorStreamClosure() {* DecodeStreams.*/var JpegStream = (function JpegStreamClosure() {- function JpegStream(stream, maybeLength, dict, xref) {+ function isAdobeImage(bytes) {+ var maxBytesScanned = Math.max(bytes.length - 16, 1024);+ // Looking for APP14, 'Adobe'+ for (var i = 0; i < maxBytesScanned; ++i) {+ if (bytes[i] == 0xFF && bytes[i + 1] == 0xEE &&+ bytes[i + 2] === 0x00 && bytes[i + 3] == 0x0E &&+ bytes[i + 4] == 0x41 && bytes[i + 5] == 0x64 &&+ bytes[i + 6] == 0x6F && bytes[i + 7] == 0x62 &&+ bytes[i + 8] == 0x65 && bytes[i + 9] === 0x00)+ return true;+ // scanning until frame tag+ if (bytes[i] == 0xFF && bytes[i + 1] == 0xC0)+ break;+ }+ return false;+ }++ function fixAdobeImage(bytes) {+ // Inserting 'EMBED' marker after JPEG signature+ var embedMarker = new Uint8Array([0xFF, 0xEC, 0, 8, 0x45, 0x4D, 0x42, 0x45,+ 0x44, 0]);+ var newBytes = new Uint8Array(bytes.length + embedMarker.length);+ newBytes.set(bytes, embedMarker.length);+ // copy JPEG header+ newBytes[0] = bytes[0];+ newBytes[1] = bytes[1];+ newBytes.set(embedMarker, 2);+ return newBytes;+ }++ function JpegStream(bytes, dict, xref) {// TODO: per poppler, some images may have 'junk' before that// need to be removed- this.stream = stream;- this.maybeLength = maybeLength;this.dict = dict;- DecodeStream.call(this, maybeLength);+ this.isAdobeImage = false;+ this.colorTransform = dict.get('ColorTransform') || -1;++ if (isAdobeImage(bytes)) {+ this.isAdobeImage = true;+ bytes = fixAdobeImage(bytes);+ }++ this.bytes = bytes;++ DecodeStream.call(this);}JpegStream.prototype = Object.create(DecodeStream.prototype);- Object.defineProperty(JpegStream.prototype, 'bytes', {- get: function JpegStream_bytes() {- // If this.maybeLength is null, we'll get the entire stream.- return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));- },- configurable: true- });-JpegStream.prototype.ensureBuffer = function JpegStream_ensureBuffer(req) {- if (this.bufferLength) {+ if (this.bufferLength)return;- }try {var jpegImage = new JpegImage();- if (this.colorTransform != -1) {+ if (this.colorTransform != -1)jpegImage.colorTransform = this.colorTransform;- }jpegImage.parse(this.bytes);var width = jpegImage.width;var height = jpegImage.height;@@ -35613,25 +35383,38 @@ var JpegStream = (function JpegStreamClosure() {}};JpegStream.prototype.getIR = function JpegStream_getIR() {- return PDFJS.createObjectURL(this.bytes, 'image/jpeg');+ return bytesToString(this.bytes);+ };+ JpegStream.prototype.getChar = function JpegStream_getChar() {+ error('internal error: getChar is not valid on JpegStream');};/*** Checks if the image can be decoded and displayed by the browser without any* further processing such as color space conversions.*/JpegStream.prototype.isNativelySupported =- function JpegStream_isNativelySupported(xref, res) {+ function JpegStream_isNativelySupported(xref, res) {var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);- return cs.name === 'DeviceGray' || cs.name === 'DeviceRGB';+ // when bug 674619 lands, let's check if browser can do+ // normal cmyk and then we won't need to decode in JS+ if (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB')+ return true;+ if (cs.name === 'DeviceCMYK' && !this.isAdobeImage &&+ this.colorTransform < 1)+ return true;+ return false;};/*** Checks if the image can be decoded by the browser.*/JpegStream.prototype.isNativelyDecodable =- function JpegStream_isNativelyDecodable(xref, res) {+ function JpegStream_isNativelyDecodable(xref, res) {var cs = ColorSpace.parse(this.dict.get('ColorSpace', 'CS'), xref, res);var numComps = cs.numComps;- return numComps == 1 || numComps == 3;+ if (numComps == 1 || numComps == 3)+ return true;++ return false;};return JpegStream;@@ -35642,28 +35425,18 @@ var JpegStream = (function JpegStreamClosure() {* the stream behaves like all the other DecodeStreams.*/var JpxStream = (function JpxStreamClosure() {- function JpxStream(stream, maybeLength, dict) {- this.stream = stream;- this.maybeLength = maybeLength;+ function JpxStream(bytes, dict) {this.dict = dict;+ this.bytes = bytes;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}JpxStream.prototype = Object.create(DecodeStream.prototype);- Object.defineProperty(JpxStream.prototype, 'bytes', {- get: function JpxStream_bytes() {- // If this.maybeLength is null, we'll get the entire stream.- return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));- },- configurable: true- });-JpxStream.prototype.ensureBuffer = function JpxStream_ensureBuffer(req) {- if (this.bufferLength) {+ if (this.bufferLength)return;- }var jpxImage = new JpxImage();jpxImage.parse(this.bytes);@@ -35671,9 +35444,8 @@ var JpxStream = (function JpxStreamClosure() {var width = jpxImage.width;var height = jpxImage.height;var componentsCount = jpxImage.componentsCount;- if (componentsCount != 1 && componentsCount != 3 && componentsCount != 4) {+ if (componentsCount != 1 && componentsCount != 3 && componentsCount != 4)error('JPX with ' + componentsCount + ' components is not supported');- }var data = new Uint8Array(width * height * componentsCount);@@ -35685,7 +35457,6 @@ var JpxStream = (function JpxStreamClosure() {var tileTop = tileCompoments[0].top;var dataPosition, sourcePosition, data0, data1, data2, data3, rowFeed;- var i, j;switch (componentsCount) {case 1:data0 = tileCompoments[0].items;@@ -35693,10 +35464,9 @@ var JpxStream = (function JpxStreamClosure() {dataPosition = width * tileTop + tileLeft;rowFeed = width - tileWidth;sourcePosition = 0;- for (j = 0; j < tileHeight; j++) {- for (i = 0; i < tileWidth; i++) {+ for (var j = 0; j < tileHeight; j++) {+ for (var i = 0; i < tileWidth; i++)data[dataPosition++] = data0[sourcePosition++];- }dataPosition += rowFeed;}break;@@ -35708,8 +35478,8 @@ var JpxStream = (function JpxStreamClosure() {dataPosition = (width * tileTop + tileLeft) * 3;rowFeed = (width - tileWidth) * 3;sourcePosition = 0;- for (j = 0; j < tileHeight; j++) {- for (i = 0; i < tileWidth; i++) {+ for (var j = 0; j < tileHeight; j++) {+ for (var i = 0; i < tileWidth; i++) {data[dataPosition++] = data0[sourcePosition];data[dataPosition++] = data1[sourcePosition];data[dataPosition++] = data2[sourcePosition];@@ -35727,8 +35497,8 @@ var JpxStream = (function JpxStreamClosure() {dataPosition = (width * tileTop + tileLeft) * 4;rowFeed = (width - tileWidth) * 4;sourcePosition = 0;- for (j = 0; j < tileHeight; j++) {- for (i = 0; i < tileWidth; i++) {+ for (var j = 0; j < tileHeight; j++) {+ for (var i = 0; i < tileWidth; i++) {data[dataPosition++] = data0[sourcePosition];data[dataPosition++] = data1[sourcePosition];data[dataPosition++] = data2[sourcePosition];@@ -35745,6 +35515,9 @@ var JpxStream = (function JpxStreamClosure() {this.bufferLength = data.length;this.eof = true;};+ JpxStream.prototype.getChar = function JpxStream_getChar() {+ error('internal error: getChar is not valid on JpxStream');+ };return JpxStream;})();@@ -35754,42 +35527,22 @@ var JpxStream = (function JpxStreamClosure() {* the stream behaves like all the other DecodeStreams.*/var Jbig2Stream = (function Jbig2StreamClosure() {- function Jbig2Stream(stream, maybeLength, dict) {- this.stream = stream;- this.maybeLength = maybeLength;+ function Jbig2Stream(bytes, dict) {this.dict = dict;+ this.bytes = bytes;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}Jbig2Stream.prototype = Object.create(DecodeStream.prototype);- Object.defineProperty(Jbig2Stream.prototype, 'bytes', {- get: function Jbig2Stream_bytes() {- // If this.maybeLength is null, we'll get the entire stream.- return shadow(this, 'bytes', this.stream.getBytes(this.maybeLength));- },- configurable: true- });-Jbig2Stream.prototype.ensureBuffer = function Jbig2Stream_ensureBuffer(req) {- if (this.bufferLength) {+ if (this.bufferLength)return;- }var jbig2Image = new Jbig2Image();var chunks = [], decodeParams = this.dict.get('DecodeParms');-- // According to the PDF specification, DecodeParms can be either- // a dictionary, or an array whose elements are dictionaries.- if (isArray(decodeParams)) {- if (decodeParams.length > 1) {- warn('JBIG2 - \'DecodeParms\' array with multiple elements ' +- 'not supported.');- }- decodeParams = decodeParams[0];- }if (decodeParams && decodeParams.has('JBIG2Globals')) {var globalsStream = decodeParams.get('JBIG2Globals');var globals = globalsStream.getBytes();@@ -35800,27 +35553,29 @@ var Jbig2Stream = (function Jbig2StreamClosure() {var dataLength = data.length;// JBIG2 had black as 1 and white as 0, inverting the colors- for (var i = 0; i < dataLength; i++) {+ for (var i = 0; i < dataLength; i++)data[i] ^= 0xFF;- }this.buffer = data;this.bufferLength = dataLength;this.eof = true;};+ Jbig2Stream.prototype.getChar = function Jbig2Stream_getChar() {+ error('internal error: getChar is not valid on Jbig2Stream');+ };return Jbig2Stream;})();var DecryptStream = (function DecryptStreamClosure() {- function DecryptStream(str, maybeLength, decrypt) {+ function DecryptStream(str, decrypt) {this.str = str;this.dict = str.dict;this.decrypt = decrypt;this.nextChunk = null;this.initialized = false;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}var chunkSize = 512;@@ -35848,9 +35603,8 @@ var DecryptStream = (function DecryptStreamClosure() {var bufferLength = this.bufferLength;var i, n = chunk.length;var buffer = this.ensureBuffer(bufferLength + n);- for (i = 0; i < n; i++) {+ for (i = 0; i < n; i++)buffer[bufferLength++] = chunk[i];- }this.bufferLength = bufferLength;};@@ -35858,79 +35612,65 @@ var DecryptStream = (function DecryptStreamClosure() {})();var Ascii85Stream = (function Ascii85StreamClosure() {- function Ascii85Stream(str, maybeLength) {+ function Ascii85Stream(str) {this.str = str;this.dict = str.dict;this.input = new Uint8Array(5);- // Most streams increase in size when decoded, but Ascii85 streams- // typically shrink by ~20%.- if (maybeLength) {- maybeLength = 0.8 * maybeLength;- }- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}Ascii85Stream.prototype = Object.create(DecodeStream.prototype);Ascii85Stream.prototype.readBlock = function Ascii85Stream_readBlock() {- var TILDA_CHAR = 0x7E; // '~'- var Z_LOWER_CHAR = 0x7A; // 'z'- var EOF = -1;-+ var tildaCode = '~'.charCodeAt(0);+ var zCode = 'z'.charCodeAt(0);var str = this.str;var c = str.getByte();- while (Lexer.isSpace(c)) {+ while (Lexer.isSpace(String.fromCharCode(c)))c = str.getByte();- }- if (c === EOF || c === TILDA_CHAR) {+ if (!c || c === tildaCode) {this.eof = true;return;}var bufferLength = this.bufferLength, buffer;- var i;// special code for z- if (c == Z_LOWER_CHAR) {+ if (c == zCode) {buffer = this.ensureBuffer(bufferLength + 4);- for (i = 0; i < 4; ++i) {+ for (var i = 0; i < 4; ++i)buffer[bufferLength + i] = 0;- }this.bufferLength += 4;} else {var input = this.input;input[0] = c;- for (i = 1; i < 5; ++i) {+ for (var i = 1; i < 5; ++i) {c = str.getByte();- while (Lexer.isSpace(c)) {+ while (Lexer.isSpace(String.fromCharCode(c)))c = str.getByte();- }input[i] = c;- if (c === EOF || c == TILDA_CHAR) {+ if (!c || c == tildaCode)break;- }}buffer = this.ensureBuffer(bufferLength + i - 1);this.bufferLength += i - 1;// partial ending;if (i < 5) {- for (; i < 5; ++i) {+ for (; i < 5; ++i)input[i] = 0x21 + 84;- }this.eof = true;}var t = 0;- for (i = 0; i < 5; ++i) {+ for (var i = 0; i < 5; ++i)t = t * 85 + (input[i] - 0x21);- }- for (i = 3; i >= 0; --i) {+ for (var i = 3; i >= 0; --i) {buffer[bufferLength + i] = t & 0xFF;t >>= 8;}@@ -35941,73 +35681,81 @@ var Ascii85Stream = (function Ascii85StreamClosure() {})();var AsciiHexStream = (function AsciiHexStreamClosure() {- function AsciiHexStream(str, maybeLength) {+ function AsciiHexStream(str) {this.str = str;this.dict = str.dict;- this.firstDigit = -1;-- // Most streams increase in size when decoded, but AsciiHex streams shrink- // by 50%.- if (maybeLength) {- maybeLength = 0.5 * maybeLength;- }- DecodeStream.call(this, maybeLength);- }+ DecodeStream.call(this);+ }++ var hexvalueMap = {+ 9: -1, // \t+ 32: -1, // space+ 48: 0,+ 49: 1,+ 50: 2,+ 51: 3,+ 52: 4,+ 53: 5,+ 54: 6,+ 55: 7,+ 56: 8,+ 57: 9,+ 65: 10,+ 66: 11,+ 67: 12,+ 68: 13,+ 69: 14,+ 70: 15,+ 97: 10,+ 98: 11,+ 99: 12,+ 100: 13,+ 101: 14,+ 102: 15+ };AsciiHexStream.prototype = Object.create(DecodeStream.prototype);AsciiHexStream.prototype.readBlock = function AsciiHexStream_readBlock() {- var UPSTREAM_BLOCK_SIZE = 8000;- var bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);- if (!bytes.length) {- this.eof = true;- return;- }+ var gtCode = '>'.charCodeAt(0), bytes = this.str.getBytes(), c, n,+ decodeLength, buffer, bufferLength, i, length;- var maxDecodeLength = (bytes.length + 1) >> 1;- var buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);- var bufferLength = this.bufferLength;+ decodeLength = (bytes.length + 1) >> 1;+ buffer = this.ensureBuffer(this.bufferLength + decodeLength);+ bufferLength = this.bufferLength;- var firstDigit = this.firstDigit;- for (var i = 0, ii = bytes.length; i < ii; i++) {- var ch = bytes[i], digit;- if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'- digit = ch & 0x0F;- } else if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {- // 'A'-'Z', 'a'-'z'- digit = (ch & 0x0F) + 9;- } else if (ch === 0x3E) { // '>'- this.eof = true;- break;- } else { // probably whitespace- continue; // ignoring+ for (i = 0, length = bytes.length; i < length; i++) {+ c = hexvalueMap[bytes[i]];+ while (c == -1 && (i + 1) < length) {+ c = hexvalueMap[bytes[++i]];}- if (firstDigit < 0) {- firstDigit = digit;++ if ((i + 1) < length && (bytes[i + 1] !== gtCode)) {+ n = hexvalueMap[bytes[++i]];+ buffer[bufferLength++] = c * 16 + n;} else {- buffer[bufferLength++] = (firstDigit << 4) | digit;- firstDigit = -1;+ // EOD marker at an odd number, behave as if a 0 followed the last+ // digit.+ if (bytes[i] !== gtCode) {+ buffer[bufferLength++] = c * 16;+ }}}- if (firstDigit >= 0 && this.eof) {- // incomplete byte- buffer[bufferLength++] = (firstDigit << 4);- firstDigit = -1;- }- this.firstDigit = firstDigit;+this.bufferLength = bufferLength;+ this.eof = true;};return AsciiHexStream;})();var RunLengthStream = (function RunLengthStreamClosure() {- function RunLengthStream(str, maybeLength) {+ function RunLengthStream(str) {this.str = str;this.dict = str.dict;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}RunLengthStream.prototype = Object.create(DecodeStream.prototype);@@ -36023,12 +35771,11 @@ var RunLengthStream = (function RunLengthStreamClosure() {return;}- var buffer;var bufferLength = this.bufferLength;var n = repeatHeader[0];if (n < 128) {// copy n bytes- buffer = this.ensureBuffer(bufferLength + n + 1);+ var buffer = this.ensureBuffer(bufferLength + n + 1);buffer[bufferLength++] = repeatHeader[1];if (n > 0) {var source = this.str.getBytes(n);@@ -36038,10 +35785,9 @@ var RunLengthStream = (function RunLengthStreamClosure() {} else {n = 257 - n;var b = repeatHeader[1];- buffer = this.ensureBuffer(bufferLength + n + 1);- for (var i = 0; i < n; i++) {+ var buffer = this.ensureBuffer(bufferLength + n + 1);+ for (var i = 0; i < n; i++)buffer[bufferLength++] = b;- }}this.bufferLength = bufferLength;};@@ -36477,11 +36223,11 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {[2, 2], [2, 2], [2, 2], [2, 2]];- function CCITTFaxStream(str, maybeLength, params) {+ function CCITTFaxStream(str, params) {this.str = str;this.dict = str.dict;- params = params || Dict.empty;+ params = params || new Dict();this.encoding = params.get('K') || 0;this.eoline = params.get('EndOfLine') || false;@@ -36489,9 +36235,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.columns = params.get('Columns') || 1728;this.rows = params.get('Rows') || 0;var eoblock = params.get('EndOfBlock');- if (eoblock === null || eoblock === undefined) {+ if (eoblock === null || eoblock === undefined)eoblock = true;- }this.eoblock = eoblock;this.black = params.get('BlackIs1') || false;@@ -36506,6 +36251,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.inputBits = 0;this.inputBuf = 0;this.outputBits = 0;+ this.buf = EOF;var code1;while ((code1 = this.lookBits(12)) === 0) {@@ -36519,7 +36265,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.eatBits(1);}- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}CCITTFaxStream.prototype = Object.create(DecodeStream.prototype);@@ -36527,13 +36273,14 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {CCITTFaxStream.prototype.readBlock = function CCITTFaxStream_readBlock() {while (!this.eof) {var c = this.lookChar();+ this.buf = EOF;this.ensureBuffer(this.bufferLength + 1);this.buffer[this.bufferLength++] = c;}};CCITTFaxStream.prototype.addPixels =- function ccittFaxStreamAddPixels(a1, blackPixels) {+ function ccittFaxStreamAddPixels(a1, blackPixels) {var codingLine = this.codingLine;var codingPos = this.codingPos;@@ -36553,7 +36300,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {};CCITTFaxStream.prototype.addPixelsNeg =- function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {+ function ccittFaxStreamAddPixelsNeg(a1, blackPixels) {var codingLine = this.codingLine;var codingPos = this.codingPos;@@ -36563,9 +36310,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.err = true;a1 = this.columns;}- if ((codingPos & 1) ^ blackPixels) {+ if ((codingPos & 1) ^ blackPixels)++codingPos;- }codingLine[codingPos] = a1;} else if (a1 < codingLine[codingPos]) {@@ -36574,9 +36320,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.err = true;a1 = 0;}- while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {+ while (codingPos > 0 && a1 < codingLine[codingPos - 1])--codingPos;- }codingLine[codingPos] = a1;}@@ -36584,23 +36329,26 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {};CCITTFaxStream.prototype.lookChar = function CCITTFaxStream_lookChar() {+ if (this.buf != EOF)+ return this.buf;+var refLine = this.refLine;var codingLine = this.codingLine;var columns = this.columns;- var refPos, blackPixels, bits, i;+ var refPos, blackPixels, bits;if (this.outputBits === 0) {- if (this.eof) {+ if (this.eof)return null;- }+this.err = false;var code1, code2, code3;if (this.nextLine2D) {- for (i = 0; codingLine[i] < columns; ++i) {+ for (var i = 0; codingLine[i] < columns; ++i)refLine[i] = codingLine[i];- }+refLine[i++] = columns;refLine[i] = columns;codingLine[0] = 0;@@ -36613,9 +36361,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {switch (code1) {case twoDimPass:this.addPixels(refLine[refPos + 1], blackPixels);- if (refLine[refPos + 1] < columns) {+ if (refLine[refPos + 1] < columns)refPos += 2;- }break;case twoDimHoriz:code1 = code2 = 0;@@ -36651,9 +36398,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {if (codingLine[this.codingPos] < columns) {++refPos;while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case twoDimVertR2:@@ -36673,9 +36419,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {if (codingLine[this.codingPos] < columns) {++refPos;while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case twoDimVert0:@@ -36684,54 +36429,48 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {if (codingLine[this.codingPos] < columns) {++refPos;while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case twoDimVertL3:this.addPixelsNeg(refLine[refPos] - 3, blackPixels);blackPixels ^= 1;if (codingLine[this.codingPos] < columns) {- if (refPos > 0) {+ if (refPos > 0)--refPos;- } else {+ else++refPos;- }while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case twoDimVertL2:this.addPixelsNeg(refLine[refPos] - 2, blackPixels);blackPixels ^= 1;if (codingLine[this.codingPos] < columns) {- if (refPos > 0) {+ if (refPos > 0)--refPos;- } else {+ else++refPos;- }while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case twoDimVertL1:this.addPixelsNeg(refLine[refPos] - 1, blackPixels);blackPixels ^= 1;if (codingLine[this.codingPos] < columns) {- if (refPos > 0) {+ if (refPos > 0)--refPos;- } else {+ else++refPos;- }+while (refLine[refPos] <= codingLine[this.codingPos] &&- refLine[refPos] < columns) {+ refLine[refPos] < columns)refPos += 2;- }}break;case EOF:@@ -36764,9 +36503,8 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}}- if (this.byteAlign) {+ if (this.byteAlign)this.inputBits &= ~7;- }var gotEOL = false;@@ -36800,11 +36538,10 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.eatBits(1);}if (this.encoding >= 0) {- for (i = 0; i < 4; ++i) {+ for (var i = 0; i < 4; ++i) {code1 = this.lookBits(12);- if (code1 != 1) {+ if (code1 != 1)info('bad rtc code: ' + code1);- }this.eatBits(12);if (this.encoding > 0) {this.lookBits(1);@@ -36833,17 +36570,15 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}}- if (codingLine[0] > 0) {+ if (codingLine[0] > 0)this.outputBits = codingLine[this.codingPos = 0];- } else {+ elsethis.outputBits = codingLine[this.codingPos = 1];- }this.row++;}- var c;if (this.outputBits >= 8) {- c = (this.codingPos & 1) ? 0 : 0xFF;+ this.buf = (this.codingPos & 1) ? 0 : 0xFF;this.outputBits -= 8;if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {this.codingPos++;@@ -36851,20 +36586,20 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {codingLine[this.codingPos - 1]);}} else {- bits = 8;- c = 0;+ var bits = 8;+ this.buf = 0;do {if (this.outputBits > bits) {- c <<= bits;+ this.buf <<= bits;if (!(this.codingPos & 1)) {- c |= 0xFF >> (8 - bits);+ this.buf |= 0xFF >> (8 - bits);}this.outputBits -= bits;bits = 0;} else {- c <<= this.outputBits;+ this.buf <<= this.outputBits;if (!(this.codingPos & 1)) {- c |= 0xFF >> (8 - this.outputBits);+ this.buf |= 0xFF >> (8 - this.outputBits);}bits -= this.outputBits;this.outputBits = 0;@@ -36873,16 +36608,16 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {this.outputBits = (codingLine[this.codingPos] -codingLine[this.codingPos - 1]);} else if (bits > 0) {- c <<= bits;+ this.buf <<= bits;bits = 0;}}} while (bits);}if (this.black) {- c ^= 0xFF;+ this.buf ^= 0xFF;}- return c;+ return this.buf;};// This functions returns the code found from the table.@@ -36892,17 +36627,15 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {// returned. The second array element is the actual code. The third array// element indicates whether EOF was reached.CCITTFaxStream.prototype.findTableCode =- function ccittFaxStreamFindTableCode(start, end, table, limit) {+ function ccittFaxStreamFindTableCode(start, end, table, limit) {var limitValue = limit || 0;for (var i = start; i <= end; ++i) {var code = this.lookBits(i);- if (code == EOF) {+ if (code == EOF)return [true, 1, false];- }- if (i < end) {+ if (i < end)code <<= end - i;- }if (!limitValue || code >= limitValue) {var p = table[code - limitValue];if (p[0] == i) {@@ -36915,7 +36648,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {};CCITTFaxStream.prototype.getTwoDimCode =- function ccittFaxStreamGetTwoDimCode() {+ function ccittFaxStreamGetTwoDimCode() {var code = 0;var p;@@ -36928,31 +36661,28 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}} else {var result = this.findTableCode(1, 7, twoDimTable);- if (result[0] && result[2]) {+ if (result[0] && result[2])return result[1];- }}info('Bad two dim code');return EOF;};CCITTFaxStream.prototype.getWhiteCode =- function ccittFaxStreamGetWhiteCode() {+ function ccittFaxStreamGetWhiteCode() {var code = 0;var p;var n;if (this.eoblock) {code = this.lookBits(12);- if (code == EOF) {+ if (code == EOF)return 1;- }- if ((code >> 5) === 0) {+ if ((code >> 5) === 0)p = whiteTable1[code];- } else {+ elsep = whiteTable2[code >> 3];- }if (p[0] > 0) {this.eatBits(p[0]);@@ -36960,14 +36690,12 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}} else {var result = this.findTableCode(1, 9, whiteTable2);- if (result[0]) {+ if (result[0])return result[1];- }result = this.findTableCode(11, 12, whiteTable1);- if (result[0]) {+ if (result[0])return result[1];- }}info('bad white code');this.eatBits(1);@@ -36975,21 +36703,19 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {};CCITTFaxStream.prototype.getBlackCode =- function ccittFaxStreamGetBlackCode() {+ function ccittFaxStreamGetBlackCode() {var code, p;if (this.eoblock) {code = this.lookBits(13);- if (code == EOF) {+ if (code == EOF)return 1;- }- if ((code >> 7) === 0) {+ if ((code >> 7) === 0)p = blackTable1[code];- } else if ((code >> 9) === 0 && (code >> 7) !== 0) {+ else if ((code >> 9) === 0 && (code >> 7) !== 0)p = blackTable2[(code >> 1) - 64];- } else {+ elsep = blackTable3[code >> 7];- }if (p[0] > 0) {this.eatBits(p[0]);@@ -36997,19 +36723,16 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {}} else {var result = this.findTableCode(2, 6, blackTable3);- if (result[0]) {+ if (result[0])return result[1];- }result = this.findTableCode(7, 12, blackTable2, 64);- if (result[0]) {+ if (result[0])return result[1];- }result = this.findTableCode(10, 13, blackTable1);- if (result[0]) {+ if (result[0])return result[1];- }}info('bad black code');this.eatBits(1);@@ -37019,10 +36742,9 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {var c;while (this.inputBits < n) {- if ((c = this.str.getByte()) === -1) {- if (this.inputBits === 0) {+ if ((c = this.str.getByte()) === null || c === undefined) {+ if (this.inputBits === 0)return EOF;- }return ((this.inputBuf << (n - this.inputBits)) &(0xFFFF >> (16 - n)));}@@ -37033,16 +36755,15 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() {};CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {- if ((this.inputBits -= n) < 0) {+ if ((this.inputBits -= n) < 0)this.inputBits = 0;- }};return CCITTFaxStream;})();var LZWStream = (function LZWStreamClosure() {- function LZWStream(str, maybeLength, earlyChange) {+ function LZWStream(str, earlyChange) {this.str = str;this.dict = str.dict;this.cachedData = 0;@@ -37065,7 +36786,7 @@ var LZWStream = (function LZWStreamClosure() {}this.lzwState = lzwState;- DecodeStream.call(this, maybeLength);+ DecodeStream.call(this);}LZWStream.prototype = Object.create(DecodeStream.prototype);@@ -37075,7 +36796,7 @@ var LZWStream = (function LZWStreamClosure() {var cachedData = this.cachedData;while (bitsCached < n) {var c = this.str.getByte();- if (c === -1) {+ if (c === null || c === undefined) {this.eof = true;return null;}@@ -37094,9 +36815,8 @@ var LZWStream = (function LZWStreamClosure() {var i, j, q;var lzwState = this.lzwState;- if (!lzwState) {+ if (!lzwState)return; // eof was found- }var earlyChange = lzwState.earlyChange;var nextCode = lzwState.nextCode;@@ -37157,9 +36877,8 @@ var LZWStream = (function LZWStreamClosure() {} while (estimatedDecodedSize < decodedLength);buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);}- for (j = 0; j < currentSequenceLength; j++) {+ for (j = 0; j < currentSequenceLength; j++)buffer[currentBufferLength++] = currentSequence[j];- }}lzwState.nextCode = nextCode;lzwState.codeLength = codeLength;@@ -37183,24 +36902,110 @@ var NullStream = (function NullStreamClosure() {})();-var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {+function MessageHandler(name, comObj) {+ this.name = name;+ this.comObj = comObj;+ this.callbackIndex = 1;+ var callbacks = this.callbacks = {};+ var ah = this.actionHandler = {};++ ah['console_log'] = [function ahConsoleLog(data) {+ log.apply(null, data);+ }];+ // If there's no console available, console_error in the+ // action handler will do nothing.+ if ('console' in globalScope) {+ ah['console_error'] = [function ahConsoleError(data) {+ globalScope['console'].error.apply(null, data);+ }];+ } else {+ ah['console_error'] = [function ahConsoleError(data) {+ log.apply(null, 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 {+ error('Cannot resolve callback ' + callbackId);+ }+ } else if (data.action in ah) {+ var action = ah[data.action];+ 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 {+ error('Unkown action from worker: ' + data.action);+ }+ };+}++MessageHandler.prototype = {+ on: function messageHandlerOn(actionName, handler, scope) {+ var ah = this.actionHandler;+ if (ah[actionName]) {+ 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 = {setup: function wphSetup(handler) {var pdfManager;function loadDocument(recoveryMode) {- var loadDocumentPromise = new LegacyPromise();+ var loadDocumentPromise = new Promise();var parseSuccess = function parseSuccess() {- var numPagesPromise = pdfManager.ensureDoc('numPages');- var fingerprintPromise = pdfManager.ensureDoc('fingerprint');+ var numPagesPromise = pdfManager.ensureModel('numPages');+ var fingerprintPromise = pdfManager.ensureModel('fingerprint');var outlinePromise = pdfManager.ensureCatalog('documentOutline');- var infoPromise = pdfManager.ensureDoc('documentInfo');+ var infoPromise = pdfManager.ensureModel('documentInfo');var metadataPromise = pdfManager.ensureCatalog('metadata');var encryptedPromise = pdfManager.ensureXRef('encrypt');var javaScriptPromise = pdfManager.ensureCatalog('javaScript');Promise.all([numPagesPromise, fingerprintPromise, outlinePromise,- infoPromise, metadataPromise, encryptedPromise,- javaScriptPromise]).then(function onDocReady(results) {+ infoPromise, metadataPromise, encryptedPromise,+ javaScriptPromise]).then(+ function onDocReady(results) {var doc = {numPages: results[0],@@ -37220,10 +37025,10 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {loadDocumentPromise.reject(e);};- pdfManager.ensureDoc('checkHeader', []).then(function() {- pdfManager.ensureDoc('parseStartXRef', []).then(function() {- pdfManager.ensureDoc('parse', [recoveryMode]).then(- parseSuccess, parseFailure);+ pdfManager.ensureModel('checkHeader', []).then(function() {+ pdfManager.ensureModel('parseStartXRef', []).then(function() {+ pdfManager.ensureModel('parse', [recoveryMode]).then(+ parseSuccess, parseFailure);}, parseFailure);}, parseFailure);@@ -37231,7 +37036,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {}function getPdfManager(data) {- var pdfManagerPromise = new LegacyPromise();+ var pdfManagerPromise = new Promise();var source = data.source;var disableRange = data.disableRange;@@ -37254,8 +37059,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {}var networkManager = new NetworkManager(source.url, {- httpHeaders: source.httpHeaders,- withCredentials: source.withCredentials+ httpHeaders: source.httpHeaders});var fullRequestXhrId = networkManager.requestFull({onHeadersReceived: function onHeadersReceived() {@@ -37279,13 +37083,6 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {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;- }// NOTE: by cancelling the full request, and then issuing range// requests, there will be an issue for sites where you can only@@ -37293,6 +37090,7 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {// server should not be returning that it can support range requests.networkManager.abortRequest(fullRequestXhrId);+ source.length = length;try {pdfManager = new NetworkPdfManager(source, handler);pdfManagerPromise.resolve(pdfManager);@@ -37313,20 +37111,20 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {onError: function onError(status) {if (status == 404) {- var exception = new MissingPDFException('Missing PDF "' +- source.url + '".');+ 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 + '".');+ status + ') while retrieving PDF "' ++ source.url + '".');}},onProgress: function onProgress(evt) {handler.send('DocProgress', {loaded: evt.loaded,- total: evt.lengthComputable ? evt.total : source.length+ total: evt.lengthComputable ? evt.total : void(0)});}});@@ -37340,9 +37138,6 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {handler.send('test', false);return;}- // making sure postMessage transfers are working- var supportTransfers = data[0] === 255;- handler.postMessageTransfers = supportTransfers;// check if the response property is supported by xhrvar xhr = new XMLHttpRequest();var responseExists = 'response' in xhr;@@ -37356,16 +37151,14 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {handler.send('test', false);return;}- handler.send('test', {- supportTypedArray: true,- supportTransfers: supportTransfers- });+ handler.send('test', true);});handler.on('GetDocRequest', function wphSetupDoc(data) {var onSuccess = function(doc) {handler.send('GetDoc', { pdfInfo: doc });+ pdfManager.ensureModel('traversePages', []).then(null, onFailure);};var onFailure = function(e) {@@ -37394,27 +37187,14 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {}};- PDFJS.maxImageSize = data.maxImageSize === undefined ?- -1 : data.maxImageSize;- PDFJS.disableFontFace = data.disableFontFace;- PDFJS.disableCreateObjectURL = data.disableCreateObjectURL;- PDFJS.verbosity = data.verbosity;- PDFJS.cMapUrl = data.cMapUrl === undefined ?- null : data.cMapUrl;- PDFJS.cMapPacked = data.cMapPacked === true;-- getPdfManager(data).then(function () {- pdfManager.onLoadedStream().then(function(stream) {- handler.send('DataLoaded', { length: stream.bytes.byteLength });- });- }).then(function pdfManagerReady() {+ getPdfManager(data).then(function pdfManagerReady() {loadDocument(false).then(onSuccess, function loadFailure(ex) {// Try again with recoveryMode == trueif (!(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 = new Promise();pdfManager.passwordChangedPromise.then(pdfManagerReady);}@@ -37451,26 +37231,24 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {});});- handler.on('GetPageIndex', function wphSetupGetPageIndex(data, deferred) {- var ref = new Ref(data.ref.num, data.ref.gen);- var catalog = pdfManager.pdfDocument.catalog;- catalog.getPageIndex(ref).then(function (pageIndex) {- deferred.resolve(pageIndex);- }, deferred.reject);- });-handler.on('GetDestinations',- function wphSetupGetDestinations(data, deferred) {+ function wphSetupGetDestinations(data, promise) {pdfManager.ensureCatalog('destinations').then(function(destinations) {- deferred.resolve(destinations);+ promise.resolve(destinations);});});- handler.on('GetData', function wphSetupGetData(data, deferred) {+ handler.on('GetData', function wphSetupGetData(data, promise) {pdfManager.requestLoadedStream();pdfManager.onLoadedStream().then(function(stream) {- deferred.resolve(stream.bytes);+ promise.resolve(stream.bytes);+ });+ });++ handler.on('DataLoaded', function wphSetupDataLoaded(data, promise) {+ pdfManager.onLoadedStream().then(function(stream) {+ promise.resolve({ length: stream.bytes.byteLength });});});@@ -37497,15 +37275,35 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {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) {+ page.getOperatorList(handler).then(function(opListData) {++ var operatorList = opListData.queue;+ var dependency = Object.keys(opListData.dependencies);++ // 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.- info('page=' + pageNum + ' - getOperatorList: time=' +- (Date.now() - start) + 'ms, len=' + operatorList.fnArray.length);+ log('page=%d - getOperatorList: time=%dms, len=%d', pageNum,+ Date.now() - start, operatorList.fnArray.length);+ // Filter the dependecies for fonts.+ var fonts = {};+ for (var i = 0, ii = dependency.length; i < ii; i++) {+ var dep = dependency[i];+ if (dep.indexOf('g_font_') === 0) {+ fonts[dep] = true;+ }+ }+ handler.send('RenderPage', {+ pageIndex: data.pageIndex,+ operatorList: operatorList,+ depFonts: Object.keys(fonts)+ });}, function(e) {var minimumStackMessage =- 'worker.js: while trying to getPage() and getOperatorList()';+ 'worker.js: while trying to getPage() and getOperatorList()';var wrappedException;@@ -37529,36 +37327,30 @@ var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {handler.send('PageError', {pageNum: pageNum,- error: wrappedException,- intent: data.intent+ error: wrappedException});});});}, this);- handler.on('GetTextContent', function wphExtractText(data, deferred) {+ handler.on('GetTextContent', function wphExtractText(data, promise) {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');+ promise.resolve(textContent);+ log('text indexing: page=%d - time=%dms', pageNum,+ Date.now() - start);}, function (e) {// Skip errored pages- deferred.reject(e);+ promise.reject(e);});});});- handler.on('Cleanup', function wphCleanup(data, deferred) {- pdfManager.cleanup();- deferred.resolve(true);- });-- handler.on('Terminate', function wphTerminate(data, deferred) {- pdfManager.terminate();- deferred.resolve();+ handler.on('Terminate', function wphTerminate(data, promise) {+ pdfManager.streamManager.networkManager.abortAllRequests();+ promise.resolve();});}};@@ -37590,25 +37382,25 @@ var workerConsole = {timeEnd: function timeEnd(name) {var time = consoleTimer[name];if (!time) {- error('Unknown timer name ' + name);+ error('Unkown timer name ' + name);}this.log('Timer:', name, Date.now() - time);}};-// Worker thread?if (typeof window === 'undefined') {- if (!('console' in globalScope)) {- globalScope.console = workerConsole;- }-- // 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- });+ globalScope.console = workerConsole;++ // 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) {+ globalScope.postMessage({+ action: '_warn',+ data: msg+ });+ }});var handler = new MessageHandler('worker_processor', this);@@ -37616,174 +37408,6 @@ if (typeof window === 'undefined') {}-/* This class implements the QM Coder decoding as defined in- * JPEG 2000 Part I Final Committee Draft Version 1.0- * Annex C.3 Arithmetic decoding procedure- * available at http://www.jpeg.org/public/fcd15444-1.pdf- *- * The arithmetic decoder is used in conjunction with context models to decode- * JPEG2000 and JBIG2 streams.- */-var ArithmeticDecoder = (function ArithmeticDecoderClosure() {- // Table C-2- var QeTable = [- {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},- {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},- {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},- {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},- {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},- {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},- {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},- {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},- {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},- {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},- {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},- {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},- {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},- {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},- {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},- {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},- {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},- {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},- {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},- {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},- {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},- {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},- {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},- {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},- {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},- {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},- {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},- {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},- {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},- {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},- {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},- {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},- {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},- {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},- {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},- {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},- {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},- {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},- {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},- {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},- {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},- {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},- {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},- {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},- {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},- {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},- {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}- ];-- // C.3.5 Initialisation of the decoder (INITDEC)- function ArithmeticDecoder(data, start, end) {- this.data = data;- this.bp = start;- this.dataEnd = end;-- this.chigh = data[start];- this.clow = 0;-- this.byteIn();-- this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);- this.clow = (this.clow << 7) & 0xFFFF;- this.ct -= 7;- this.a = 0x8000;- }-- ArithmeticDecoder.prototype = {- // C.3.4 Compressed data input (BYTEIN)- byteIn: function ArithmeticDecoder_byteIn() {- var data = this.data;- var bp = this.bp;- if (data[bp] == 0xFF) {- var b1 = data[bp + 1];- if (b1 > 0x8F) {- this.clow += 0xFF00;- this.ct = 8;- } else {- bp++;- this.clow += (data[bp] << 9);- this.ct = 7;- this.bp = bp;- }- } else {- bp++;- this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;- this.ct = 8;- this.bp = bp;- }- if (this.clow > 0xFFFF) {- this.chigh += (this.clow >> 16);- this.clow &= 0xFFFF;- }- },- // C.3.2 Decoding a decision (DECODE)- readBit: function ArithmeticDecoder_readBit(contexts, pos) {- // contexts are packed into 1 byte:- // highest 7 bits carry cx.index, lowest bit carries cx.mps- var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;- var qeTableIcx = QeTable[cx_index];- var qeIcx = qeTableIcx.qe;- var d;- var a = this.a - qeIcx;-- if (this.chigh < qeIcx) {- // exchangeLps- if (a < qeIcx) {- a = qeIcx;- d = cx_mps;- cx_index = qeTableIcx.nmps;- } else {- a = qeIcx;- d = 1 ^ cx_mps;- if (qeTableIcx.switchFlag === 1) {- cx_mps = d;- }- cx_index = qeTableIcx.nlps;- }- } else {- this.chigh -= qeIcx;- if ((a & 0x8000) !== 0) {- this.a = a;- return cx_mps;- }- // exchangeMps- if (a < qeIcx) {- d = 1 ^ cx_mps;- if (qeTableIcx.switchFlag === 1) {- cx_mps = d;- }- cx_index = qeTableIcx.nlps;- } else {- d = cx_mps;- cx_index = qeTableIcx.nmps;- }- }- // C.3.3 renormD;- do {- if (this.ct === 0) {- this.byteIn();- }-- a <<= 1;- this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);- this.clow = (this.clow << 1) & 0xFFFF;- this.ct--;- } while ((a & 0x8000) === 0);- this.a = a;-- contexts[pos] = cx_index << 1 | cx_mps;- return d;- }- };-- return ArithmeticDecoder;-})();--var JpxImage = (function JpxImageClosure() {// Table E.1var SubbandsGainLog2 = {@@ -37804,28 +37428,18 @@ var JpxImage = (function JpxImageClosure() {// TODO catch parse errorvar data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);this.parse(data);- if (this.onload) {+ if (this.onload)this.onload();- }}).bind(this);xhr.send(null);},parse: function JpxImage_parse(data) {function readUint(data, offset, bytes) {var n = 0;- for (var i = 0; i < bytes; i++) {+ for (var i = 0; i < bytes; i++)n = n * 256 + (data[offset + i] & 0xFF);- }return n;}-- var head = readUint(data, 0, 2);- // No box header, immediate start of codestream (SOC)- if (head === 0xFF4F) {- this.parseCodestream(data, 0, data.length);- return;- }-var position = 0, length = data.length;while (position < length) {var headerSize = 8;@@ -37837,12 +37451,10 @@ var JpxImage = (function JpxImageClosure() {position += 8;headerSize += 8;}- if (lbox === 0) {+ if (lbox === 0)lbox = length - position + headerSize;- }- if (lbox < headerSize) {+ if (lbox < headerSize)error('JPX error: Invalid box field size');- }var dataLength = lbox - headerSize;var jumpDataLength = true;switch (tbox) {@@ -37859,42 +37471,8 @@ var JpxImage = (function JpxImageClosure() {this.parseCodestream(data, position, position + dataLength);break;}- if (jumpDataLength) {+ if (jumpDataLength)position += dataLength;- }- }- },- parseImageProperties: function JpxImage_parseImageProperties(stream) {- try {- var newByte = stream.getByte();- while (newByte >= 0) {- var oldByte = newByte;- newByte = stream.getByte();- var code = (oldByte << 8) | newByte;- // Image and tile size (SIZ)- if (code == 0xFF51) {- stream.skip(4);- var Xsiz = stream.getUint32(); // Byte 4- var Ysiz = stream.getUint32(); // Byte 8- var XOsiz = stream.getUint32(); // Byte 12- var YOsiz = stream.getUint32(); // Byte 16- stream.skip(16);- var Csiz = stream.getUint16(); // Byte 36- this.width = Xsiz - XOsiz;- this.height = Ysiz - YOsiz;- this.componentsCount = Csiz;- // Results are always returned as UInt8Arrays- this.bitsPerComponent = 8;- return;- }- }- throw 'No size marker found in JPX stream';- } catch (e) {- if (this.failOnCorruptedImage) {- error('JPX error: ' + e);- } else {- warn('JPX error: ' + e + '. Trying to recover');- }}},parseCodestream: function JpxImage_parseCodestream(data, start, end) {@@ -37905,7 +37483,7 @@ var JpxImage = (function JpxImageClosure() {var code = readUint16(data, position);position += 2;- var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;+ var length = 0, j;switch (code) {case 0xFF4F: // Start of codestream (SOC)context.mainHeader = true;@@ -37947,7 +37525,8 @@ var JpxImage = (function JpxImageClosure() {length = readUint16(data, position);var qcd = {};j = position + 2;- sqcd = data[j++];+ var sqcd = data[j++];+ var spqcdSize, scalarExpounded;switch (sqcd & 0x1F) {case 0:spqcdSize = 8;@@ -37964,10 +37543,10 @@ var JpxImage = (function JpxImageClosure() {default:throw 'Invalid SQcd value ' + sqcd;}- qcd.noQuantization = (spqcdSize == 8);+ qcd.noQuantization = spqcdSize == 8;qcd.scalarExpounded = scalarExpounded;qcd.guardBits = sqcd >> 5;- spqcds = [];+ var spqcds = [];while (j < length + position) {var spqcd = {};if (spqcdSize == 8) {@@ -37981,9 +37560,9 @@ var JpxImage = (function JpxImageClosure() {spqcds.push(spqcd);}qcd.SPqcds = spqcds;- if (context.mainHeader) {+ if (context.mainHeader)context.QCD = qcd;- } else {+ else {context.currentTile.QCD = qcd;context.currentTile.QCC = [];}@@ -37993,13 +37572,14 @@ var JpxImage = (function JpxImageClosure() {var qcc = {};j = position + 2;var cqcc;- if (context.SIZ.Csiz < 257) {+ if (context.SIZ.Csiz < 257)cqcc = data[j++];- } else {+ else {cqcc = readUint16(data, j);j += 2;}- sqcd = data[j++];+ var sqcd = data[j++];+ var spqcdSize, scalarExpounded;switch (sqcd & 0x1F) {case 0:spqcdSize = 8;@@ -38016,12 +37596,12 @@ var JpxImage = (function JpxImageClosure() {default:throw 'Invalid SQcd value ' + sqcd;}- qcc.noQuantization = (spqcdSize == 8);+ qcc.noQuantization = spqcdSize == 8;qcc.scalarExpounded = scalarExpounded;qcc.guardBits = sqcd >> 5;- spqcds = [];- while (j < (length + position)) {- spqcd = {};+ var spqcds = [];+ while (j < length + position) {+ var spqcd = {};if (spqcdSize == 8) {spqcd.epsilon = data[j++] >> 3;spqcd.mu = 0;@@ -38033,11 +37613,10 @@ var JpxImage = (function JpxImageClosure() {spqcds.push(spqcd);}qcc.SPqcds = spqcds;- if (context.mainHeader) {+ if (context.mainHeader)context.QCC[cqcc] = qcc;- } else {+ elsecontext.currentTile.QCC[cqcc] = qcc;- }break;case 0xFF52: // Coding style default (COD)length = readUint16(data, position);@@ -38063,11 +37642,11 @@ var JpxImage = (function JpxImageClosure() {cod.verticalyStripe = !!(blockStyle & 8);cod.predictableTermination = !!(blockStyle & 16);cod.segmentationSymbolUsed = !!(blockStyle & 32);- cod.reversibleTransformation = data[j++];+ cod.transformation = data[j++];if (cod.entropyCoderWithCustomPrecincts) {- var precinctsSizes = [];+ var precinctsSizes = {};while (j < length + position) {- var precinctsSize = data[j++];+ var precinctsSize = data[j];precinctsSizes.push({PPx: precinctsSize & 0xF,PPy: precinctsSize >> 4@@ -38080,21 +37659,20 @@ var JpxImage = (function JpxImageClosure() {cod.selectiveArithmeticCodingBypass ||cod.resetContextProbabilities ||cod.terminationOnEachCodingPass ||- cod.verticalyStripe || cod.predictableTermination) {+ cod.verticalyStripe || cod.predictableTermination)throw 'Unsupported COD options: ' +globalScope.JSON.stringify(cod);- }- if (context.mainHeader) {+ if (context.mainHeader)context.COD = cod;- } else {+ else {context.currentTile.COD = cod;context.currentTile.COC = [];}break;case 0xFF90: // Start of tile-part (SOT)length = readUint16(data, position);- tile = {};+ var tile = {};tile.index = readUint16(data, position + 2);tile.length = readUint32(data, position + 4);tile.dataEnd = tile.length + position - 2;@@ -38112,7 +37690,7 @@ var JpxImage = (function JpxImageClosure() {context.currentTile = tile;break;case 0xFF93: // Start of data (SOD)- tile = context.currentTile;+ var tile = context.currentTile;if (tile.partIndex === 0) {initializeTile(context, tile.index);buildPackets(context);@@ -38120,25 +37698,23 @@ var JpxImage = (function JpxImageClosure() {// moving to the end of the datalength = tile.dataEnd - position;+parseTilePackets(context, data, position, length);break;case 0xFF64: // Comment (COM)length = readUint16(data, position);// skipping contentbreak;- case 0xFF53: // Coding style component (COC)- throw 'Codestream code 0xFF53 (COC) is not implemented';default:throw 'Unknown codestream code: ' + code.toString(16);}position += length;}} catch (e) {- if (this.failOnCorruptedImage) {+ if (this.failOnCorruptedImage)error('JPX error: ' + e);- } else {+ elsewarn('JPX error: ' + e + '. Trying to recover');- }}this.tiles = transformComponents(context);this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;@@ -38148,7 +37724,7 @@ var JpxImage = (function JpxImageClosure() {};function readUint32(data, offset) {return (data[offset] << 24) | (data[offset + 1] << 16) |- (data[offset + 2] << 8) | data[offset + 3];+ (data[offset + 2] << 8) | data[offset + 3];}function readUint16(data, offset) {return (data[offset] << 8) | data[offset + 1];@@ -38173,12 +37749,12 @@ var JpxImage = (function JpxImageClosure() {function calculateTileGrids(context, components) {var siz = context.SIZ;// Section B.3 Division into tile and tile-components- var tile, tiles = [];+ var tiles = [];var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);for (var q = 0; q < numYtiles; q++) {for (var p = 0; p < numXtiles; p++) {- tile = {};+ var tile = {};tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);@@ -38196,8 +37772,7 @@ var JpxImage = (function JpxImageClosure() {var component = components[i];var tileComponents = [];for (var j = 0, jj = tiles.length; j < jj; j++) {- var tileComponent = {};- tile = tiles[j];+ var tileComponent = {}, tile = tiles[j];tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);@@ -38219,27 +37794,27 @@ var JpxImage = (function JpxImageClosure() {result.PPy = codOrCoc.precinctsSizes[r].PPy;}// calculate codeblock size as described in section B.7- result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :- Math.min(codOrCoc.xcb, result.PPx));- result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :- Math.min(codOrCoc.ycb, result.PPy));+ result.xcb_ = r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :+ Math.min(codOrCoc.xcb, result.PPx);+ result.ycb_ = r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :+ Math.min(codOrCoc.ycb, result.PPy);return result;}function buildPrecincts(context, resolution, dimensions) {// Section B.6 Division resolution to precinctsvar precinctWidth = 1 << dimensions.PPx;var precinctHeight = 1 << dimensions.PPy;- var numprecinctswide = (resolution.trx1 > resolution.trx0 ?+ var numprecinctswide = resolution.trx1 > resolution.trx0 ?Math.ceil(resolution.trx1 / precinctWidth) -- Math.floor(resolution.trx0 / precinctWidth) : 0);- var numprecinctshigh = (resolution.try1 > resolution.try0 ?+ Math.floor(resolution.trx0 / precinctWidth) : 0;+ var numprecinctshigh = resolution.try1 > resolution.try0 ?Math.ceil(resolution.try1 / precinctHeight) -- Math.floor(resolution.try0 / precinctHeight) : 0);+ Math.floor(resolution.try0 / precinctHeight) : 0;var numprecincts = numprecinctswide * numprecinctshigh;var precinctXOffset = Math.floor(resolution.trx0 / precinctWidth) *- precinctWidth;+ precinctWidth;var precinctYOffset = Math.floor(resolution.try0 / precinctHeight) *- precinctHeight;+ precinctHeight;resolution.precinctParameters = {precinctXOffset: precinctXOffset,precinctYOffset: precinctYOffset,@@ -38256,17 +37831,16 @@ var JpxImage = (function JpxImageClosure() {var ycb_ = dimensions.ycb_;var codeblockWidth = 1 << xcb_;var codeblockHeight = 1 << ycb_;- var cbx0 = subband.tbx0 >> xcb_;- var cby0 = subband.tby0 >> ycb_;- var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;- var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;+ var cbx0 = Math.floor(subband.tbx0 / codeblockWidth);+ var cby0 = Math.floor(subband.tby0 / codeblockHeight);+ var cbx1 = Math.ceil(subband.tbx1 / codeblockWidth);+ var cby1 = Math.ceil(subband.tby1 / codeblockHeight);var precinctParameters = subband.resolution.precinctParameters;var codeblocks = [];var precincts = [];- var i, ii, j, codeblock, precinctNumber;- for (j = cby0; j < cby1; j++) {- for (i = cbx0; i < cbx1; i++) {- codeblock = {+ for (var j = cby0; j < cby1; j++) {+ for (var i = cbx0; i < cbx1; i++) {+ var codeblock = {cbx: i,cby: j,tbx0: codeblockWidth * i,@@ -38276,12 +37850,13 @@ var JpxImage = (function JpxImageClosure() {};// calculate precinct numbervar pi = Math.floor((codeblock.tbx0 -- precinctParameters.precinctXOffset) /- precinctParameters.precinctWidth);+ precinctParameters.precinctXOffset) /+ precinctParameters.precinctWidth);var pj = Math.floor((codeblock.tby0 -- precinctParameters.precinctYOffset) /- precinctParameters.precinctHeight);- precinctNumber = pj + pi * precinctParameters.numprecinctswide;+ precinctParameters.precinctYOffset) /+ precinctParameters.precinctHeight);+ var precinctNumber = pj ++ pi * precinctParameters.numprecinctswide;codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);@@ -38289,22 +37864,17 @@ var JpxImage = (function JpxImageClosure() {codeblock.precinctNumber = precinctNumber;codeblock.subbandType = subband.type;var coefficientsLength = (codeblock.tbx1_ - codeblock.tbx0_) *- (codeblock.tby1_ - codeblock.tby0_);+ (codeblock.tby1_ - codeblock.tby0_);codeblock.Lblock = 3;codeblocks.push(codeblock);// building precinct for the sub-band- var precinct = precincts[precinctNumber];- if (precinct !== undefined) {- if (i < precinct.cbxMin) {- precinct.cbxMin = i;- } else if (i > precinct.cbxMax) {- precinct.cbxMax = i;- }- if (j < precinct.cbyMin) {- precinct.cbxMin = j;- } else if (j > precinct.cbyMax) {- precinct.cbyMax = j;- }+ var precinct;+ if (precinctNumber in precincts) {+ precinct = precincts[precinctNumber];+ precinct.cbxMin = Math.min(precinct.cbxMin, i);+ precinct.cbyMin = Math.min(precinct.cbyMin, j);+ precinct.cbxMax = Math.max(precinct.cbxMax, i);+ precinct.cbyMax = Math.max(precinct.cbyMax, j);} else {precincts[precinctNumber] = precinct = {cbxMin: i,@@ -38323,6 +37893,10 @@ var JpxImage = (function JpxImageClosure() {numcodeblockhigh: cby1 - cby1 + 1};subband.codeblocks = codeblocks;+ for (var i = 0, ii = codeblocks.length; i < ii; i++) {+ var codeblock = codeblocks[i];+ var precinctNumber = codeblock.precinctNumber;+ }subband.precincts = precincts;}function createPacket(resolution, precinctNumber, layerNumber) {@@ -38335,9 +37909,8 @@ var JpxImage = (function JpxImageClosure() {var codeblocks = subband.codeblocks;for (var j = 0, jj = codeblocks.length; j < jj; j++) {var codeblock = codeblocks[j];- if (codeblock.precinctNumber != precinctNumber) {+ if (codeblock.precinctNumber != precinctNumber)continue;- }precinctCodeblocks.push(codeblock);}}@@ -38366,9 +37939,8 @@ var JpxImage = (function JpxImageClosure() {for (; r <= maxDecompositionLevelsCount; r++) {for (; i < componentsCount; i++) {var component = tile.components[i];- if (r > component.codingStyleParameters.decompositionLevelsCount) {+ if (r > component.codingStyleParameters.decompositionLevelsCount)continue;- }var resolution = component.resolutions[r];var numprecincts = resolution.precinctParameters.numprecincts;@@ -38406,9 +37978,8 @@ var JpxImage = (function JpxImageClosure() {for (; l < layersCount; l++) {for (; i < componentsCount; i++) {var component = tile.components[i];- if (r > component.codingStyleParameters.decompositionLevelsCount) {+ if (r > component.codingStyleParameters.decompositionLevelsCount)continue;- }var resolution = component.resolutions[r];var numprecincts = resolution.precinctParameters.numprecincts;@@ -38553,21 +38124,17 @@ var JpxImage = (function JpxImageClosure() {}function readCodingpasses() {var value = readBits(1);- if (value === 0) {+ if (value === 0)return 1;- }value = (value << 1) | readBits(1);- if (value == 0x02) {+ if (value == 0x02)return 2;- }value = (value << 2) | readBits(2);- if (value <= 0x0E) {+ if (value <= 0x0E)return (value & 0x03) + 3;- }value = (value << 5) | readBits(5);- if (value <= 0x1FE) {+ if (value <= 0x1FE)return (value & 0x1F) + 6;- }value = (value << 7) | readBits(7);return (value & 0x7F) + 37;}@@ -38581,20 +38148,19 @@ var JpxImage = (function JpxImageClosure() {continue;}var layerNumber = packet.layerNumber;- var queue = [], codeblock;+ var queue = [];for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {- codeblock = packet.codeblocks[i];+ var codeblock = packet.codeblocks[i];var precinct = codeblock.precinct;var codeblockColumn = codeblock.cbx - precinct.cbxMin;var codeblockRow = codeblock.cby - precinct.cbyMin;var codeblockIncluded = false;var firstTimeInclusion = false;- var valueReady;if ('included' in codeblock) {codeblockIncluded = !!readBits(1);} else {// reading inclusion tree- precinct = codeblock.precinct;+ var precinct = codeblock.precinct;var inclusionTree, zeroBitPlanesTree;if ('inclusionTree' in precinct) {inclusionTree = precinct.inclusionTree;@@ -38611,7 +38177,7 @@ var JpxImage = (function JpxImageClosure() {if (inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber)) {while (true) {if (readBits(1)) {- valueReady = !inclusionTree.nextLevel();+ var valueReady = !inclusionTree.nextLevel();if (valueReady) {codeblock.included = true;codeblockIncluded = firstTimeInclusion = true;@@ -38624,28 +38190,24 @@ var JpxImage = (function JpxImageClosure() {}}}- if (!codeblockIncluded) {+ if (!codeblockIncluded)continue;- }if (firstTimeInclusion) {zeroBitPlanesTree = precinct.zeroBitPlanesTree;zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);while (true) {if (readBits(1)) {- valueReady = !zeroBitPlanesTree.nextLevel();- if (valueReady) {+ var valueReady = !zeroBitPlanesTree.nextLevel();+ if (valueReady)break;- }- } else {+ } elsezeroBitPlanesTree.incrementValue();- }}codeblock.zeroBitPlanes = zeroBitPlanesTree.value;}var codingpasses = readCodingpasses();- while (readBits(1)) {+ while (readBits(1))codeblock.Lblock++;- }var codingpassesLog2 = log2(codingpasses);// rounding down log2var bits = ((codingpasses < (1 << codingpassesLog2)) ?@@ -38660,10 +38222,9 @@ var JpxImage = (function JpxImageClosure() {alignToByte();while (queue.length > 0) {var packetItem = queue.shift();- codeblock = packetItem.codeblock;- if (!('data' in codeblock)) {+ var codeblock = packetItem.codeblock;+ if (!('data' in codeblock))codeblock.data = [];- }codeblock.data.push({data: data,start: offset + position,@@ -38676,35 +38237,33 @@ var JpxImage = (function JpxImageClosure() {return position;}function copyCoefficients(coefficients, x0, y0, width, height,- delta, mb, codeblocks, reversible,+ delta, mb, codeblocks, transformation,segmentationSymbolUsed) {+ var r = 0.5; // formula (E-6)for (var i = 0, ii = codeblocks.length; i < ii; ++i) {var codeblock = codeblocks[i];var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;var blockHeight = codeblock.tby1_ - codeblock.tby0_;- if (blockWidth === 0 || blockHeight === 0) {+ if (blockWidth === 0 || blockHeight === 0)continue;- }- if (!('data' in codeblock)) {+ if (!('data' in codeblock))continue;- }var bitModel, currentCodingpassType;bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,- codeblock.zeroBitPlanes);+ codeblock.zeroBitPlanes);currentCodingpassType = 2; // first bit plane starts from cleanup// collect datavar data = codeblock.data, totalLength = 0, codingpasses = 0;- var q, qq, dataItem;- for (q = 0, qq = data.length; q < qq; q++) {- dataItem = data[q];+ for (var q = 0, qq = data.length; q < qq; q++) {+ var dataItem = data[q];totalLength += dataItem.end - dataItem.start;codingpasses += dataItem.codingpasses;}var encodedData = new Uint8Array(totalLength), k = 0;- for (q = 0, qq = data.length; q < qq; q++) {- dataItem = data[q];+ for (var q = 0, qq = data.length; q < qq; q++) {+ var dataItem = data[q];var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);encodedData.set(chunk, k);k += chunk.length;@@ -38713,7 +38272,7 @@ var JpxImage = (function JpxImageClosure() {var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);bitModel.setDecoder(decoder);- for (q = 0; q < codingpasses; q++) {+ for (var q = 0; q < codingpasses; q++) {switch (currentCodingpassType) {case 0:bitModel.runSignificancePropogationPass();@@ -38723,37 +38282,28 @@ var JpxImage = (function JpxImageClosure() {break;case 2:bitModel.runCleanupPass();- if (segmentationSymbolUsed) {+ if (segmentationSymbolUsed)bitModel.checkSegmentationSymbol();- }break;}currentCodingpassType = (currentCodingpassType + 1) % 3;}var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;- var n, nb, correction, position = 0;- var irreversible = !reversible;- var sign = bitModel.coefficentsSign;- var magnitude = bitModel.coefficentsMagnitude;- var bitsDecoded = bitModel.bitsDecoded;- var magnitudeCorrection = reversible ? 0 : 0.5;+ var position = 0;for (var j = 0; j < blockHeight; j++) {- for (k = 0; k < blockWidth; k++) {- n = magnitude[position];- if (n !== 0) {- n = (n + magnitudeCorrection) * delta;- if (sign[position] !== 0) {- n = -n;- }- nb = bitsDecoded[position];- if (irreversible || mb > nb) {- coefficients[offset] = n * (1 << (mb - nb));- } else {- coefficients[offset] = n;- }- }- offset++;+ for (var k = 0; k < blockWidth; k++) {+ var n = (bitModel.coefficentsSign[position] ? -1 : 1) *+ bitModel.coefficentsMagnitude[position];+ var nb = bitModel.bitsDecoded[position], correction;+ if (transformation === 0 || mb > nb) {+ // use r only if transformation is irreversible or+ // not all bitplanes were decoded for reversible transformation+ n += n < 0 ? n - r : n > 0 ? n + r : 0;+ correction = 1 << (mb - nb);+ } else+ correction = 1;+ coefficients[offset++] = n * correction * delta;position++;}offset += width - blockWidth;@@ -38769,15 +38319,12 @@ var JpxImage = (function JpxImageClosure() {var spqcds = quantizationParameters.SPqcds;var scalarExpounded = quantizationParameters.scalarExpounded;var guardBits = quantizationParameters.guardBits;+ var transformation = codingStyleParameters.transformation;var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;var precision = context.components[c].precision;- var reversible = codingStyleParameters.reversibleTransformation;- var transform = (reversible ? new ReversibleTransform() :- new IrreversibleTransform());-var subbandCoefficients = [];- var b = 0;+ var k = 0, b = 0;for (var i = 0; i <= decompositionLevelsCount; i++) {var resolution = component.resolutions[i];@@ -38798,13 +38345,13 @@ var JpxImage = (function JpxImageClosure() {var gainLog2 = SubbandsGainLog2[subband.type];// calulate quantization coefficient (Section E.1.1.1)- var delta = (reversible ? 1 :- Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));+ var delta = Math.pow(2, (precision + gainLog2) - epsilon) *+ (1 + mu / 2048);var mb = (guardBits + epsilon - 1);var coefficients = new Float32Array(width * height);copyCoefficients(coefficients, subband.tbx0, subband.tby0,- width, height, delta, mb, subband.codeblocks, reversible,+ width, height, delta, mb, subband.codeblocks, transformation,segmentationSymbolUsed);subbandCoefficients.push({@@ -38817,8 +38364,11 @@ var JpxImage = (function JpxImageClosure() {}}+ var transformation = codingStyleParameters.transformation;+ var transform = transformation === 0 ? new IrreversibleTransform() :+ new ReversibleTransform();var result = transform.calculate(subbandCoefficients,- component.tcx0, component.tcy0);+ component.tcx0, component.tcy0);return {left: component.tcx0,top: component.tcy0,@@ -38835,55 +38385,49 @@ var JpxImage = (function JpxImageClosure() {for (var i = 0, ii = context.tiles.length; i < ii; i++) {var tile = context.tiles[i];var result = [];- var c;- for (c = 0; c < componentsCount; c++) {+ for (var c = 0; c < componentsCount; c++) {var image = transformTile(context, tile, c);result.push(image);}// Section G.2.2 Inverse multi component transform- var y0items, y1items, y2items, j, jj, y0, y1, y2;- var component, offset, tileImage, items;if (tile.codingStyleDefaultParameters.multipleComponentTransform) {- var component0 = tile.components[0];- if (!component0.codingStyleParameters.reversibleTransformation) {- // inverse irreversible multiple component transform- y0items = result[0].items;- y1items = result[1].items;- y2items = result[2].items;- for (j = 0, jj = y0items.length; j < jj; ++j) {- y0 = y0items[j] + 0.5; y1 = y1items[j]; y2 = y2items[j];- y0items[j] = y0 + 1.402 * y2;- y1items[j] = y0 - 0.34413 * y1 - 0.71414 * y2;- y2items[j] = y0 + 1.772 * y1;- }- } else {- // inverse reversible multiple component transform- y0items = result[0].items;- y1items = result[1].items;- y2items = result[2].items;- for (j = 0, jj = y0items.length; j < jj; ++j) {- y0 = y0items[j]; y1 = y1items[j]; y2 = y2items[j];- var i1 = y0 - ((y2 + y1) >> 2);- y1items[j] = i1;- y0items[j] = y2 + i1;- y2items[j] = y1 + i1;- }- }+ var y0items = result[0].items;+ var y1items = result[1].items;+ var y2items = result[2].items;+ for (var j = 0, jj = y0items.length; j < jj; j++) {+ var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j];+ var i1 = y0 - ((y2 + y1) >> 2);+ y1items[j] = i1;+ y0items[j] = y2 + i1;+ y2items[j] = y1 + i1;+ }+ }++ // Section G.1 DC level shifting to unsigned component values+ for (var c = 0; c < componentsCount; c++) {+ var component = components[c];+ if (component.isSigned)+ continue;++ var offset = 1 << (component.precision - 1);+ var tileImage = result[c];+ var items = tileImage.items;+ for (var j = 0, jj = items.length; j < jj; j++)+ items[j] += offset;}// To simplify things: shift and clamp output to 8 bit unsigned- for (c = 0; c < componentsCount; c++) {- component = components[c];+ for (var c = 0; c < componentsCount; c++) {+ var component = components[c];+ var offset = component.isSigned ? 128 : 0;var shift = component.precision - 8;- tileImage = result[c];- items = tileImage.items;+ var tileImage = result[c];+ var items = tileImage.items;var data = new Uint8Array(items.length);- var low = -(128 << shift);- var high = 127 << shift;- for (j = 0, jj = items.length; j < jj; j++) {- var val = items[j];- data[j] = val <= low ? 0 : val >= high ? 255 : (val >> shift) + 128;+ for (var j = 0, jj = items.length; j < jj; j++) {+ var value = (items[j] >> shift) + offset;+ data[j] = value < 0 ? 0 : value > 255 ? 255 : value;}result[c].items = data;}@@ -38899,11 +38443,11 @@ var JpxImage = (function JpxImageClosure() {var resultTiles = [];for (var c = 0; c < componentsCount; c++) {var component = tile.components[c];- var qcdOrQcc = (c in context.currentTile.QCC ?- context.currentTile.QCC[c] : context.currentTile.QCD);+ var qcdOrQcc = c in context.currentTile.QCC ?+ context.currentTile.QCC[c] : context.currentTile.QCD;component.quantizationParameters = qcdOrQcc;- var codOrCoc = (c in context.currentTile.COC ?- context.currentTile.COC[c] : context.currentTile.COD);+ var codOrCoc = c in context.currentTile.COC ?+ context.currentTile.COC[c] : context.currentTile.COD;component.codingStyleParameters = codOrCoc;}tile.codingStyleDefaultParameters = context.currentTile.COD;@@ -38927,9 +38471,9 @@ var JpxImage = (function JpxImageClosure() {}TagTree.prototype = {reset: function TagTree_reset(i, j) {- var currentLevel = 0, value = 0, level;+ var currentLevel = 0, value = 0;while (currentLevel < this.levels.length) {- level = this.levels[currentLevel];+ var level = this.levels[currentLevel];var index = i + j * level.width;if (index in level.items) {value = level.items[index];@@ -38941,7 +38485,7 @@ var JpxImage = (function JpxImageClosure() {currentLevel++;}currentLevel--;- level = this.levels[currentLevel];+ var level = this.levels[currentLevel];level.items[level.index] = value;this.currentLevel = currentLevel;delete this.value;@@ -38961,7 +38505,7 @@ var JpxImage = (function JpxImageClosure() {}this.currentLevel = currentLevel;- level = this.levels[currentLevel];+ var level = this.levels[currentLevel];level.items[level.index] = value;return true;}@@ -38975,9 +38519,8 @@ var JpxImage = (function JpxImageClosure() {this.levels = [];for (var i = 0; i < levelsLength; i++) {var items = new Uint8Array(width * height);- for (var j = 0, jj = items.length; j < jj; j++) {+ for (var j = 0, jj = items.length; j < jj; j++)items[j] = defaultValue;- }var level = {width: width,@@ -38999,9 +38542,8 @@ var JpxImage = (function JpxImageClosure() {level.index = index;var value = level.items[index];- if (value == 0xFF) {+ if (value == 0xFF)break;- }if (value > stopValue) {this.currentLevel = currentLevel;@@ -39027,7 +38569,7 @@ var JpxImage = (function JpxImageClosure() {var level = this.levels[levelIndex];var currentValue = level.items[level.index];while (--levelIndex >= 0) {- level = this.levels[levelIndex];+ var level = this.levels[levelIndex];level.items[level.index] = currentValue;}},@@ -39037,12 +38579,11 @@ var JpxImage = (function JpxImageClosure() {var value = level.items[level.index];level.items[level.index] = 0xFF;currentLevel--;- if (currentLevel < 0) {+ if (currentLevel < 0)return false;- }this.currentLevel = currentLevel;- level = this.levels[currentLevel];+ var level = this.levels[currentLevel];level.items[level.index] = value;return true;}@@ -39050,10 +38591,171 @@ var JpxImage = (function JpxImageClosure() {return InclusionTree;})();+ // Implements C.3. Arithmetic decoding procedures+ var ArithmeticDecoder = (function ArithmeticDecoderClosure() {+ var QeTable = [+ {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},+ {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},+ {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},+ {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},+ {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},+ {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},+ {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},+ {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},+ {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},+ {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},+ {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},+ {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},+ {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},+ {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},+ {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},+ {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},+ {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},+ {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},+ {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},+ {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},+ {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},+ {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},+ {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},+ {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},+ {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},+ {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},+ {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},+ {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},+ {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},+ {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},+ {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},+ {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},+ {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},+ {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},+ {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},+ {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},+ {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},+ {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},+ {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},+ {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},+ {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},+ {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},+ {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},+ {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},+ {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},+ {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},+ {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}+ ];++ function ArithmeticDecoder(data, start, end) {+ this.data = data;+ this.bp = start;+ this.dataEnd = end;++ this.chigh = data[start];+ this.clow = 0;++ this.byteIn();++ this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);+ this.clow = (this.clow << 7) & 0xFFFF;+ this.ct -= 7;+ this.a = 0x8000;+ }++ ArithmeticDecoder.prototype = {+ byteIn: function ArithmeticDecoder_byteIn() {+ var data = this.data;+ var bp = this.bp;+ if (data[bp] == 0xFF) {+ var b1 = data[bp + 1];+ if (b1 > 0x8F) {+ this.clow += 0xFF00;+ this.ct = 8;+ } else {+ bp++;+ this.clow += (data[bp] << 9);+ this.ct = 7;+ this.bp = bp;+ }+ } else {+ bp++;+ this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;+ this.ct = 8;+ this.bp = bp;+ }+ if (this.clow > 0xFFFF) {+ this.chigh += (this.clow >> 16);+ this.clow &= 0xFFFF;+ }+ },+ readBit: function ArithmeticDecoder_readBit(cx) {+ var qeIcx = QeTable[cx.index].qe;+ this.a -= qeIcx;++ if (this.chigh < qeIcx) {+ var d = this.exchangeLps(cx);+ this.renormD();+ return d;+ } else {+ this.chigh -= qeIcx;+ if ((this.a & 0x8000) === 0) {+ var d = this.exchangeMps(cx);+ this.renormD();+ return d;+ } else {+ return cx.mps;+ }+ }+ },+ renormD: function ArithmeticDecoder_renormD() {+ do {+ if (this.ct === 0)+ this.byteIn();++ this.a <<= 1;+ this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);+ this.clow = (this.clow << 1) & 0xFFFF;+ this.ct--;+ } while ((this.a & 0x8000) === 0);+ },+ exchangeMps: function ArithmeticDecoder_exchangeMps(cx) {+ var d;+ var qeTableIcx = QeTable[cx.index];+ if (this.a < qeTableIcx.qe) {+ d = 1 - cx.mps;++ if (qeTableIcx.switchFlag == 1) {+ cx.mps = 1 - cx.mps;+ }+ cx.index = qeTableIcx.nlps;+ } else {+ d = cx.mps;+ cx.index = qeTableIcx.nmps;+ }+ return d;+ },+ exchangeLps: function ArithmeticDecoder_exchangeLps(cx) {+ var d;+ var qeTableIcx = QeTable[cx.index];+ if (this.a < qeTableIcx.qe) {+ this.a = qeTableIcx.qe;+ d = cx.mps;+ cx.index = qeTableIcx.nmps;+ } else {+ this.a = qeTableIcx.qe;+ d = 1 - cx.mps;++ if (qeTableIcx.switchFlag == 1) {+ cx.mps = 1 - cx.mps;+ }+ cx.index = qeTableIcx.nlps;+ }+ return d;+ }+ };++ return ArithmeticDecoder;+ })();+// Section D. Coefficient bit modelingvar BitModel = (function BitModelClosure() {- var UNIFORM_CONTEXT = 17;- var RUNLENGTH_CONTEXT = 18;// Table D-1// The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),// vv - sum of Vi (0..2), and hh - sum of Hi (0..2)@@ -39073,12 +38775,35 @@ var JpxImage = (function JpxImageClosure() {8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8]);+ // Table D-2+ function calcSignContribution(significance0, sign0, significance1, sign1) {+ if (significance1) {+ if (!sign1)+ return significance0 ? (!sign0 ? 1 : 0) : 1;+ else+ return significance0 ? (!sign0 ? 0 : -1) : -1;+ } else+ return significance0 ? (!sign0 ? 1 : -1) : 0;+ }+ // Table D-3+ var SignContextLabels = [+ {contextLabel: 13, xorBit: 0},+ {contextLabel: 12, xorBit: 0},+ {contextLabel: 11, xorBit: 0},+ {contextLabel: 10, xorBit: 0},+ {contextLabel: 9, xorBit: 0},+ {contextLabel: 10, xorBit: 1},+ {contextLabel: 11, xorBit: 1},+ {contextLabel: 12, xorBit: 1},+ {contextLabel: 13, xorBit: 1}+ ];+function BitModel(width, height, subband, zeroBitPlanes) {this.width = width;this.height = height;- this.contextLabelTable = (subband == 'HH' ? HHContextLabel :- (subband == 'HL' ? HLContextLabel : LLAndLHContextsLabel));+ this.contextLabelTable = subband == 'HH' ? HHContextLabel :+ subband == 'HL' ? HLContextLabel : LLAndLHContextsLabel;var coefficientCount = width * height;@@ -39089,12 +38814,9 @@ var JpxImage = (function JpxImageClosure() {this.coefficentsMagnitude = new Uint32Array(coefficientCount);this.processingFlags = new Uint8Array(coefficientCount);- var bitsDecoded = new Uint8Array(coefficientCount);- if (zeroBitPlanes !== 0) {- for (var i = 0; i < coefficientCount; i++) {- bitsDecoded[i] = zeroBitPlanes;- }- }+ var bitsDecoded = new Uint8Array(this.width * this.height);+ for (var i = 0, ii = bitsDecoded.length; i < ii; i++)+ bitsDecoded[i] = zeroBitPlanes;this.bitsDecoded = bitsDecoded;this.reset();@@ -39105,52 +38827,36 @@ var JpxImage = (function JpxImageClosure() {this.decoder = decoder;},reset: function BitModel_reset() {- // We have 17 contexts that are accessed via context labels,- // plus the uniform and runlength context.- this.contexts = new Int8Array(19);-- // Contexts are packed into 1 byte:- // highest 7 bits carry the index, lowest bit carries mps- this.contexts[0] = (4 << 1) | 0;- this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;- this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;+ this.uniformContext = {index: 46, mps: 0};+ this.runLengthContext = {index: 3, mps: 0};+ this.contexts = [];+ this.contexts.push({index: 4, mps: 0});+ for (var i = 1; i <= 16; i++)+ this.contexts.push({index: 0, mps: 0});},setNeighborsSignificance:- function BitModel_setNeighborsSignificance(row, column, index) {+ function BitModel_setNeighborsSignificance(row, column) {var neighborsSignificance = this.neighborsSignificance;var width = this.width, height = this.height;- var left = (column > 0);- var right = (column + 1 < width);- var i;-+ var index = row * width + column;if (row > 0) {- i = index - width;- if (left) {- neighborsSignificance[i - 1] += 0x10;- }- if (right) {- neighborsSignificance[i + 1] += 0x10;- }- neighborsSignificance[i] += 0x04;+ if (column > 0)+ neighborsSignificance[index - width - 1] += 0x10;+ if (column + 1 < width)+ neighborsSignificance[index - width + 1] += 0x10;+ neighborsSignificance[index - width] += 0x04;}-if (row + 1 < height) {- i = index + width;- if (left) {- neighborsSignificance[i - 1] += 0x10;- }- if (right) {- neighborsSignificance[i + 1] += 0x10;- }- neighborsSignificance[i] += 0x04;+ if (column > 0)+ neighborsSignificance[index + width - 1] += 0x10;+ if (column + 1 < width)+ neighborsSignificance[index + width + 1] += 0x10;+ neighborsSignificance[index + width] += 0x04;}-- if (left) {+ if (column > 0)neighborsSignificance[index - 1] += 0x01;- }- if (right) {+ if (column + 1 < width)neighborsSignificance[index + 1] += 0x01;- }neighborsSignificance[index] |= 0x80;},runSignificancePropogationPass:@@ -39165,33 +38871,32 @@ var JpxImage = (function JpxImageClosure() {var contexts = this.contexts;var labels = this.contextLabelTable;var bitsDecoded = this.bitsDecoded;+ // clear processed flagvar processedInverseMask = ~1;var processedMask = 1;var firstMagnitudeBitMask = 2;+ for (var q = 0, qq = width * height; q < qq; q++)+ processingFlags[q] &= processedInverseMask;for (var i0 = 0; i0 < height; i0 += 4) {for (var j = 0; j < width; j++) {var index = i0 * width + j;for (var i1 = 0; i1 < 4; i1++, index += width) {var i = i0 + i1;- if (i >= height) {+ if (i >= height)break;- }- // clear processed flag first- processingFlags[index] &= processedInverseMask;- if (coefficentsMagnitude[index] ||- !neighborsSignificance[index]) {+ if (coefficentsMagnitude[index] || !neighborsSignificance[index])continue;- }var contextLabel = labels[neighborsSignificance[index]];- var decision = decoder.readBit(contexts, contextLabel);+ var cx = contexts[contextLabel];+ var decision = decoder.readBit(cx);if (decision) {- var sign = this.decodeSignBit(i, j, index);+ var sign = this.decodeSignBit(i, j);coefficentsSign[index] = sign;coefficentsMagnitude[index] = 1;- this.setNeighborsSignificance(i, j, index);+ this.setNeighborsSignificance(i, j);processingFlags[index] |= firstMagnitudeBitMask;}bitsDecoded[index]++;@@ -39200,56 +38905,28 @@ var JpxImage = (function JpxImageClosure() {}}},- decodeSignBit: function BitModel_decodeSignBit(row, column, index) {+ decodeSignBit: function BitModel_decodeSignBit(row, column) {var width = this.width, height = this.height;+ var index = row * width + column;var coefficentsMagnitude = this.coefficentsMagnitude;var coefficentsSign = this.coefficentsSign;- var contribution, sign0, sign1, significance1;- var contextLabel, decoded;-- // calculate horizontal contribution- significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);- if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {- sign1 = coefficentsSign[index + 1];- if (significance1) {- sign0 = coefficentsSign[index - 1];- contribution = 1 - sign1 - sign0;- } else {- contribution = 1 - sign1 - sign1;- }- } else if (significance1) {- sign0 = coefficentsSign[index - 1];- contribution = 1 - sign0 - sign0;- } else {- contribution = 0;- }- var horizontalContribution = 3 * contribution;-- // calculate vertical contribution and combine with the horizontal- significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);- if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {- sign1 = coefficentsSign[index + width];- if (significance1) {- sign0 = coefficentsSign[index - width];- contribution = 1 - sign1 - sign0 + horizontalContribution;- } else {- contribution = 1 - sign1 - sign1 + horizontalContribution;- }- } else if (significance1) {- sign0 = coefficentsSign[index - width];- contribution = 1 - sign0 - sign0 + horizontalContribution;- } else {- contribution = horizontalContribution;- }-- if (contribution >= 0) {- contextLabel = 9 + contribution;- decoded = this.decoder.readBit(this.contexts, contextLabel);- } else {- contextLabel = 9 - contribution;- decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;- }- return decoded;+ var horizontalContribution = calcSignContribution(+ column > 0 && coefficentsMagnitude[index - 1],+ coefficentsSign[index - 1],+ column + 1 < width && coefficentsMagnitude[index + 1],+ coefficentsSign[index + 1]);+ var verticalContribution = calcSignContribution(+ row > 0 && coefficentsMagnitude[index - width],+ coefficentsSign[index - width],+ row + 1 < height && coefficentsMagnitude[index + width],+ coefficentsSign[index + width]);++ var contextLabelAndXor = SignContextLabels[+ 3 * (1 - horizontalContribution) + (1 - verticalContribution)];+ var contextLabel = contextLabelAndXor.contextLabel;+ var cx = this.contexts[contextLabel];+ var decoded = this.decoder.readBit(cx);+ return decoded ^ contextLabelAndXor.xorBit;},runMagnitudeRefinementPass:function BitModel_runMagnitudeRefinementPass() {@@ -39262,29 +38939,32 @@ var JpxImage = (function JpxImageClosure() {var processingFlags = this.processingFlags;var processedMask = 1;var firstMagnitudeBitMask = 2;- var length = width * height;- var width4 = width * 4;-- for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {- indexNext = Math.min(length, index0 + width4);+ for (var i0 = 0; i0 < height; i0 += 4) {for (var j = 0; j < width; j++) {- for (var index = index0 + j; index < indexNext; index += width) {+ for (var i1 = 0; i1 < 4; i1++) {+ var i = i0 + i1;+ if (i >= height)+ break;+ var index = i * width + j;// significant but not those that have just becomeif (!coefficentsMagnitude[index] ||- (processingFlags[index] & processedMask) !== 0) {+ (processingFlags[index] & processedMask) !== 0)continue;- }var contextLabel = 16;- if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {- processingFlags[index] ^= firstMagnitudeBitMask;+ if ((processingFlags[index] &+ firstMagnitudeBitMask) !== 0) {+ processingFlags[i * width + j] ^= firstMagnitudeBitMask;// first refinement- var significance = neighborsSignificance[index] & 127;- contextLabel = significance === 0 ? 15 : 14;+ var significance = neighborsSignificance[index];+ var sumOfSignificance = (significance & 3) ++ ((significance >> 2) & 3) + ((significance >> 4) & 7);+ contextLabel = sumOfSignificance >= 1 ? 15 : 14;}- var bit = decoder.readBit(contexts, contextLabel);+ var cx = contexts[contextLabel];+ var bit = decoder.readBit(cx);coefficentsMagnitude[index] =(coefficentsMagnitude[index] << 1) | bit;bitsDecoded[index]++;@@ -39314,7 +38994,7 @@ var JpxImage = (function JpxImageClosure() {var index0 = i0 * width + j;// using the property: labels[neighborsSignificance[index]] == 0// when neighborsSignificance[index] == 0- var allEmpty = (i0 + 3 < height &&+ var allEmpty = i0 + 3 < height &&processingFlags[index0] === 0 &&processingFlags[index0 + oneRowDown] === 0 &&processingFlags[index0 + twoRowsDown] === 0 &&@@ -39322,12 +39002,12 @@ var JpxImage = (function JpxImageClosure() {neighborsSignificance[index0] === 0 &&neighborsSignificance[index0 + oneRowDown] === 0 &&neighborsSignificance[index0 + twoRowsDown] === 0 &&- neighborsSignificance[index0 + threeRowsDown] === 0);+ neighborsSignificance[index0 + threeRowsDown] === 0;var i1 = 0, index = index0;- var i, sign;+ var cx, i;if (allEmpty) {- var hasSignificantCoefficent =- decoder.readBit(contexts, RUNLENGTH_CONTEXT);+ cx = this.runLengthContext;+ var hasSignificantCoefficent = decoder.readBit(cx);if (!hasSignificantCoefficent) {bitsDecoded[index0]++;bitsDecoded[index0 + oneRowDown]++;@@ -39335,42 +39015,40 @@ var JpxImage = (function JpxImageClosure() {bitsDecoded[index0 + threeRowsDown]++;continue; // next column}- i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |- decoder.readBit(contexts, UNIFORM_CONTEXT);+ cx = this.uniformContext;+ i1 = (decoder.readBit(cx) << 1) | decoder.readBit(cx);i = i0 + i1;index += i1 * width;- sign = this.decodeSignBit(i, j, index);+ var sign = this.decodeSignBit(i, j);coefficentsSign[index] = sign;coefficentsMagnitude[index] = 1;- this.setNeighborsSignificance(i, j, index);+ this.setNeighborsSignificance(i, j);processingFlags[index] |= firstMagnitudeBitMask;index = index0;- for (var i2 = i0; i2 <= i; i2++, index += width) {+ for (var i2 = i0; i2 <= i; i2++, index += width)bitsDecoded[index]++;- }i1++;}for (; i1 < 4; i1++, index += width) {i = i0 + i1;- if (i >= height) {+ if (i >= height)break;- }if (coefficentsMagnitude[index] ||- (processingFlags[index] & processedMask) !== 0) {+ (processingFlags[index] & processedMask) !== 0)continue;- }var contextLabel = labels[neighborsSignificance[index]];- var decision = decoder.readBit(contexts, contextLabel);+ cx = contexts[contextLabel];+ var decision = decoder.readBit(cx);if (decision == 1) {- sign = this.decodeSignBit(i, j, index);+ var sign = this.decodeSignBit(i, j);coefficentsSign[index] = sign;coefficentsMagnitude[index] = 1;- this.setNeighborsSignificance(i, j, index);+ this.setNeighborsSignificance(i, j);processingFlags[index] |= firstMagnitudeBitMask;}bitsDecoded[index]++;@@ -39380,46 +39058,30 @@ var JpxImage = (function JpxImageClosure() {},checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {var decoder = this.decoder;- var contexts = this.contexts;- var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |- (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |- (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |- decoder.readBit(contexts, UNIFORM_CONTEXT);- if (symbol != 0xA) {+ var cx = this.uniformContext;+ var symbol = (decoder.readBit(cx) << 3) | (decoder.readBit(cx) << 2) |+ (decoder.readBit(cx) << 1) | decoder.readBit(cx);+ if (symbol != 0xA)throw 'Invalid segmentation symbol';- }}};return BitModel;})();- // Section F, Discrete wavelet transformation+ // Section F, Discrete wavelet transofrmationvar Transform = (function TransformClosure() {- function Transform() {}-+ function Transform() {+ }Transform.prototype.calculate =function transformCalculate(subbands, u0, v0) {var ll = subbands[0];- for (var i = 1, ii = subbands.length; i < ii; i += 3) {+ for (var i = 1, ii = subbands.length, j = 1; i < ii; i += 3, j++) {ll = this.iterate(ll, subbands[i], subbands[i + 1],subbands[i + 2], u0, v0);}return ll;};- Transform.prototype.extend = function extend(buffer, offset, size) {- // Section F.3.7 extending... using max extension of 4- var i1 = offset - 1, j1 = offset + 1;- var i2 = offset + size - 2, j2 = offset + size;- buffer[i1--] = buffer[j1++];- buffer[j2++] = buffer[i2--];- buffer[i1--] = buffer[j1++];- buffer[j2++] = buffer[i2--];- buffer[i1--] = buffer[j1++];- buffer[j2++] = buffer[i2--];- buffer[i1] = buffer[j1];- buffer[j2] = buffer[i2];- };Transform.prototype.iterate = function Transform_iterate(ll, hl, lh, hh,u0, v0) {var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;@@ -39431,109 +39093,102 @@ var JpxImage = (function JpxImageClosure() {var width = llWidth + hlWidth;var height = llHeight + lhHeight;var items = new Float32Array(width * height);- var i, j, k, l, v, u;-- for (i = 0, k = 0; i < llHeight; i++) {- l = i * 2 * width;- for (j = 0; j < llWidth; j++, k++, l += 2) {+ for (var i = 0, ii = llHeight; i < ii; i++) {+ var k = i * llWidth, l = i * 2 * width;+ for (var j = 0, jj = llWidth; j < jj; j++, k++, l += 2)items[l] = llItems[k];- }}- for (i = 0, k = 0; i < hlHeight; i++) {- l = i * 2 * width + 1;- for (j = 0; j < hlWidth; j++, k++, l += 2) {+ for (var i = 0, ii = hlHeight; i < ii; i++) {+ var k = i * hlWidth, l = i * 2 * width + 1;+ for (var j = 0, jj = hlWidth; j < jj; j++, k++, l += 2)items[l] = hlItems[k];- }}- for (i = 0, k = 0; i < lhHeight; i++) {- l = (i * 2 + 1) * width;- for (j = 0; j < lhWidth; j++, k++, l += 2) {+ for (var i = 0, ii = lhHeight; i < ii; i++) {+ var k = i * lhWidth, l = (i * 2 + 1) * width;+ for (var j = 0, jj = lhWidth; j < jj; j++, k++, l += 2)items[l] = lhItems[k];- }}- for (i = 0, k = 0; i < hhHeight; i++) {- l = (i * 2 + 1) * width + 1;- for (j = 0; j < hhWidth; j++, k++, l += 2) {+ for (var i = 0, ii = hhHeight; i < ii; i++) {+ var k = i * hhWidth, l = (i * 2 + 1) * width + 1;+ for (var j = 0, jj = hhWidth; j < jj; j++, k++, l += 2)items[l] = hhItems[k];- }}var bufferPadding = 4;- var rowBuffer = new Float32Array(width + 2 * bufferPadding);+ var bufferLength = new Float32Array(Math.max(width, height) ++ 2 * bufferPadding);+ var buffer = new Float32Array(bufferLength);+ var bufferOut = new Float32Array(bufferLength);// Section F.3.4 HOR_SR- if (width === 1) {- // if width = 1, when u0 even keep items as is, when odd divide by 2- if ((u0 & 1) !== 0) {- for (v = 0, k = 0; v < height; v++, k += width) {- items[k] *= 0.5;+ for (var v = 0; v < height; v++) {+ if (width == 1) {+ // if width = 1, when u0 even keep items as is, when odd divide by 2+ if ((u0 % 1) !== 0) {+ items[v * width] /= 2;}+ continue;}- } else {- for (v = 0, k = 0; v < height; v++, k += width) {- rowBuffer.set(items.subarray(k, k + width), bufferPadding);- this.extend(rowBuffer, bufferPadding, width);- this.filter(rowBuffer, bufferPadding, width, u0, rowBuffer);+ var k = v * width;+ var l = bufferPadding;+ for (var u = 0; u < width; u++, k++, l++)+ buffer[l] = items[k];- items.set(- rowBuffer.subarray(bufferPadding, bufferPadding + width),- k);- }- }+ // Section F.3.7 extending... using max extension of 4+ var i1 = bufferPadding - 1, j1 = bufferPadding + 1;+ var i2 = bufferPadding + width - 2, j2 = bufferPadding + width;+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];- // Accesses to the items array can take long, because it may not fit into- // CPU cache and has to be fetched from main memory. Since subsequent- // accesses to the items array are not local when reading columns, we- // have a cache miss every time. To reduce cache misses, get up to- // 'numBuffers' items at a time and store them into the individual- // buffers. The colBuffers should be small enough to fit into CPU cache.- var numBuffers = 16;- var colBuffers = [];- for (i = 0; i < numBuffers; i++) {- colBuffers.push(new Float32Array(height + 2 * bufferPadding));+ this.filter(buffer, bufferPadding, width, u0, bufferOut);++ k = v * width;+ l = bufferPadding;+ for (var u = 0; u < width; u++, k++, l++)+ items[k] = bufferOut[l];}- var b, currentBuffer = 0;- ll = bufferPadding + height;// Section F.3.5 VER_SR- if (height === 1) {+ for (var u = 0; u < width; u++) {+ if (height == 1) {// if height = 1, when v0 even keep items as is, when odd divide by 2- if ((v0 & 1) !== 0) {- for (u = 0; u < width; u++) {- items[u] *= 0.5;+ if ((v0 % 1) !== 0) {+ items[u] /= 2;}+ continue;}- } else {- for (u = 0; u < width; u++) {- // if we ran out of buffers, copy several image columns at once- if (currentBuffer === 0) {- numBuffers = Math.min(width - u, numBuffers);- for (k = u, l = bufferPadding; l < ll; k += width, l++) {- for (b = 0; b < numBuffers; b++) {- colBuffers[b][l] = items[k + b];- }- }- currentBuffer = numBuffers;- }- currentBuffer--;- var buffer = colBuffers[currentBuffer];- this.extend(buffer, bufferPadding, height);- this.filter(buffer, bufferPadding, height, v0, buffer);-- // If this is last buffer in this group of buffers, flush all buffers.- if (currentBuffer === 0) {- k = u - numBuffers + 1;- for (l = bufferPadding; l < ll; k += width, l++) {- for (b = 0; b < numBuffers; b++) {- items[k + b] = colBuffers[b][l];- }- }- }- }- }+ var k = u;+ var l = bufferPadding;+ for (var v = 0; v < height; v++, k += width, l++)+ buffer[l] = items[k];++ // Section F.3.7 extending... using max extension of 4+ var i1 = bufferPadding - 1, j1 = bufferPadding + 1;+ var i2 = bufferPadding + height - 2, j2 = bufferPadding + height;+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];+ buffer[i1--] = buffer[j1++];+ buffer[j2++] = buffer[i2--];++ this.filter(buffer, bufferPadding, height, v0, bufferOut);+ k = u;+ l = bufferPadding;+ for (var v = 0; v < height; v++, k += width, l++)+ items[k] = bufferOut[l];+ }return {width: width,height: height,@@ -39552,8 +39207,9 @@ var JpxImage = (function JpxImageClosure() {IrreversibleTransform.prototype = Object.create(Transform.prototype);IrreversibleTransform.prototype.filter =function irreversibleTransformFilter(y, offset, length, i0, x) {- var len = length >> 1;- offset = offset | 0;+ var i0_ = Math.floor(i0 / 2);+ var i1_ = Math.floor((i0 + length) / 2);+ var offset_ = offset - (i0 % 1);var alpha = -1.586134342059924;var beta = -0.052980118572961;@@ -39561,35 +39217,36 @@ var JpxImage = (function JpxImageClosure() {var delta = 0.443506852043971;var K = 1.230174104914001;var K_ = 1 / K;- var j, n, nn;- // step 1 is combined with step 3+ // step 1+ var j = offset_ - 2;+ for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2)+ x[j] = K * y[j];// step 2- for (j = offset - 3, n = len + 4; n--; j += 2) {+ var j = offset_ - 3;+ for (var n = i0_ - 2, nn = i1_ + 2; n < nn; n++, j += 2)x[j] = K_ * y[j];- }- // step 1 & 3- for (j = offset - 2, n = len + 3; n--; j += 2) {- x[j] = K * y[j] -- delta * (x[j - 1] + x[j + 1]);- }+ // step 3+ var j = offset_ - 2;+ for (var n = i0_ - 1, nn = i1_ + 2; n < nn; n++, j += 2)+ x[j] -= delta * (x[j - 1] + x[j + 1]);// step 4- for (j = offset - 1, n = len + 2; n--; j += 2) {+ var j = offset_ - 1;+ for (var n = i0_ - 1, nn = i1_ + 1; n < nn; n++, j += 2)x[j] -= gamma * (x[j - 1] + x[j + 1]);- }// step 5- for (j = offset, n = len + 1; n--; j += 2) {+ var j = offset_;+ for (var n = i0_, nn = i1_ + 1; n < nn; n++, j += 2)x[j] -= beta * (x[j - 1] + x[j + 1]);- }// step 6- for (j = offset + 1, n = len; n--; j += 2) {+ var j = offset_ + 1;+ for (var n = i0_, nn = i1_; n < nn; n++, j += 2)x[j] -= alpha * (x[j - 1] + x[j + 1]);- }};return IrreversibleTransform;@@ -39604,17 +39261,15 @@ var JpxImage = (function JpxImageClosure() {ReversibleTransform.prototype = Object.create(Transform.prototype);ReversibleTransform.prototype.filter =function reversibleTransformFilter(y, offset, length, i0, x) {- var len = length >> 1;- offset = offset | 0;- var j, n;+ var i0_ = Math.floor(i0 / 2);+ var i1_ = Math.floor((i0 + length) / 2);+ var offset_ = offset - (i0 % 1);- for (j = offset, n = len + 1; n--; j += 2) {- x[j] = y[j] - ((y[j - 1] + y[j + 1] + 2) >> 2);- }+ for (var n = i0_, nn = i1_ + 1, j = offset_; n < nn; n++, j += 2)+ x[j] = y[j] - Math.floor((y[j - 1] + y[j + 1] + 2) / 4);- for (j = offset + 1, n = len; n--; j += 2) {- x[j] = y[j] + ((x[j - 1] + x[j + 1]) >> 1);- }+ for (var n = i0_, nn = i1_, j = offset_ + 1; n < nn; n++, j += 2)+ x[j] = y[j] + Math.floor((x[j - 1] + x[j + 1]) / 2);};return ReversibleTransform;@@ -39626,15 +39281,178 @@ var JpxImage = (function JpxImageClosure() {var Jbig2Image = (function Jbig2ImageClosure() {++ // Annex E. Arithmetic Coding+ var ArithmeticDecoder = (function ArithmeticDecoderClosure() {+ var QeTable = [+ {qe: 0x5601, nmps: 1, nlps: 1, switchFlag: 1},+ {qe: 0x3401, nmps: 2, nlps: 6, switchFlag: 0},+ {qe: 0x1801, nmps: 3, nlps: 9, switchFlag: 0},+ {qe: 0x0AC1, nmps: 4, nlps: 12, switchFlag: 0},+ {qe: 0x0521, nmps: 5, nlps: 29, switchFlag: 0},+ {qe: 0x0221, nmps: 38, nlps: 33, switchFlag: 0},+ {qe: 0x5601, nmps: 7, nlps: 6, switchFlag: 1},+ {qe: 0x5401, nmps: 8, nlps: 14, switchFlag: 0},+ {qe: 0x4801, nmps: 9, nlps: 14, switchFlag: 0},+ {qe: 0x3801, nmps: 10, nlps: 14, switchFlag: 0},+ {qe: 0x3001, nmps: 11, nlps: 17, switchFlag: 0},+ {qe: 0x2401, nmps: 12, nlps: 18, switchFlag: 0},+ {qe: 0x1C01, nmps: 13, nlps: 20, switchFlag: 0},+ {qe: 0x1601, nmps: 29, nlps: 21, switchFlag: 0},+ {qe: 0x5601, nmps: 15, nlps: 14, switchFlag: 1},+ {qe: 0x5401, nmps: 16, nlps: 14, switchFlag: 0},+ {qe: 0x5101, nmps: 17, nlps: 15, switchFlag: 0},+ {qe: 0x4801, nmps: 18, nlps: 16, switchFlag: 0},+ {qe: 0x3801, nmps: 19, nlps: 17, switchFlag: 0},+ {qe: 0x3401, nmps: 20, nlps: 18, switchFlag: 0},+ {qe: 0x3001, nmps: 21, nlps: 19, switchFlag: 0},+ {qe: 0x2801, nmps: 22, nlps: 19, switchFlag: 0},+ {qe: 0x2401, nmps: 23, nlps: 20, switchFlag: 0},+ {qe: 0x2201, nmps: 24, nlps: 21, switchFlag: 0},+ {qe: 0x1C01, nmps: 25, nlps: 22, switchFlag: 0},+ {qe: 0x1801, nmps: 26, nlps: 23, switchFlag: 0},+ {qe: 0x1601, nmps: 27, nlps: 24, switchFlag: 0},+ {qe: 0x1401, nmps: 28, nlps: 25, switchFlag: 0},+ {qe: 0x1201, nmps: 29, nlps: 26, switchFlag: 0},+ {qe: 0x1101, nmps: 30, nlps: 27, switchFlag: 0},+ {qe: 0x0AC1, nmps: 31, nlps: 28, switchFlag: 0},+ {qe: 0x09C1, nmps: 32, nlps: 29, switchFlag: 0},+ {qe: 0x08A1, nmps: 33, nlps: 30, switchFlag: 0},+ {qe: 0x0521, nmps: 34, nlps: 31, switchFlag: 0},+ {qe: 0x0441, nmps: 35, nlps: 32, switchFlag: 0},+ {qe: 0x02A1, nmps: 36, nlps: 33, switchFlag: 0},+ {qe: 0x0221, nmps: 37, nlps: 34, switchFlag: 0},+ {qe: 0x0141, nmps: 38, nlps: 35, switchFlag: 0},+ {qe: 0x0111, nmps: 39, nlps: 36, switchFlag: 0},+ {qe: 0x0085, nmps: 40, nlps: 37, switchFlag: 0},+ {qe: 0x0049, nmps: 41, nlps: 38, switchFlag: 0},+ {qe: 0x0025, nmps: 42, nlps: 39, switchFlag: 0},+ {qe: 0x0015, nmps: 43, nlps: 40, switchFlag: 0},+ {qe: 0x0009, nmps: 44, nlps: 41, switchFlag: 0},+ {qe: 0x0005, nmps: 45, nlps: 42, switchFlag: 0},+ {qe: 0x0001, nmps: 45, nlps: 43, switchFlag: 0},+ {qe: 0x5601, nmps: 46, nlps: 46, switchFlag: 0}+ ];++ function ArithmeticDecoder(data, start, end) {+ this.data = data;+ this.bp = start;+ this.dataEnd = end;++ this.chigh = data[start];+ this.clow = 0;++ this.byteIn();++ this.chigh = ((this.chigh << 7) & 0xFFFF) | ((this.clow >> 9) & 0x7F);+ this.clow = (this.clow << 7) & 0xFFFF;+ this.ct -= 7;+ this.a = 0x8000;+ }++ ArithmeticDecoder.prototype = {+ byteIn: function ArithmeticDecoder_byteIn() {+ var data = this.data;+ var bp = this.bp;+ if (data[bp] == 0xFF) {+ var b1 = data[bp + 1];+ if (b1 > 0x8F) {+ this.clow += 0xFF00;+ this.ct = 8;+ } else {+ bp++;+ this.clow += (data[bp] << 9);+ this.ct = 7;+ this.bp = bp;+ }+ } else {+ bp++;+ this.clow += bp < this.dataEnd ? (data[bp] << 8) : 0xFF00;+ this.ct = 8;+ this.bp = bp;+ }+ if (this.clow > 0xFFFF) {+ this.chigh += (this.clow >> 16);+ this.clow &= 0xFFFF;+ }+ },+ readBit: function ArithmeticDecoder_readBit(cx) {+ var qeIcx = QeTable[cx.index].qe;+ this.a -= qeIcx;++ if (this.chigh < qeIcx) {+ var d = this.exchangeLps(cx);+ this.renormD();+ return d;+ } else {+ this.chigh -= qeIcx;+ if ((this.a & 0x8000) === 0) {+ var d = this.exchangeMps(cx);+ this.renormD();+ return d;+ } else {+ return cx.mps;+ }+ }+ },+ renormD: function ArithmeticDecoder_renormD() {+ do {+ if (this.ct === 0)+ this.byteIn();++ this.a <<= 1;+ this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);+ this.clow = (this.clow << 1) & 0xFFFF;+ this.ct--;+ } while ((this.a & 0x8000) === 0);+ },+ exchangeMps: function ArithmeticDecoder_exchangeMps(cx) {+ var d;+ var qeTableIcx = QeTable[cx.index];+ if (this.a < qeTableIcx.qe) {+ d = 1 - cx.mps;++ if (qeTableIcx.switchFlag == 1) {+ cx.mps = 1 - cx.mps;+ }+ cx.index = qeTableIcx.nlps;+ } else {+ d = cx.mps;+ cx.index = qeTableIcx.nmps;+ }+ return d;+ },+ exchangeLps: function ArithmeticDecoder_exchangeLps(cx) {+ var d;+ var qeTableIcx = QeTable[cx.index];+ if (this.a < qeTableIcx.qe) {+ this.a = qeTableIcx.qe;+ d = cx.mps;+ cx.index = qeTableIcx.nmps;+ } else {+ this.a = qeTableIcx.qe;+ d = 1 - cx.mps;++ if (qeTableIcx.switchFlag == 1) {+ cx.mps = 1 - cx.mps;+ }+ cx.index = qeTableIcx.nlps;+ }+ return d;+ }+ };++ return ArithmeticDecoder;+ })();+// Utility data structuresfunction ContextCache() {}ContextCache.prototype = {getContexts: function(id) {- if (id in this) {+ if (id in this)return this[id];- }- return (this[id] = new Int8Array(1<<16));+ return (this[id] = []);}};@@ -39664,64 +39482,56 @@ var Jbig2Image = (function Jbig2ImageClosure() {var state = 1, v = 0, s;var toRead = 32, offset = 4436; // defaults for state 7while (state) {- var bit = decoder.readBit(contexts, prev);- prev = (prev < 256 ? (prev << 1) | bit :- (((prev << 1) | bit) & 511) | 256);+ var cx = contexts[prev];+ if (!cx)+ contexts[prev] = cx = {index: 0, mps: 0};+ var bit = decoder.readBit(cx);+ prev = prev < 256 ? (prev << 1) | bit :+ (((prev << 1) | bit) & 511) | 256;switch (state) {case 1:s = !!bit;break;case 2:- if (bit) {- break;- }+ if (bit) break;state = 7;toRead = 2;offset = 0;break;case 3:- if (bit) {- break;- }+ if (bit) break;state = 7;toRead = 4;offset = 4;break;case 4:- if (bit) {- break;- }+ if (bit) break;state = 7;toRead = 6;offset = 20;break;case 5:- if (bit) {- break;- }+ if (bit) break;state = 7;toRead = 8;offset = 84;break;case 6:- if (bit) {- break;- }+ if (bit) break;state = 7;toRead = 12;offset = 340;break;default:- v = ((v << 1) | bit) >>> 0;- if (--toRead === 0) {+ v = v * 2 + bit;+ if (--toRead === 0)state = 0;- }continue;}state++;}v += offset;- return (!s ? v : (v > 0 ? -v : null));+ return !s ? v : v > 0 ? -v : null;}// A.3 The IAID decoding procedure@@ -39730,13 +39540,16 @@ var Jbig2Image = (function Jbig2ImageClosure() {var prev = 1;for (var i = 0; i < codeLength; i++) {- var bit = decoder.readBit(contexts, prev);- prev = (prev << 1) | bit;+ var cx = contexts[prev];+ if (!cx)+ contexts[prev] = cx = {index: 0, mps: 0};+ var bit = decoder.readBit(cx);+ prev = (prev * 2) + bit;}- if (codeLength < 31) {+ if (codeLength < 31)return prev & ((1 << codeLength) - 1);- }- return prev & 0x7FFFFFFF;+ else+ return prev - Math.pow(2, codeLength);}// 7.3 Segment types@@ -39825,118 +39638,57 @@ var Jbig2Image = (function Jbig2ImageClosure() {// 6.2 Generic Region Decoding Procedurefunction decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at,decodingContext) {- if (mmr) {+ if (mmr)error('JBIG2 error: MMR encoding is not supported');- }var useskip = !!skip;var template = CodingTemplates[templateIndex].concat(at);-- // Sorting is non-standard, and it is not required. But sorting increases- // the number of template bits that can be reused from the previous- // contextLabel in the main loop.- template.sort(function (a, b) {- return (a.y - b.y) || (a.x - b.x);- });-var templateLength = template.length;- var templateX = new Int8Array(templateLength);- var templateY = new Int8Array(templateLength);- var changingTemplateEntries = [];- var reuseMask = 0, minX = 0, maxX = 0, minY = 0;- var c, k;-- for (k = 0; k < templateLength; k++) {+ var templateX = new Int32Array(templateLength);+ var templateY = new Int32Array(templateLength);+ for (var k = 0; k < templateLength; k++) {templateX[k] = template[k].x;templateY[k] = template[k].y;- minX = Math.min(minX, template[k].x);- maxX = Math.max(maxX, template[k].x);- minY = Math.min(minY, template[k].y);- // Check if the template pixel appears in two consecutive context labels,- // so it can be reused. Otherwise, we add it to the list of changing- // template entries.- if (k < templateLength - 1 &&- template[k].y === template[k + 1].y &&- template[k].x === template[k + 1].x - 1) {- reuseMask |= 1 << (templateLength - 1 - k);- } else {- changingTemplateEntries.push(k);- }}- var changingEntriesLength = changingTemplateEntries.length;-- var changingTemplateX = new Int8Array(changingEntriesLength);- var changingTemplateY = new Int8Array(changingEntriesLength);- var changingTemplateBit = new Uint16Array(changingEntriesLength);- for (c = 0; c < changingEntriesLength; c++) {- k = changingTemplateEntries[c];- changingTemplateX[c] = template[k].x;- changingTemplateY[c] = template[k].y;- changingTemplateBit[c] = 1 << (templateLength - 1 - k);- }-- // Get the safe bounding box edges from the width, height, minX, maxX, minY- var sbb_left = -minX;- var sbb_top = -minY;- var sbb_right = width - maxX;var pseudoPixelContext = ReusedContexts[templateIndex];- var row = new Uint8Array(width);var bitmap = [];var decoder = decodingContext.decoder;var contexts = decodingContext.contextCache.getContexts('GB');- var ltp = 0, j, i0, j0, contextLabel = 0, bit, shift;+ var ltp = 0;for (var i = 0; i < height; i++) {if (prediction) {- var sltp = decoder.readBit(contexts, pseudoPixelContext);+ var cx = contexts[pseudoPixelContext];+ if (!cx)+ contexts[pseudoPixelContext] = cx = {index: 0, mps: 0};+ var sltp = decoder.readBit(cx);ltp ^= sltp;- if (ltp) {- bitmap.push(row); // duplicate previous row- continue;- }}- row = new Uint8Array(row);+ if (ltp) {+ bitmap.push(bitmap[bitmap.length - 1]); // duplicate previous row+ continue;+ }+ var row = new Uint8Array(width);bitmap.push(row);- for (j = 0; j < width; j++) {+ for (var j = 0; j < width; j++) {if (useskip && skip[i][j]) {row[j] = 0;continue;}- // Are we in the middle of a scanline, so we can reuse contextLabel- // bits?- if (j >= sbb_left && j < sbb_right && i >= sbb_top) {- // If yes, we can just shift the bits that are reusable and only- // fetch the remaining ones.- contextLabel = (contextLabel << 1) & reuseMask;- for (k = 0; k < changingEntriesLength; k++) {- i0 = i + changingTemplateY[k];- j0 = j + changingTemplateX[k];- bit = bitmap[i0][j0];- if (bit) {- bit = changingTemplateBit[k];- contextLabel |= bit;- }- }- } else {- // compute the contextLabel from scratch- contextLabel = 0;- shift = templateLength - 1;- for (k = 0; k < templateLength; k++, shift--) {- j0 = j + templateX[k];- if (j0 >= 0 && j0 < width) {- i0 = i + templateY[k];- if (i0 >= 0) {- bit = bitmap[i0][j0];- if (bit) {- contextLabel |= bit << shift;- }- }- }- }+ var contextLabel = 0;+ for (var k = 0; k < templateLength; k++) {+ var i0 = i + templateY[k], j0 = j + templateX[k];+ if (i0 < 0 || j0 < 0 || j0 >= width)+ contextLabel <<= 1; // out of bound pixel+ else+ contextLabel = (contextLabel << 1) | bitmap[i0][j0];}- var pixel = decoder.readBit(contexts, contextLabel);+ var cx = contexts[contextLabel];+ if (!cx)+ contexts[contextLabel] = cx = {index: 0, mps: 0};+ var pixel = decoder.readBit(cx);row[j] = pixel;}}@@ -39948,26 +39700,22 @@ var Jbig2Image = (function Jbig2ImageClosure() {offsetX, offsetY, prediction, at,decodingContext) {var codingTemplate = RefinementTemplates[templateIndex].coding;- if (templateIndex === 0) {+ if (templateIndex === 0)codingTemplate = codingTemplate.concat([at[0]]);- }var codingTemplateLength = codingTemplate.length;var codingTemplateX = new Int32Array(codingTemplateLength);var codingTemplateY = new Int32Array(codingTemplateLength);- var k;- for (k = 0; k < codingTemplateLength; k++) {+ for (var k = 0; k < codingTemplateLength; k++) {codingTemplateX[k] = codingTemplate[k].x;codingTemplateY[k] = codingTemplate[k].y;}-var referenceTemplate = RefinementTemplates[templateIndex].reference;- if (templateIndex === 0) {+ if (templateIndex === 0)referenceTemplate = referenceTemplate.concat([at[1]]);- }var referenceTemplateLength = referenceTemplate.length;var referenceTemplateX = new Int32Array(referenceTemplateLength);var referenceTemplateY = new Int32Array(referenceTemplateLength);- for (k = 0; k < referenceTemplateLength; k++) {+ for (var k = 0; k < referenceTemplateLength; k++) {referenceTemplateX[k] = referenceTemplate[k].x;referenceTemplateY[k] = referenceTemplate[k].y;}@@ -39983,37 +39731,38 @@ var Jbig2Image = (function Jbig2ImageClosure() {var ltp = 0;for (var i = 0; i < height; i++) {if (prediction) {- var sltp = decoder.readBit(contexts, pseudoPixelContext);+ var cx = contexts[pseudoPixelContext];+ if (!cx)+ contexts[pseudoPixelContext] = cx = {index: 0, mps: 0};+ var sltp = decoder.readBit(cx);ltp ^= sltp;- if (ltp) {- error('JBIG2 error: prediction is not supported');- }}var row = new Uint8Array(width);bitmap.push(row);for (var j = 0; j < width; j++) {- var i0, j0;+ if (ltp)+ error('JBIG2 error: prediction is not supported');+var contextLabel = 0;- for (k = 0; k < codingTemplateLength; k++) {- i0 = i + codingTemplateY[k];- j0 = j + codingTemplateX[k];- if (i0 < 0 || j0 < 0 || j0 >= width) {+ for (var k = 0; k < codingTemplateLength; k++) {+ var i0 = i + codingTemplateY[k], j0 = j + codingTemplateX[k];+ if (i0 < 0 || j0 < 0 || j0 >= width)contextLabel <<= 1; // out of bound pixel- } else {+ elsecontextLabel = (contextLabel << 1) | bitmap[i0][j0];- }}- for (k = 0; k < referenceTemplateLength; k++) {- i0 = i + referenceTemplateY[k] + offsetY;- j0 = j + referenceTemplateX[k] + offsetX;- if (i0 < 0 || i0 >= referenceHeight || j0 < 0 ||- j0 >= referenceWidth) {+ for (var k = 0; k < referenceTemplateLength; k++) {+ var i0 = i + referenceTemplateY[k] + offsetY;+ var j0 = j + referenceTemplateX[k] + offsetX;+ if (i0 < 0 || i0 >= referenceHeight || j0 < 0 || j0 >= referenceWidth)contextLabel <<= 1; // out of bound pixel- } else {+ elsecontextLabel = (contextLabel << 1) | referenceBitmap[i0][j0];- }}- var pixel = decoder.readBit(contexts, contextLabel);+ var cx = contexts[contextLabel];+ if (!cx)+ contexts[contextLabel] = cx = {index: 0, mps: 0};+ var pixel = decoder.readBit(cx);row[j] = pixel;}}@@ -40027,9 +39776,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {huffmanTables, templateIndex, at,refinementTemplateIndex, refinementAt,decodingContext) {- if (huffman) {+ if (huffman)error('JBIG2 error: huffman is not supported');- }var newSymbols = [];var currentHeight = 0;@@ -40045,38 +39793,24 @@ var Jbig2Image = (function Jbig2ImageClosure() {var totalWidth = 0;while (true) {var deltaWidth = decodeInteger(contextCache, 'IADW', decoder); // 6.5.7- if (deltaWidth === null) {+ if (deltaWidth === null)break; // OOB- }currentWidth += deltaWidth;totalWidth += currentWidth;var bitmap;if (refinement) {// 6.5.8.2 Refinement/aggregate-coded symbol bitmapvar numberOfInstances = decodeInteger(contextCache, 'IAAI', decoder);- if (numberOfInstances > 1) {- bitmap = decodeTextRegion(huffman, refinement,- currentWidth, currentHeight, 0,- numberOfInstances, 1, //strip size- symbols.concat(newSymbols),- symbolCodeLength,- 0, //transposed- 0, //ds offset- 1, //top left 7.4.3.1.1- 0, //OR operator- huffmanTables,- refinementTemplateIndex, refinementAt,- decodingContext);- } else {- var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);- var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3- var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4- var symbol = (symbolId < symbols.length ? symbols[symbolId] :- newSymbols[symbolId - symbols.length]);- bitmap = decodeRefinement(currentWidth, currentHeight,+ if (numberOfInstances > 1)+ error('JBIG2 error: number of instances > 1 is not supported');+ var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);+ var rdx = decodeInteger(contextCache, 'IARDX', decoder); // 6.4.11.3+ var rdy = decodeInteger(contextCache, 'IARDY', decoder); // 6.4.11.4+ var symbol = symbolId < symbols.length ? symbols[symbolId] :+ newSymbols[symbolId - symbols.length];+ bitmap = decodeRefinement(currentWidth, currentHeight,refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt,decodingContext);- }} else {// 6.5.8.1 Direct-coded symbol bitmapbitmap = decodeBitmap(false, currentWidth, currentHeight,@@ -40091,21 +39825,14 @@ var Jbig2Image = (function Jbig2ImageClosure() {var totalSymbolsLength = symbols.length + numberOfNewSymbols;while (flags.length < totalSymbolsLength) {var runLength = decodeInteger(contextCache, 'IAEX', decoder);- while (runLength--) {+ while (runLength--)flags.push(currentFlag);- }currentFlag = !currentFlag;}- for (var i = 0, ii = symbols.length; i < ii; i++) {- if (flags[i]) {- exportedSymbols.push(symbols[i]);- }- }- for (var j = 0; j < numberOfNewSymbols; i++, j++) {- if (flags[i]) {- exportedSymbols.push(newSymbols[j]);- }- }+ for (var i = 0, ii = symbols.length; i < ii; i++)+ if (flags[i]) exportedSymbols.push(symbols[i]);+ for (var j = 0; j < numberOfNewSymbols; i++, j++)+ if (flags[i]) exportedSymbols.push(newSymbols[j]);return exportedSymbols;}@@ -40116,28 +39843,29 @@ var Jbig2Image = (function Jbig2ImageClosure() {combinationOperator, huffmanTables,refinementTemplateIndex, refinementAt,decodingContext) {- if (huffman) {+ if (huffman)error('JBIG2 error: huffman is not supported');- }// Prepare bitmapvar bitmap = [];- var i, row;- for (i = 0; i < height; i++) {- row = new Uint8Array(width);+ for (var i = 0; i < height; i++) {+ var row = new Uint8Array(width);if (defaultPixelValue) {- for (var j = 0; j < width; j++) {+ for (var j = 0; j < width; j++)row[j] = defaultPixelValue;- }}bitmap.push(row);}var decoder = decodingContext.decoder;var contextCache = decodingContext.contextCache;++ if (transposed)+ error('JBIG2 error: transposed is not supported');+var stripT = -decodeInteger(contextCache, 'IADT', decoder); // 6.4.6var firstS = 0;- i = 0;+ var i = 0;while (i < numberOfSymbolInstances) {var deltaT = decodeInteger(contextCache, 'IADT', decoder); // 6.4.6stripT += deltaT;@@ -40146,12 +39874,12 @@ var Jbig2Image = (function Jbig2ImageClosure() {firstS += deltaFirstS;var currentS = firstS;do {- var currentT = (stripSize == 1 ? 0 :- decodeInteger(contextCache, 'IAIT', decoder)); // 6.4.9+ var currentT = stripSize == 1 ? 0 :+ decodeInteger(contextCache, 'IAIT', decoder); // 6.4.9var t = stripSize * stripT + currentT;var symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);- var applyRefinement = (refinement &&- decodeInteger(contextCache, 'IARI', decoder));+ var applyRefinement = refinement &&+ decodeInteger(contextCache, 'IARI', decoder);var symbolBitmap = inputSymbols[symbolId];var symbolWidth = symbolBitmap[0].length;var symbolHeight = symbolBitmap.length;@@ -40169,65 +39897,31 @@ var Jbig2Image = (function Jbig2ImageClosure() {}var offsetT = t - ((referenceCorner & 1) ? 0 : symbolHeight);var offsetS = currentS - ((referenceCorner & 2) ? symbolWidth : 0);- var s2, t2, symbolRow;- if (transposed) {- // Place Symbol Bitmap from T1,S1- for (s2 = 0; s2 < symbolHeight; s2++) {- row = bitmap[offsetS + s2];- if (!row) {- continue;- }- symbolRow = symbolBitmap[s2];- // To ignore Parts of Symbol bitmap which goes- // outside bitmap region- var maxWidth = Math.min(width - offsetT, symbolWidth);- switch (combinationOperator) {- case 0: // OR- for (t2 = 0; t2 < maxWidth; t2++) {- row[offsetT + t2] |= symbolRow[t2];- }- break;- case 2: // XOR- for (t2 = 0; t2 < maxWidth; t2++) {- row[offsetT + t2] ^= symbolRow[t2];- }- break;- default:- error('JBIG2 error: operator ' + combinationOperator +- ' is not supported');- }- }- currentS += symbolHeight - 1;- } else {- for (t2 = 0; t2 < symbolHeight; t2++) {- row = bitmap[offsetT + t2];- if (!row) {- continue;- }- symbolRow = symbolBitmap[t2];- switch (combinationOperator) {- case 0: // OR- for (s2 = 0; s2 < symbolWidth; s2++) {- row[offsetS + s2] |= symbolRow[s2];- }- break;- case 2: // XOR- for (s2 = 0; s2 < symbolWidth; s2++) {- row[offsetS + s2] ^= symbolRow[s2];- }- break;- default:- error('JBIG2 error: operator ' + combinationOperator +- ' is not supported');- }+ for (var t2 = 0; t2 < symbolHeight; t2++) {+ var row = bitmap[offsetT + t2];+ if (!row) continue;+ var symbolRow = symbolBitmap[t2];+ switch (combinationOperator) {+ case 0: // OR+ for (var s2 = 0; s2 < symbolWidth; s2++)+ row[offsetS + s2] |= symbolRow[s2];+ break;+ case 2: // XOR+ for (var s2 = 0; s2 < symbolWidth; s2++)+ row[offsetS + s2] ^= symbolRow[s2];+ break;+ default:+ error('JBIG2 error: operator ' + combinationOperator ++ ' is not supported');}- currentS += symbolWidth - 1;}++ currentS += symbolWidth - 1;i++;+var deltaS = decodeInteger(contextCache, 'IADS', decoder); // 6.4.8- if (deltaS === null) {+ if (deltaS === null)break; // OOB- }currentS += deltaS + dsOffset;} while (true);}@@ -40239,13 +39933,11 @@ var Jbig2Image = (function Jbig2ImageClosure() {segmentHeader.number = readUint32(data, start);var flags = data[start + 4];var segmentType = flags & 0x3F;- if (!SegmentTypes[segmentType]) {+ if (!SegmentTypes[segmentType])error('JBIG2 error: invalid segment type: ' + segmentType);- }segmentHeader.type = segmentType;segmentHeader.typeName = SegmentTypes[segmentType];segmentHeader.deferredNonRetain = !!(flags & 0x80);-var pageAssociationFieldSize = !!(flags & 0x40);var referredFlags = data[start + 5];var referredToCount = (referredFlags >> 5) & 7;@@ -40259,32 +39951,28 @@ var Jbig2Image = (function Jbig2ImageClosure() {while (--bytes > 0) {retainBits.push(data[position++]);}- } else if (referredFlags == 5 || referredFlags == 6) {+ } else if (referredFlags == 5 || referredFlags == 6)error('JBIG2 error: invalid referred-to flags');- }-segmentHeader.retainBits = retainBits;- var referredToSegmentNumberSize = (segmentHeader.number <= 256 ? 1 :- (segmentHeader.number <= 65536 ? 2 : 4));+ var referredToSegmentNumberSize = segmentHeader.number <= 256 ? 1 :+ segmentHeader.number <= 65536 ? 2 : 4;var referredTo = [];- var i, ii;- for (i = 0; i < referredToCount; i++) {- var number = (referredToSegmentNumberSize == 1 ? data[position] :- (referredToSegmentNumberSize == 2 ? readUint16(data, position) :- readUint32(data, position)));+ for (var i = 0; i < referredToCount; i++) {+ var number = referredToSegmentNumberSize == 1 ? data[position] :+ referredToSegmentNumberSize == 2 ? readUint16(data, position) :+ readUint32(data, position);referredTo.push(number);position += referredToSegmentNumberSize;}segmentHeader.referredTo = referredTo;- if (!pageAssociationFieldSize) {+ if (!pageAssociationFieldSize)segmentHeader.pageAssociation = data[position++];- } else {+ else {segmentHeader.pageAssociation = readUint32(data, position);position += 4;}segmentHeader.length = readUint32(data, position);position += 4;-if (segmentHeader.length == 0xFFFFFFFF) {// 7.2.7 Segment data length, unknown segment lengthif (segmentType === 38) { // ImmediateGenericRegion@@ -40303,7 +39991,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {searchPattern[3] = (genericRegionInfo.height >> 16) & 0xFF;searchPattern[4] = (genericRegionInfo.height >> 8) & 0xFF;searchPattern[5] = genericRegionInfo.height & 0xFF;- for (i = position, ii = data.length; i < ii; i++) {+ for (var i = position, ii = data.length; i < ii; i++) {var j = 0;while (j < searchPatternLength && searchPattern[j] === data[i + j]) {j++;@@ -40340,9 +40028,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {segment.end = position;}segments.push(segment);- if (segmentHeader.type == 51) {+ if (segmentHeader.type == 51)break; // end of file is found- }}if (header.randomAccess) {for (var i = 0, ii = segments.length; i < ii; i++) {@@ -40370,7 +40057,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {var header = segment.header;var data = segment.data, position = segment.start, end = segment.end;- var args, at, i, atLength;+ var args;switch (header.type) {case 0: // SymbolDictionary// 7.4.2 Symbol dictionary segment syntax@@ -40388,9 +40075,9 @@ var Jbig2Image = (function Jbig2ImageClosure() {dictionary.refinementTemplate = (dictionaryFlags >> 12) & 1;position += 2;if (!dictionary.huffman) {- atLength = dictionary.template === 0 ? 4 : 1;- at = [];- for (i = 0; i < atLength; i++) {+ var atLength = dictionary.template === 0 ? 4 : 1;+ var at = [];+ for (var i = 0; i < atLength; i++) {at.push({x: readInt8(data, position),y: readInt8(data, position + 1)@@ -40400,8 +40087,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {dictionary.at = at;}if (dictionary.refinement && !dictionary.refinementTemplate) {- at = [];- for (i = 0; i < 2; i++) {+ var at = [];+ for (var i = 0; i < 2; i++) {at.push({x: readInt8(data, position),y: readInt8(data, position + 1)@@ -40447,8 +40134,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {!!(textRegionHuffmanFlags & 14);}if (textRegion.refinement && !textRegion.refinementTemplate) {- at = [];- for (i = 0; i < 2; i++) {+ var at = [];+ for (var i = 0; i < 2; i++) {at.push({x: readInt8(data, position),y: readInt8(data, position + 1)@@ -40460,9 +40147,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {textRegion.numberOfSymbolInstances = readUint32(data, position);position += 4;// TODO 7.4.3.1.7 Symbol ID Huffman table decoding- if (textRegion.huffman) {+ if (textRegion.huffman)error('JBIG2 error: huffman is not supported');- }args = [textRegion, header.referredTo, data, position, end];break;case 38: // ImmediateGenericRegion@@ -40475,9 +40161,9 @@ var Jbig2Image = (function Jbig2ImageClosure() {genericRegion.template = (genericRegionSegmentFlags >> 1) & 3;genericRegion.prediction = !!(genericRegionSegmentFlags & 8);if (!genericRegion.mmr) {- atLength = genericRegion.template === 0 ? 4 : 1;- at = [];- for (i = 0; i < atLength; i++) {+ var atLength = genericRegion.template === 0 ? 4 : 1;+ var at = [];+ for (var i = 0; i < atLength; i++) {at.push({x: readInt8(data, position),y: readInt8(data, position + 1)@@ -40495,9 +40181,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {resolutionX: readUint32(data, position + 8),resolutionY: readUint32(data, position + 12)};- if (pageInfo.height == 0xFFFFFFFF) {+ if (pageInfo.height == 0xFFFFFFFF)delete pageInfo.height;- }var pageSegmentFlags = data[position + 16];var pageStripingInformatiom = readUint16(data, position + 17);pageInfo.lossless = !!(pageSegmentFlags & 1);@@ -40514,23 +40199,18 @@ var Jbig2Image = (function Jbig2ImageClosure() {break;case 51: // EndOfFilebreak;- case 62: // 7.4.15 defines 2 extension types which- // are comments and can be ignored.- break;default:error('JBIG2 error: segment type ' + header.typeName + '(' +header.type + ') is not implemented');}var callbackName = 'on' + header.typeName;- if (callbackName in visitor) {+ if (callbackName in visitor)visitor[callbackName].apply(visitor, args);- }}function processSegments(segments, visitor) {- for (var i = 0, ii = segments.length; i < ii; i++) {+ for (var i = 0, ii = segments.length; i < ii; i++)processSegment(segments[i], visitor);- }}function parseJbig2(data, start, end) {@@ -40538,9 +40218,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {if (data[position] != 0x97 || data[position + 1] != 0x4A ||data[position + 2] != 0x42 || data[position + 3] != 0x32 ||data[position + 4] != 0x0D || data[position + 5] != 0x0A ||- data[position + 6] != 0x1A || data[position + 7] != 0x0A) {+ data[position + 6] != 0x1A || data[position + 7] != 0x0A)error('JBIG2 error: invalid header');- }var header = {};position += 8;var flags = data[position++];@@ -40571,13 +40250,9 @@ var Jbig2Image = (function Jbig2ImageClosure() {this.currentPageInfo = info;var rowSize = (info.width + 7) >> 3;var buffer = new Uint8Array(rowSize * info.height);- // The contents of ArrayBuffers are initialized to 0.- // Fill the buffer with 0xFF only if info.defaultPixelValue is set- if (info.defaultPixelValue) {- for (var i = 0, ii = buffer.length; i < ii; i++) {- buffer[i] = 0xFF;- }- }+ var fill = info.defaultPixelValue ? 0xFF : 0;+ for (var i = 0, ii = buffer.length; i < ii; i++)+ buffer[i] = fill;this.buffer = buffer;},drawBitmap: function SimpleSegmentVisitor_drawBitmap(regionInfo, bitmap) {@@ -40587,47 +40262,34 @@ var Jbig2Image = (function Jbig2ImageClosure() {var combinationOperator = pageInfo.combinationOperatorOverride ?regionInfo.combinationOperator : pageInfo.combinationOperator;var buffer = this.buffer;- var mask0 = 128 >> (regionInfo.x & 7);- var offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);- var i, j, mask, offset;- switch (combinationOperator) {- case 0: // OR- for (i = 0; i < height; i++) {- mask = mask0;- offset = offset0;- for (j = 0; j < width; j++) {- if (bitmap[i][j]) {- buffer[offset] |= mask;- }+ for (var i = 0; i < height; i++) {+ var mask = 128 >> (regionInfo.x & 7);+ var offset = (i + regionInfo.y) * rowSize + (regionInfo.x >> 3);+ switch (combinationOperator) {+ case 0: // OR+ for (var j = 0; j < width; j++) {+ buffer[offset] |= bitmap[i][j] ? mask : 0;mask >>= 1;if (!mask) {mask = 128;offset++;}}- offset0 += rowSize;- }- break;- case 2: // XOR- for (i = 0; i < height; i++) {- mask = mask0;- offset = offset0;- for (j = 0; j < width; j++) {- if (bitmap[i][j]) {- buffer[offset] ^= mask;- }+ break;+ case 2: // XOR+ for (var j = 0; j < width; j++) {+ buffer[offset] ^= bitmap[i][j] ? mask : 0;mask >>= 1;if (!mask) {mask = 128;offset++;}}- offset0 += rowSize;- }- break;- default:- error('JBIG2 error: operator ' + combinationOperator +- ' is not supported');+ break;+ default:+ error('JBIG2 error: operator ' + combinationOperator ++ ' is not supported');+ }}},onImmediateGenericRegion:@@ -40650,20 +40312,17 @@ var Jbig2Image = (function Jbig2ImageClosure() {referredSegments,data, start, end) {var huffmanTables;- if (dictionary.huffman) {+ if (dictionary.huffman)error('JBIG2 error: huffman is not supported');- }// Combines exported symbols from all referred segmentsvar symbols = this.symbols;- if (!symbols) {+ if (!symbols)this.symbols = symbols = {};- }var inputSymbols = [];- for (var i = 0, ii = referredSegments.length; i < ii; i++) {+ for (var i = 0, ii = referredSegments.length; i < ii; i++)inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);- }var decodingContext = new DecodingContext(data, start, end);symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman,@@ -40683,9 +40342,8 @@ var Jbig2Image = (function Jbig2ImageClosure() {// Combines exported symbols from all referred segmentsvar symbols = this.symbols;var inputSymbols = [];- for (var i = 0, ii = referredSegments.length; i < ii; i++) {+ for (var i = 0, ii = referredSegments.length; i < ii; i++)inputSymbols = inputSymbols.concat(symbols[referredSegments[i]]);- }var symbolCodeLength = log2(inputSymbols.length);var decodingContext = new DecodingContext(data, start, end);@@ -40699,7 +40357,7 @@ var Jbig2Image = (function Jbig2ImageClosure() {},onImmediateLosslessTextRegion:function SimpleSegmentVisitor_onImmediateLosslessTextRegion() {- this.onImmediateTextRegion.apply(this, arguments);+ this.onImmediateTextRegion.apply(this, arguments);}};@@ -40774,10 +40432,10 @@ var bidi = PDFJS.bidi = (function bidiClosure() {}function findUnequal(arr, start, value) {+ var j;for (var j = start, jj = arr.length; j < jj; ++j) {- if (arr[j] != value) {+ if (arr[j] != value)return j;- }}return j;}@@ -40836,58 +40494,51 @@ var bidi = PDFJS.bidi = (function bidiClosure() {}}- function createBidiText(str, isLTR, vertical) {- return {- str: str,- dir: (vertical ? 'ttb' : (isLTR ? 'ltr' : 'rtl'))- };+ function BidiResult(str, isLTR, vertical) {+ this.str = str;+ this.dir = vertical ? 'ttb' : isLTR ? 'ltr' : 'rtl';}- // These are used in bidi(), which is called frequently. We re-use them on- // each call to avoid unnecessary allocations.- var chars = [];- var types = [];-function bidi(str, startLevel, vertical) {var isLTR = true;var strLength = str.length;- if (strLength === 0 || vertical) {- return createBidiText(str, isLTR, vertical);- }+ if (strLength === 0 || vertical)+ return new BidiResult(str, isLTR, vertical);- // Get types and fill arrays- chars.length = 0;- types.length = 0;+ // get types, fill arrays++ var chars = [];+ var types = [];+ var oldtypes = [];var numBidi = 0;- var i, ii;- for (i = 0; i < strLength; ++i) {+ for (var i = 0; i < strLength; ++i) {chars[i] = str.charAt(i);var charCode = str.charCodeAt(i);var charType = 'L';- if (charCode <= 0x00ff) {+ if (charCode <= 0x00ff)charType = baseTypes[charCode];- } else if (0x0590 <= charCode && charCode <= 0x05f4) {+ else if (0x0590 <= charCode && charCode <= 0x05f4)charType = 'R';- } else if (0x0600 <= charCode && charCode <= 0x06ff) {+ else if (0x0600 <= charCode && charCode <= 0x06ff)charType = arabicTypes[charCode & 0xff];- } else if (0x0700 <= charCode && charCode <= 0x08AC) {+ else if (0x0700 <= charCode && charCode <= 0x08AC)charType = 'AL';- }- if (charType == 'R' || charType == 'AL' || charType == 'AN') {++ if (charType == 'R' || charType == 'AL' || charType == 'AN')numBidi++;- }- types[i] = charType;++ oldtypes[i] = types[i] = charType;}- // Detect the bidi method- // - If there are no rtl characters then no bidi needed- // - If less than 30% chars are rtl then string is primarily ltr- // - If more than 30% chars are rtl then string is primarily rtl+ // detect the bidi method+ // if there are no rtl characters then no bidi needed+ // if less than 30% chars are rtl then string is primarily ltr+ // if more than 30% chars are rtl then string is primarily rtlif (numBidi === 0) {isLTR = true;- return createBidiText(str, isLTR);+ return new BidiResult(str, isLTR);}if (startLevel == -1) {@@ -40901,14 +40552,16 @@ var bidi = PDFJS.bidi = (function bidiClosure() {}var levels = [];- for (i = 0; i < strLength; ++i) {++ for (var i = 0; i < strLength; ++i) {levels[i] = startLevel;}/*X1-X10: skip most of this, since we are NOT doing the embeddings.*/- var e = (isOdd(startLevel) ? 'R' : 'L');++ var e = isOdd(startLevel) ? 'R' : 'L';var sor = e;var eor = sor;@@ -40917,13 +40570,13 @@ var bidi = PDFJS.bidi = (function bidiClosure() {type of the NSM to the type of the previous character. If the NSM is at thestart of the level run, it will get the type of sor.*/+var lastType = sor;- for (i = 0; i < strLength; ++i) {- if (types[i] == 'NSM') {+ for (var i = 0; i < strLength; ++i) {+ if (types[i] == 'NSM')types[i] = lastType;- } else {+ elselastType = types[i];- }}/*@@ -40931,25 +40584,24 @@ var bidi = PDFJS.bidi = (function bidiClosure() {first strong type (R, L, AL, or sor) is found. If an AL is found, changethe type of the European number to Arabic number.*/- lastType = sor;- var t;- for (i = 0; i < strLength; ++i) {- t = types[i];- if (t == 'EN') {++ var lastType = sor;+ for (var i = 0; i < strLength; ++i) {+ var t = types[i];+ if (t == 'EN')types[i] = (lastType == 'AL') ? 'AN' : 'EN';- } else if (t == 'R' || t == 'L' || t == 'AL') {+ else if (t == 'R' || t == 'L' || t == 'AL')lastType = t;- }}/*W3. Change all ALs to R.*/- for (i = 0; i < strLength; ++i) {- t = types[i];- if (t == 'AL') {++ for (var i = 0; i < strLength; ++i) {+ var t = types[i];+ if (t == 'AL')types[i] = 'R';- }}/*@@ -40957,35 +40609,32 @@ var bidi = PDFJS.bidi = (function bidiClosure() {European number. A single common separator between two numbers of the sametype changes to that type:*/- for (i = 1; i < strLength - 1; ++i) {- if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN') {++ for (var i = 1; i < strLength - 1; ++i) {+ if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN')types[i] = 'EN';- }if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') &&- types[i + 1] == types[i - 1]) {+ types[i + 1] == types[i - 1])types[i] = types[i - 1];- }}/*W5. A sequence of European terminators adjacent to European numbers changesto all European numbers:*/- for (i = 0; i < strLength; ++i) {++ for (var i = 0; i < strLength; ++i) {if (types[i] == 'EN') {// do before- var j;- for (j = i - 1; j >= 0; --j) {- if (types[j] != 'ET') {+ for (var j = i - 1; j >= 0; --j) {+ if (types[j] != 'ET')break;- }types[j] = 'EN';}// do after- for (j = i + 1; j < strLength; --j) {- if (types[j] != 'ET') {+ for (var j = i + 1; j < strLength; --j) {+ if (types[j] != 'ET')break;- }types[j] = 'EN';}}@@ -40994,11 +40643,11 @@ var bidi = PDFJS.bidi = (function bidiClosure() {/*W6. Otherwise, separators and terminators change to Other Neutral:*/- for (i = 0; i < strLength; ++i) {- t = types[i];- if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS') {++ for (var i = 0; i < strLength; ++i) {+ var t = types[i];+ if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS')types[i] = 'ON';- }}/*@@ -41006,14 +40655,14 @@ var bidi = PDFJS.bidi = (function bidiClosure() {first strong type (R, L, or sor) is found. If an L is found, then changethe type of the European number to L.*/- lastType = sor;- for (i = 0; i < strLength; ++i) {- t = types[i];- if (t == 'EN') {- types[i] = ((lastType == 'L') ? 'L' : 'EN');- } else if (t == 'R' || t == 'L') {++ var lastType = sor;+ for (var i = 0; i < strLength; ++i) {+ var t = types[i];+ if (t == 'EN')+ types[i] = (lastType == 'L') ? 'L' : 'EN';+ else if (t == 'R' || t == 'L')lastType = t;- }}/*@@ -41022,27 +40671,22 @@ var bidi = PDFJS.bidi = (function bidiClosure() {numbers are treated as though they were R. Start-of-level-run (sor) andend-of-level-run (eor) are used at level run boundaries.*/- for (i = 0; i < strLength; ++i) {++ for (var i = 0; i < strLength; ++i) {if (types[i] == 'ON') {var end = findUnequal(types, i + 1, 'ON');var before = sor;- if (i > 0) {+ if (i > 0)before = types[i - 1];- }-var after = eor;- if (end + 1 < strLength) {+ if (end + 1 < strLength)after = types[end + 1];- }- if (before != 'L') {+ if (before != 'L')before = 'R';- }- if (after != 'L') {+ if (after != 'L')after = 'R';- }- if (before == after) {+ if (before == after)setValues(types, i, end, before);- }i = end - 1; // reset to end (-1 so next iteration is ok)}}@@ -41050,10 +40694,10 @@ var bidi = PDFJS.bidi = (function bidiClosure() {/*N2. Any remaining neutrals take the embedding direction.*/- for (i = 0; i < strLength; ++i) {- if (types[i] == 'ON') {++ for (var i = 0; i < strLength; ++i) {+ if (types[i] == 'ON')types[i] = e;- }}/*@@ -41063,15 +40707,16 @@ var bidi = PDFJS.bidi = (function bidiClosure() {I2. For all characters with an odd (right-to-left) embedding direction,those of type L, EN or AN go up one level.*/- for (i = 0; i < strLength; ++i) {- t = types[i];++ for (var i = 0; i < strLength; ++i) {+ var t = types[i];if (isEven(levels[i])) {if (t == 'R') {levels[i] += 1;} else if (t == 'AN' || t == 'EN') {levels[i] += 2;}- } else { // isOdd+ } else { // isOdd, soif (t == 'L' || t == 'AN' || t == 'EN') {levels[i] += 1;}@@ -41098,24 +40743,23 @@ var bidi = PDFJS.bidi = (function bidiClosure() {*/// find highest level & lowest odd level+var highestLevel = -1;var lowestOddLevel = 99;- var level;- for (i = 0, ii = levels.length; i < ii; ++i) {- level = levels[i];- if (highestLevel < level) {+ for (var i = 0, ii = levels.length; i < ii; ++i) {+ var level = levels[i];+ if (highestLevel < level)highestLevel = level;- }- if (lowestOddLevel > level && isOdd(level)) {+ if (lowestOddLevel > level && isOdd(level))lowestOddLevel = level;- }}// now reverse between those limits- for (level = highestLevel; level >= lowestOddLevel; --level) {++ for (var level = highestLevel; level >= lowestOddLevel; --level) {// find segments to reversevar start = -1;- for (i = 0, ii = levels.length; i < ii; ++i) {+ for (var i = 0, ii = levels.length; i < ii; ++i) {if (levels[i] < level) {if (start >= 0) {reverseValues(chars, start, i);@@ -41148,175 +40792,98 @@ var bidi = PDFJS.bidi = (function bidiClosure() {// don't mirror as characters are already mirrored in the pdf// Finally, return string+var result = '';- for (i = 0, ii = chars.length; i < ii; ++i) {+ for (var i = 0, ii = chars.length; i < ii; ++i) {var ch = chars[i];- if (ch != '<' && ch != '>') {+ if (ch != '<' && ch != '>')result += ch;- }}- return createBidiText(result, isLTR);++ return new BidiResult(result, isLTR);}return bidi;})();-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */-/* Copyright 2014 Opera Software ASA- *- * 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.- *- *- * Based on https://code.google.com/p/smhasher/wiki/MurmurHash3.- * Hashes roughly 100 KB per millisecond on i7 3.4 GHz.- */-/* globals Uint32ArrayView */+var Metadata = PDFJS.Metadata = (function MetadataClosure() {+ function fixMetadata(meta) {+ return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {+ var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,+ function(code, d1, d2, d3) {+ return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);+ });+ var chars = '';+ for (var i = 0; i < bytes.length; i += 2) {+ var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);+ chars += code >= 32 && code < 127 && code != 60 && code != 62 &&+ code != 38 && false ? String.fromCharCode(code) :+ '&#x' + (0x10000 + code).toString(16).substring(1) + ';';+ }+ return '>' + chars;+ });+ }-'use strict';+ function Metadata(meta) {+ if (typeof meta === 'string') {+ // Ghostscript produces invalid metadata+ meta = fixMetadata(meta);-var MurmurHash3_64 = (function MurmurHash3_64Closure (seed) {- // Workaround for missing math precison in JS.- var MASK_HIGH = 0xffff0000;- var MASK_LOW = 0xffff;+ var parser = new DOMParser();+ meta = parser.parseFromString(meta, 'application/xml');+ } else if (!(meta instanceof Document)) {+ error('Metadata: Invalid metadata object');+ }- function MurmurHash3_64 (seed) {- var SEED = 0xc3d2e1f0;- this.h1 = seed ? seed & 0xffffffff : SEED;- this.h2 = seed ? seed & 0xffffffff : SEED;+ this.metaDocument = meta;+ this.metadata = {};+ this.parse();}- MurmurHash3_64.prototype = {- update: function MurmurHash3_64_update(input) {- var useUint32ArrayView = false;- var i;- if (typeof input == 'string') {- var data = new Uint8Array(input.length * 2);- var length = 0;- for (i = 0; i < input.length; i++) {- var code = input.charCodeAt(i);- if (code <= 0xff) {- data[length++] = code;- }- else {- data[length++] = code >>> 8;- data[length++] = code & 0xff;- }- }- } else if (input instanceof Uint8Array) {- data = input;- length = data.length;- } else if (typeof input === 'object' && ('length' in input)) {- // processing regular arrays as well, e.g. for IE9- data = input;- length = data.length;- useUint32ArrayView = true;- } else {- throw new Error('Wrong data format in MurmurHash3_64_update. ' +- 'Input must be a string or array.');- }-- var blockCounts = length >> 2;- var tailLength = length - blockCounts * 4;- // we don't care about endianness here- var dataUint32 = useUint32ArrayView ?- new Uint32ArrayView(data, blockCounts) :- new Uint32Array(data.buffer, 0, blockCounts);- var k1 = 0;- var k2 = 0;- var h1 = this.h1;- var h2 = this.h2;- var C1 = 0xcc9e2d51;- var C2 = 0x1b873593;- var C1_LOW = C1 & MASK_LOW;- var C2_LOW = C2 & MASK_LOW;-- for (i = 0; i < blockCounts; i++) {- if (i & 1) {- k1 = dataUint32[i];- k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);- k1 = k1 << 15 | k1 >>> 17;- k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);- h1 ^= k1;- h1 = h1 << 13 | h1 >>> 19;- h1 = h1 * 5 + 0xe6546b64;- } else {- k2 = dataUint32[i];- k2 = (k2 * C1 & MASK_HIGH) | (k2 * C1_LOW & MASK_LOW);- k2 = k2 << 15 | k2 >>> 17;- k2 = (k2 * C2 & MASK_HIGH) | (k2 * C2_LOW & MASK_LOW);- h2 ^= k2;- h2 = h2 << 13 | h2 >>> 19;- h2 = h2 * 5 + 0xe6546b64;- }- }+ Metadata.prototype = {+ parse: function Metadata_parse() {+ var doc = this.metaDocument;+ var rdf = doc.documentElement;- k1 = 0;-- switch (tailLength) {- case 3:- k1 ^= data[blockCounts * 4 + 2] << 16;- /* falls through */- case 2:- k1 ^= data[blockCounts * 4 + 1] << 8;- /* falls through */- case 1:- k1 ^= data[blockCounts * 4];- /* falls through */- k1 = (k1 * C1 & MASK_HIGH) | (k1 * C1_LOW & MASK_LOW);- k1 = k1 << 15 | k1 >>> 17;- k1 = (k1 * C2 & MASK_HIGH) | (k1 * C2_LOW & MASK_LOW);- if (blockCounts & 1) {- h1 ^= k1;- } else {- h2 ^= k1;- }+ if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>+ rdf = rdf.firstChild;+ while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf')+ rdf = rdf.nextSibling;}- this.h1 = h1;- this.h2 = h2;- return this;- },+ var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;+ if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes())+ return;- hexdigest: function MurmurHash3_64_hexdigest () {- var h1 = this.h1;- var h2 = this.h2;+ var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;- h1 ^= h2 >>> 1;- h1 = (h1 * 0xed558ccd & MASK_HIGH) | (h1 * 0x8ccd & MASK_LOW);- h2 = (h2 * 0xff51afd7 & MASK_HIGH) |- (((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16);- h1 ^= h2 >>> 1;- h1 = (h1 * 0x1a85ec53 & MASK_HIGH) | (h1 * 0xec53 & MASK_LOW);- h2 = (h2 * 0xc4ceb9fe & MASK_HIGH) |- (((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16);- h1 ^= h2 >>> 1;+ for (i = 0, length = children.length; i < length; i++) {+ desc = children[i];+ if (desc.nodeName.toLowerCase() !== 'rdf:description')+ continue;- for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {- var hex = (arr[i] >>> 0).toString(16);- while (hex.length < 8) {- hex = '0' + hex;+ for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {+ if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {+ entry = desc.childNodes[ii];+ name = entry.nodeName.toLowerCase();+ this.metadata[name] = entry.textContent.trim();+ }}- str += hex;}+ },- return str;+ get: function Metadata_get(name) {+ return this.metadata[name] || null;+ },++ has: function Metadata_has(name) {+ return typeof this.metadata[name] !== 'undefined';}};- return MurmurHash3_64;+ return Metadata;})();/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- //* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */@@ -41408,10 +40975,6 @@ var JpegImage = (function jpegImage() {return code[0].children;}- function getBlockBufferOffset(component, row, col) {- return 64 * ((component.blocksPerLine + 1) * row + col);- }-function decodeScan(data, offset,frame, components, resetInterval,spectralStart, spectralEnd,@@ -41424,7 +40987,6 @@ var JpegImage = (function jpegImage() {var maxH = frame.maxH, maxV = frame.maxV;var startOffset = offset, bitsData = 0, bitsCount = 0;-function readBit() {if (bitsCount > 0) {bitsCount--;@@ -41441,10 +41003,8 @@ var JpegImage = (function jpegImage() {bitsCount = 7;return bitsData >>> 7;}-function decodeHuffman(tree) {- var node = tree;- var bit;+ var node = tree, bit;while ((bit = readBit()) !== null) {node = node[bit];if (typeof node === 'number')@@ -41454,7 +41014,6 @@ var JpegImage = (function jpegImage() {}return null;}-function receive(length) {var n = 0;while (length > 0) {@@ -41465,18 +41024,16 @@ var JpegImage = (function jpegImage() {}return n;}-function receiveAndExtend(length) {var n = receive(length);if (n >= 1 << (length - 1))return n;return n + (-1 << length) + 1;}-- function decodeBaseline(component, offset) {+ function decodeBaseline(component, zz) {var t = decodeHuffman(component.huffmanTableDC);var diff = t === 0 ? 0 : receiveAndExtend(t);- component.blockData[offset] = (component.pred += diff);+ zz[0]= (component.pred += diff);var k = 1;while (k < 64) {var rs = decodeHuffman(component.huffmanTableAC);@@ -41489,23 +41046,20 @@ var JpegImage = (function jpegImage() {}k += r;var z = dctZigZag[k];- component.blockData[offset + z] = receiveAndExtend(s);+ zz[z] = receiveAndExtend(s);k++;}}-- function decodeDCFirst(component, offset) {+ function decodeDCFirst(component, zz) {var t = decodeHuffman(component.huffmanTableDC);var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);- component.blockData[offset] = (component.pred += diff);+ zz[0] = (component.pred += diff);}-- function decodeDCSuccessive(component, offset) {- component.blockData[offset] |= readBit() << successive;+ function decodeDCSuccessive(component, zz) {+ zz[0] |= readBit() << successive;}-var eobrun = 0;- function decodeACFirst(component, offset) {+ function decodeACFirst(component, zz) {if (eobrun > 0) {eobrun--;return;@@ -41524,13 +41078,12 @@ var JpegImage = (function jpegImage() {}k += r;var z = dctZigZag[k];- component.blockData[offset + z] = receiveAndExtend(s) * (1 << successive);+ zz[z] = receiveAndExtend(s) * (1 << successive);k++;}}-var successiveACState = 0, successiveACNextValue;- function decodeACSuccessive(component, offset) {+ function decodeACSuccessive(component, zz) {var k = spectralStart, e = spectralEnd, r = 0;while (k <= e) {var z = dctZigZag[k];@@ -41555,26 +41108,25 @@ var JpegImage = (function jpegImage() {continue;case 1: // skipping r zero itemscase 2:- if (component.blockData[offset + z]) {- component.blockData[offset + z] += (readBit() << successive);- } else {+ if (zz[z])+ zz[z] += (readBit() << successive);+ else {r--;if (r === 0)successiveACState = successiveACState == 2 ? 3 : 0;}break;case 3: // set value for a zero item- if (component.blockData[offset + z]) {- component.blockData[offset + z] += (readBit() << successive);- } else {- component.blockData[offset + z] = successiveACNextValue << successive;+ if (zz[z])+ zz[z] += (readBit() << successive);+ else {+ zz[z] = successiveACNextValue << successive;successiveACState = 0;}break;case 4: // eob- if (component.blockData[offset + z]) {- component.blockData[offset + z] += (readBit() << successive);- }+ if (zz[z])+ zz[z] += (readBit() << successive);break;}k++;@@ -41585,21 +41137,17 @@ var JpegImage = (function jpegImage() {successiveACState = 0;}}-function decodeMcu(component, decode, mcu, row, col) {var mcuRow = (mcu / mcusPerLine) | 0;var mcuCol = mcu % mcusPerLine;var blockRow = mcuRow * component.v + row;var blockCol = mcuCol * component.h + col;- var offset = getBlockBufferOffset(component, blockRow, blockCol);- decode(component, offset);+ decode(component, component.blocks[blockRow][blockCol]);}-function decodeBlock(component, decode, mcu) {var blockRow = (mcu / component.blocksPerLine) | 0;var blockCol = mcu % component.blocksPerLine;- var offset = getBlockBufferOffset(component, blockRow, blockCol);- decode(component, offset);+ decode(component, component.blocks[blockRow][blockCol]);}var componentsLength = components.length;@@ -41621,16 +41169,13 @@ var JpegImage = (function jpegImage() {} else {mcuExpected = mcusPerLine * frame.mcusPerColumn;}- if (!resetInterval) {- resetInterval = mcuExpected;- }+ if (!resetInterval) resetInterval = mcuExpected;var h, v;while (mcu < mcuExpected) {// reset interval stuff- for (i = 0; i < componentsLength; i++) {+ for (i = 0; i < componentsLength; i++)components[i].pred = 0;- }eobrun = 0;if (componentsLength == 1) {@@ -41664,197 +41209,202 @@ var JpegImage = (function jpegImage() {if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTxoffset += 2;- } else {- break;}+ else+ break;}return offset - startOffset;}- // A port of poppler's IDCT method which in turn is taken from:- // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,- // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",- // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,- // 988-991.- function quantizeAndInverse(component, blockBufferOffset, p) {- var qt = component.quantizationTable;- var v0, v1, v2, v3, v4, v5, v6, v7, t;- var i;-- // dequant- for (i = 0; i < 64; i++) {- p[i] = component.blockData[blockBufferOffset + i] * qt[i];- }-- // inverse DCT on rows- for (i = 0; i < 8; ++i) {- var row = 8 * i;-- // check for all-zero AC coefficients- if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&- p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&- p[7 + row] == 0) {- t = (dctSqrt2 * p[0 + row] + 512) >> 10;- p[0 + row] = t;- p[1 + row] = t;- p[2 + row] = t;- p[3 + row] = t;- p[4 + row] = t;- p[5 + row] = t;- p[6 + row] = t;- p[7 + row] = t;- continue;- }-- // stage 4- v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;- v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;- v2 = p[2 + row];- v3 = p[6 + row];- v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;- v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;- v5 = p[3 + row] << 4;- v6 = p[5 + row] << 4;-- // stage 3- t = (v0 - v1+ 1) >> 1;- v0 = (v0 + v1 + 1) >> 1;- v1 = t;- t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;- v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;- v3 = t;- t = (v4 - v6 + 1) >> 1;- v4 = (v4 + v6 + 1) >> 1;- v6 = t;- t = (v7 + v5 + 1) >> 1;- v5 = (v7 - v5 + 1) >> 1;- v7 = t;-- // stage 2- t = (v0 - v3 + 1) >> 1;- v0 = (v0 + v3 + 1) >> 1;- v3 = t;- t = (v1 - v2 + 1) >> 1;- v1 = (v1 + v2 + 1) >> 1;- v2 = t;- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;- v7 = t;- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;- v6 = t;-- // stage 1- p[0 + row] = v0 + v7;- p[7 + row] = v0 - v7;- p[1 + row] = v1 + v6;- p[6 + row] = v1 - v6;- p[2 + row] = v2 + v5;- p[5 + row] = v2 - v5;- p[3 + row] = v3 + v4;- p[4 + row] = v3 - v4;- }-- // inverse DCT on columns- for (i = 0; i < 8; ++i) {- var col = i;-- // check for all-zero AC coefficients- if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&- p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&- p[7*8 + col] == 0) {- t = (dctSqrt2 * p[i+0] + 8192) >> 14;- p[0*8 + col] = t;- p[1*8 + col] = t;- p[2*8 + col] = t;- p[3*8 + col] = t;- p[4*8 + col] = t;- p[5*8 + col] = t;- p[6*8 + col] = t;- p[7*8 + col] = t;- continue;- }-- // stage 4- v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;- v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;- v2 = p[2*8 + col];- v3 = p[6*8 + col];- v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;- v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;- v5 = p[3*8 + col];- v6 = p[5*8 + col];-- // stage 3- t = (v0 - v1 + 1) >> 1;- v0 = (v0 + v1 + 1) >> 1;- v1 = t;- t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;- v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;- v3 = t;- t = (v4 - v6 + 1) >> 1;- v4 = (v4 + v6 + 1) >> 1;- v6 = t;- t = (v7 + v5 + 1) >> 1;- v5 = (v7 - v5 + 1) >> 1;- v7 = t;-- // stage 2- t = (v0 - v3 + 1) >> 1;- v0 = (v0 + v3 + 1) >> 1;- v3 = t;- t = (v1 - v2 + 1) >> 1;- v1 = (v1 + v2 + 1) >> 1;- v2 = t;- t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;- v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;- v7 = t;- t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;- v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;- v6 = t;-- // stage 1- p[0*8 + col] = v0 + v7;- p[7*8 + col] = v0 - v7;- p[1*8 + col] = v1 + v6;- p[6*8 + col] = v1 - v6;- p[2*8 + col] = v2 + v5;- p[5*8 + col] = v2 - v5;- p[3*8 + col] = v3 + v4;- p[4*8 + col] = v3 - v4;- }-- // convert to 8-bit integers- for (i = 0; i < 64; ++i) {- var index = blockBufferOffset + i;- component.blockData[index] = clampTo8bitInt((p[i] + 2056) >> 4);- }- }-function buildComponentData(frame, component) {var lines = [];var blocksPerLine = component.blocksPerLine;var blocksPerColumn = component.blocksPerColumn;var samplesPerLine = blocksPerLine << 3;- var computationBuffer = new Int32Array(64);+ var R = new Int32Array(64), r = new Uint8Array(64);++ // A port of poppler's IDCT method which in turn is taken from:+ // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,+ // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",+ // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,+ // 988-991.+ function quantizeAndInverse(zz, dataOut, dataIn) {+ var qt = component.quantizationTable;+ var v0, v1, v2, v3, v4, v5, v6, v7, t;+ var p = dataIn;+ var i;++ // dequant+ for (i = 0; i < 64; i++)+ p[i] = zz[i] * qt[i];++ // inverse DCT on rows+ for (i = 0; i < 8; ++i) {+ var row = 8 * i;++ // check for all-zero AC coefficients+ if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&+ p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&+ p[7 + row] == 0) {+ t = (dctSqrt2 * p[0 + row] + 512) >> 10;+ p[0 + row] = t;+ p[1 + row] = t;+ p[2 + row] = t;+ p[3 + row] = t;+ p[4 + row] = t;+ p[5 + row] = t;+ p[6 + row] = t;+ p[7 + row] = t;+ continue;+ }++ // stage 4+ v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;+ v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;+ v2 = p[2 + row];+ v3 = p[6 + row];+ v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;+ v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;+ v5 = p[3 + row] << 4;+ v6 = p[5 + row] << 4;++ // stage 3+ t = (v0 - v1+ 1) >> 1;+ v0 = (v0 + v1 + 1) >> 1;+ v1 = t;+ t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;+ v3 = t;+ t = (v4 - v6 + 1) >> 1;+ v4 = (v4 + v6 + 1) >> 1;+ v6 = t;+ t = (v7 + v5 + 1) >> 1;+ v5 = (v7 - v5 + 1) >> 1;+ v7 = t;++ // stage 2+ t = (v0 - v3 + 1) >> 1;+ v0 = (v0 + v3 + 1) >> 1;+ v3 = t;+ t = (v1 - v2 + 1) >> 1;+ v1 = (v1 + v2 + 1) >> 1;+ v2 = t;+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;+ v7 = t;+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;+ v6 = t;++ // stage 1+ p[0 + row] = v0 + v7;+ p[7 + row] = v0 - v7;+ p[1 + row] = v1 + v6;+ p[6 + row] = v1 - v6;+ p[2 + row] = v2 + v5;+ p[5 + row] = v2 - v5;+ p[3 + row] = v3 + v4;+ p[4 + row] = v3 - v4;+ }++ // inverse DCT on columns+ for (i = 0; i < 8; ++i) {+ var col = i;++ // check for all-zero AC coefficients+ if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&+ p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&+ p[7*8 + col] == 0) {+ t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;+ p[0*8 + col] = t;+ p[1*8 + col] = t;+ p[2*8 + col] = t;+ p[3*8 + col] = t;+ p[4*8 + col] = t;+ p[5*8 + col] = t;+ p[6*8 + col] = t;+ p[7*8 + col] = t;+ continue;+ }- var i, j, ll = 0;+ // stage 4+ v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;+ v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;+ v2 = p[2*8 + col];+ v3 = p[6*8 + col];+ v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;+ v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;+ v5 = p[3*8 + col];+ v6 = p[5*8 + col];++ // stage 3+ t = (v0 - v1 + 1) >> 1;+ v0 = (v0 + v1 + 1) >> 1;+ v1 = t;+ t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;+ v3 = t;+ t = (v4 - v6 + 1) >> 1;+ v4 = (v4 + v6 + 1) >> 1;+ v6 = t;+ t = (v7 + v5 + 1) >> 1;+ v5 = (v7 - v5 + 1) >> 1;+ v7 = t;++ // stage 2+ t = (v0 - v3 + 1) >> 1;+ v0 = (v0 + v3 + 1) >> 1;+ v3 = t;+ t = (v1 - v2 + 1) >> 1;+ v1 = (v1 + v2 + 1) >> 1;+ v2 = t;+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;+ v7 = t;+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;+ v6 = t;++ // stage 1+ p[0*8 + col] = v0 + v7;+ p[7*8 + col] = v0 - v7;+ p[1*8 + col] = v1 + v6;+ p[6*8 + col] = v1 - v6;+ p[2*8 + col] = v2 + v5;+ p[5*8 + col] = v2 - v5;+ p[3*8 + col] = v3 + v4;+ p[4*8 + col] = v3 - v4;+ }++ // convert to 8-bit integers+ for (i = 0; i < 64; ++i) {+ var sample = 128 + ((p[i] + 8) >> 4);+ dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;+ }+ }++ var i, j;for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {+ var scanLine = blockRow << 3;+ for (i = 0; i < 8; i++)+ lines.push(new Uint8Array(samplesPerLine));for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {- var offset = getBlockBufferOffset(component, blockRow, blockCol)- quantizeAndInverse(component, offset, computationBuffer);+ quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);++ var offset = 0, sample = blockCol << 3;+ for (j = 0; j < 8; j++) {+ var line = lines[scanLine + j];+ for (i = 0; i < 8; i++)+ line[sample + i] = r[offset++];+ }}}- return component.blockData;+ return lines;}- function clampTo8bitInt(a) {- return a <= 0 ? 0 : a >= 255 ? 255 : a | 0;- }-- function clamp0to255(a) {- return a <= 0 ? 0 : a >= 255 ? 255 : a;+ function clampTo8bit(a) {+ return a < 0 ? 0 : a > 255 ? 255 : a;}constructor.prototype = {@@ -41871,48 +41421,60 @@ var JpegImage = (function jpegImage() {}).bind(this);xhr.send(null);},-parse: function parse(data) {-+ var offset = 0, length = data.length;function readUint16() {var value = (data[offset] << 8) | data[offset + 1];offset += 2;return value;}-function readDataBlock() {var length = readUint16();var array = data.subarray(offset, offset + length - 2);offset += array.length;return array;}-function prepareComponents(frame) {- var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);- var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);- for (var i = 0; i < frame.components.length; i++) {- component = frame.components[i];- var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / frame.maxH);- var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / frame.maxV);- var blocksPerLineForMcu = mcusPerLine * component.h;- var blocksPerColumnForMcu = mcusPerColumn * component.v;-- var blocksBufferSize = 64 * blocksPerColumnForMcu- * (blocksPerLineForMcu + 1);- component.blockData = new Int16Array(blocksBufferSize);- component.blocksPerLine = blocksPerLine;- component.blocksPerColumn = blocksPerColumn;+ var maxH = 0, maxV = 0;+ var component, componentId;+ for (componentId in frame.components) {+ if (frame.components.hasOwnProperty(componentId)) {+ component = frame.components[componentId];+ if (maxH < component.h) maxH = component.h;+ if (maxV < component.v) maxV = component.v;+ }+ }+ var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);+ var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);+ for (componentId in frame.components) {+ if (frame.components.hasOwnProperty(componentId)) {+ component = frame.components[componentId];+ var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);+ var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);+ var blocksPerLineForMcu = mcusPerLine * component.h;+ var blocksPerColumnForMcu = mcusPerColumn * component.v;+ var blocks = [];+ for (var i = 0; i < blocksPerColumnForMcu; i++) {+ var row = [];+ for (var j = 0; j < blocksPerLineForMcu; j++)+ row.push(new Int32Array(64));+ blocks.push(row);+ }+ component.blocksPerLine = blocksPerLine;+ component.blocksPerColumn = blocksPerColumn;+ component.blocks = blocks;+ }}+ frame.maxH = maxH;+ frame.maxV = maxV;frame.mcusPerLine = mcusPerLine;frame.mcusPerColumn = mcusPerColumn;}-- var offset = 0, length = data.length;var jfif = null;var adobe = null;var pixels = null;var frame, resetInterval;- var quantizationTables = [];+ var quantizationTables = [], frames = [];var huffmanTablesAC = [], huffmanTablesDC = [];var fileMarker = readUint16();if (fileMarker != 0xFFD8) { // SOI (Start of Image)@@ -41995,9 +41557,6 @@ var JpegImage = (function jpegImage() {case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)- if (frame) {- throw "Only single frame JPEGs supported";- }readUint16(); // skip data lengthframe = {};frame.extended = (fileMarker === 0xFFC1);@@ -42005,28 +41564,25 @@ var JpegImage = (function jpegImage() {frame.precision = data[offset++];frame.scanLines = readUint16();frame.samplesPerLine = readUint16();- frame.components = [];- frame.componentIds = {};+ frame.components = {};+ frame.componentsOrder = [];var componentsCount = data[offset++], componentId;var maxH = 0, maxV = 0;for (i = 0; i < componentsCount; i++) {componentId = data[offset];var h = data[offset + 1] >> 4;var v = data[offset + 1] & 15;- if (maxH < h) maxH = h;- if (maxV < v) maxV = v;var qId = data[offset + 2];- var l = frame.components.push({+ frame.componentsOrder.push(componentId);+ frame.components[componentId] = {h: h,v: v,quantizationTable: quantizationTables[qId]- });- frame.componentIds[componentId] = l - 1;+ };offset += 3;}- frame.maxH = maxH;- frame.maxV = maxV;prepareComponents(frame);+ frames.push(frame);break;case 0xFFC4: // DHT (Define Huffman Tables)@@ -42042,7 +41598,7 @@ var JpegImage = (function jpegImage() {huffmanValues[j] = data[offset];i += 17 + codeLengthSum;- ((huffmanTableSpec >> 4) === 0 ?+ ((huffmanTableSpec >> 4) === 0 ?huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =buildHuffmanTable(codeLengths, huffmanValues);}@@ -42058,8 +41614,7 @@ var JpegImage = (function jpegImage() {var selectorsCount = data[offset++];var components = [], component;for (i = 0; i < selectorsCount; i++) {- var componentIndex = frame.componentIds[data[offset++]];- component = frame.components[componentIndex];+ component = frame.components[data[offset++]];var tableSpec = data[offset++];component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];@@ -42086,88 +41641,61 @@ var JpegImage = (function jpegImage() {}fileMarker = readUint16();}+ if (frames.length != 1)+ throw "only single frame JPEGs supported";this.width = frame.samplesPerLine;this.height = frame.scanLines;this.jfif = jfif;this.adobe = adobe;this.components = [];- for (var i = 0; i < frame.components.length; i++) {- var component = frame.components[i];+ for (var i = 0; i < frame.componentsOrder.length; i++) {+ var component = frame.components[frame.componentsOrder[i]];this.components.push({- output: buildComponentData(frame, component),+ lines: buildComponentData(frame, component),scaleX: component.h / frame.maxH,- scaleY: component.v / frame.maxV,- blocksPerLine: component.blocksPerLine,- blocksPerColumn: component.blocksPerColumn+ scaleY: component.v / frame.maxV});}},-getData: function getData(width, height) {var scaleX = this.width / width, scaleY = this.height / height;- var component, componentScaleX, componentScaleY;- var x, y, i;+ var component1, component2, component3, component4;+ var component1Line, component2Line, component3Line, component4Line;+ var x, y;var offset = 0;var Y, Cb, Cr, K, C, M, Ye, R, G, B;var colorTransform;- var numComponents = this.components.length;- var dataLength = width * height * numComponents;+ var dataLength = width * height * this.components.length;var data = new Uint8Array(dataLength);- var componentLine;-- // lineData is reused for all components. Assume first component is- // the biggest- var lineData = new Uint8Array((this.components[0].blocksPerLine << 3) *- this.components[0].blocksPerColumn * 8);-- // First construct image data ...- for (i = 0; i < numComponents; i++) {- component = this.components[i];- var blocksPerLine = component.blocksPerLine;- var blocksPerColumn = component.blocksPerColumn;- var samplesPerLine = blocksPerLine << 3;-- var j, k, ll = 0;- var lineOffset = 0;- for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {- var scanLine = blockRow << 3;- for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {- var bufferOffset = getBlockBufferOffset(component, blockRow, blockCol);- var offset = 0, sample = blockCol << 3;- for (j = 0; j < 8; j++) {- var lineOffset = (scanLine + j) * samplesPerLine;- for (k = 0; k < 8; k++) {- lineData[lineOffset + sample + k] =- component.output[bufferOffset + offset++];- }+ switch (this.components.length) {+ case 1:+ component1 = this.components[0];+ for (y = 0; y < height; y++) {+ component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];+ for (x = 0; x < width; x++) {+ Y = component1Line[0 | (x * component1.scaleX * scaleX)];++ data[offset++] = Y;}}- }-- componentScaleX = component.scaleX * scaleX;- componentScaleY = component.scaleY * scaleY;- offset = i;-- var cx, cy;- var index;- for (y = 0; y < height; y++) {- for (x = 0; x < width; x++) {- cy = 0 | (y * componentScaleY);- cx = 0 | (x * componentScaleX);- index = cy * samplesPerLine + cx;- data[offset] = lineData[index];- offset += numComponents;+ break;+ case 2:+ // PDF might compress two component data in custom colorspace+ component1 = this.components[0];+ component2 = this.components[1];+ for (y = 0; y < height; y++) {+ component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];+ component2Line = component1.lines[0 | (y * component2.scaleY * scaleY)];+ for (x = 0; x < width; x++) {+ Y = component1Line[0 | (x * component1.scaleX * scaleX)];+ data[offset++] = Y;+ Y = component2Line[0 | (x * component2.scaleX * scaleX)];+ data[offset++] = Y;+ }}- }- }-- // ... then transform colors, if necessary- switch (numComponents) {- case 1: case 2: break;- // no color conversion for one or two compoenents-+ break;case 3:// The default transform for three components is truecolorTransform = true;@@ -42177,23 +41705,37 @@ var JpegImage = (function jpegImage() {else if (typeof this.colorTransform !== 'undefined')colorTransform = !!this.colorTransform;- if (colorTransform) {- for (i = 0; i < dataLength; i += numComponents) {- Y = data[i ];- Cb = data[i + 1];- Cr = data[i + 2];+ component1 = this.components[0];+ component2 = this.components[1];+ component3 = this.components[2];+ for (y = 0; y < height; y++) {+ component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];+ component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];+ component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];+ for (x = 0; x < width; x++) {+ if (!colorTransform) {+ R = component1Line[0 | (x * component1.scaleX * scaleX)];+ G = component2Line[0 | (x * component2.scaleX * scaleX)];+ B = component3Line[0 | (x * component3.scaleX * scaleX)];+ } else {+ Y = component1Line[0 | (x * component1.scaleX * scaleX)];+ Cb = component2Line[0 | (x * component2.scaleX * scaleX)];+ Cr = component3Line[0 | (x * component3.scaleX * scaleX)];- R = clamp0to255(Y + 1.402 * (Cr - 128));- G = clamp0to255(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));- B = clamp0to255(Y + 1.772 * (Cb - 128));+ R = clampTo8bit(Y + 1.402 * (Cr - 128));+ G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));+ B = clampTo8bit(Y + 1.772 * (Cb - 128));+ }- data[i ] = R;- data[i + 1] = G;- data[i + 2] = B;+ data[offset++] = R;+ data[offset++] = G;+ data[offset++] = B;}}break;case 4:+ if (!this.adobe)+ throw 'Unsupported color mode (4 components)';// The default transform for four components is falsecolorTransform = false;// The adobe transform marker overrides any previous setting@@ -42202,20 +41744,35 @@ var JpegImage = (function jpegImage() {else if (typeof this.colorTransform !== 'undefined')colorTransform = !!this.colorTransform;- if (colorTransform) {- for (i = 0; i < dataLength; i += numComponents) {- Y = data[i];- Cb = data[i + 1];- Cr = data[i + 2];-- C = 255 - clamp0to255(Y + 1.402 * (Cr - 128));- M = 255 - clamp0to255(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));- Ye = 255 - clamp0to255(Y + 1.772 * (Cb - 128));-- data[i ] = C;- data[i + 1] = M;- data[i + 2] = Ye;- // K is unchanged+ component1 = this.components[0];+ component2 = this.components[1];+ component3 = this.components[2];+ component4 = this.components[3];+ for (y = 0; y < height; y++) {+ component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];+ component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];+ component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];+ component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];+ for (x = 0; x < width; x++) {+ if (!colorTransform) {+ C = component1Line[0 | (x * component1.scaleX * scaleX)];+ M = component2Line[0 | (x * component2.scaleX * scaleX)];+ Ye = component3Line[0 | (x * component3.scaleX * scaleX)];+ K = component4Line[0 | (x * component4.scaleX * scaleX)];+ } else {+ Y = component1Line[0 | (x * component1.scaleX * scaleX)];+ Cb = component2Line[0 | (x * component2.scaleX * scaleX)];+ Cr = component3Line[0 | (x * component3.scaleX * scaleX)];+ K = component4Line[0 | (x * component4.scaleX * scaleX)];++ C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));+ M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));+ Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));+ }+ data[offset++] = C;+ data[offset++] = M;+ data[offset++] = Ye;+ data[offset++] = K;}}break;@@ -42226,49 +41783,54 @@ var JpegImage = (function jpegImage() {},copyToImageData: function copyToImageData(imageData) {var width = imageData.width, height = imageData.height;- var imageDataBytes = width * height * 4;var imageDataArray = imageData.data;var data = this.getData(width, height);- var i = 0, j = 0;+ var i = 0, j = 0, x, y;var Y, K, C, M, R, G, B;switch (this.components.length) {case 1:- while (j < imageDataBytes) {- Y = data[i++];-- imageDataArray[j++] = Y;- imageDataArray[j++] = Y;- imageDataArray[j++] = Y;- imageDataArray[j++] = 255;+ for (y = 0; y < height; y++) {+ for (x = 0; x < width; x++) {+ Y = data[i++];++ imageDataArray[j++] = Y;+ imageDataArray[j++] = Y;+ imageDataArray[j++] = Y;+ imageDataArray[j++] = 255;+ }}break;case 3:- while (j < imageDataBytes) {- R = data[i++];- G = data[i++];- B = data[i++];-- imageDataArray[j++] = R;- imageDataArray[j++] = G;- imageDataArray[j++] = B;- imageDataArray[j++] = 255;+ for (y = 0; y < height; y++) {+ for (x = 0; x < width; x++) {+ R = data[i++];+ G = data[i++];+ B = data[i++];++ imageDataArray[j++] = R;+ imageDataArray[j++] = G;+ imageDataArray[j++] = B;+ imageDataArray[j++] = 255;+ }}break;case 4:- while (j < imageDataBytes) {- C = data[i++];- M = data[i++];- Y = data[i++];- K = data[i++];-- R = 255 - clamp0to255(C * (1 - K / 255) + K);- G = 255 - clamp0to255(M * (1 - K / 255) + K);- B = 255 - clamp0to255(Y * (1 - K / 255) + K);-- imageDataArray[j++] = R;- imageDataArray[j++] = G;- imageDataArray[j++] = B;- imageDataArray[j++] = 255;+ for (y = 0; y < height; y++) {+ for (x = 0; x < width; x++) {+ C = data[i++];+ M = data[i++];+ Y = data[i++];+ K = data[i++];++ R = 255 - clampTo8bit(C * (1 - K / 255) + K);+ G = 255 - clampTo8bit(M * (1 - K / 255) + K);+ B = 255 - clampTo8bit(Y * (1 - K / 255) + K);++ imageDataArray[j++] = R;+ imageDataArray[j++] = G;+ imageDataArray[j++] = B;+ imageDataArray[j++] = 255;+ }}break;default:@@ -42283,15 +41845,4 @@ var JpegImage = (function jpegImage() {}).call((typeof window === 'undefined') ? this : window);-if (!PDFJS.workerSrc && typeof document !== 'undefined') {- // workerSrc is not set -- using last script url to define default location- PDFJS.workerSrc = (function () {- 'use strict';- var scriptTagContainer = document.body ||- document.getElementsByTagName('head')[0];- var pdfjsSrc = scriptTagContainer.lastChild.src;- return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');- })();-}-diff --git a/data/ext/viewerPDF/pdfjs/build/pdf.js b/data/ext/viewerPDF/pdfjs/build/pdf.jsdeleted file mode 100644index cbf5a831a..000000000--- a/data/ext/viewerPDF/pdfjs/build/pdf.js+++ /dev/null@@ -1,8539 +0,0 @@-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */-/* 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.- */-/*jshint globalstrict: false */--// Initializing PDFJS global object (if still undefined)-if (typeof PDFJS === 'undefined') {- (typeof window !== 'undefined' ? window : this).PDFJS = {};-}--PDFJS.version = '1.0.21';-PDFJS.build = 'f954cde';--(function pdfjsWrapper() {- // Use strict in our context only - users might not want it- 'use strict';--/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */-/* 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.- */-/* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,- Promise */--'use strict';--var globalScope = (typeof window === 'undefined') ? this : window;--var isWorker = (typeof window == 'undefined');--var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];--var TextRenderingMode = {- FILL: 0,- STROKE: 1,- FILL_STROKE: 2,- INVISIBLE: 3,- FILL_ADD_TO_PATH: 4,- STROKE_ADD_TO_PATH: 5,- FILL_STROKE_ADD_TO_PATH: 6,- ADD_TO_PATH: 7,- FILL_STROKE_MASK: 3,- ADD_TO_PATH_FLAG: 4-};--var ImageKind = {- GRAYSCALE_1BPP: 1,- RGB_24BPP: 2,- RGBA_32BPP: 3-};--// The global PDFJS object exposes the API-// In production, it will be declared outside a global wrapper-// In development, it will be declared here-if (!globalScope.PDFJS) {- globalScope.PDFJS = {};-}--globalScope.PDFJS.pdfBug = false;--PDFJS.VERBOSITY_LEVELS = {- errors: 0,- warnings: 1,- infos: 5-};--// All the possible operations for an operator list.-var OPS = PDFJS.OPS = {- // Intentionally start from 1 so it is easy to spot bad operators that will be- // 0's.- dependency: 1,- setLineWidth: 2,- setLineCap: 3,- setLineJoin: 4,- setMiterLimit: 5,- setDash: 6,- setRenderingIntent: 7,- setFlatness: 8,- setGState: 9,- save: 10,- restore: 11,- transform: 12,- moveTo: 13,- lineTo: 14,- curveTo: 15,- curveTo2: 16,- curveTo3: 17,- closePath: 18,- rectangle: 19,- stroke: 20,- closeStroke: 21,- fill: 22,- eoFill: 23,- fillStroke: 24,- eoFillStroke: 25,- closeFillStroke: 26,- closeEOFillStroke: 27,- endPath: 28,- clip: 29,- eoClip: 30,- beginText: 31,- endText: 32,- setCharSpacing: 33,- setWordSpacing: 34,- setHScale: 35,- setLeading: 36,- setFont: 37,- setTextRenderingMode: 38,- setTextRise: 39,- moveText: 40,- setLeadingMoveText: 41,- setTextMatrix: 42,- nextLine: 43,- showText: 44,- showSpacedText: 45,- nextLineShowText: 46,- nextLineSetSpacingShowText: 47,- setCharWidth: 48,- setCharWidthAndBounds: 49,- setStrokeColorSpace: 50,- setFillColorSpace: 51,- setStrokeColor: 52,- setStrokeColorN: 53,- setFillColor: 54,- setFillColorN: 55,- setStrokeGray: 56,- setFillGray: 57,- setStrokeRGBColor: 58,- setFillRGBColor: 59,- setStrokeCMYKColor: 60,- setFillCMYKColor: 61,- shadingFill: 62,- beginInlineImage: 63,- beginImageData: 64,- endInlineImage: 65,- paintXObject: 66,- markPoint: 67,- markPointProps: 68,- beginMarkedContent: 69,- beginMarkedContentProps: 70,- endMarkedContent: 71,- beginCompat: 72,- endCompat: 73,- paintFormXObjectBegin: 74,- paintFormXObjectEnd: 75,- beginGroup: 76,- endGroup: 77,- beginAnnotations: 78,- endAnnotations: 79,- beginAnnotation: 80,- endAnnotation: 81,- paintJpegXObject: 82,- paintImageMaskXObject: 83,- paintImageMaskXObjectGroup: 84,- paintImageXObject: 85,- paintInlineImageXObject: 86,- paintInlineImageXObjectGroup: 87,- paintImageXObjectRepeat: 88,- paintImageMaskXObjectRepeat: 89,- paintSolidColorImageMask: 90-};--// A notice for devs. These are good for things that are helpful to devs, such-// as warning that Workers were disabled, which is important to devs but not-// end users.-function info(msg) {- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {- console.log('Info: ' + msg);- }-}--// Non-fatal warnings.-function warn(msg) {- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {- console.log('Warning: ' + msg);- }-}--// Fatal errors that should trigger the fallback UI and halt execution by-// throwing an exception.-function error(msg) {- // If multiple arguments were passed, pass them all to the log function.- if (arguments.length > 1) {- var logArguments = ['Error:'];- logArguments.push.apply(logArguments, arguments);- console.log.apply(console, logArguments);- // Join the arguments into a single string for the lines below.- msg = [].join.call(arguments, ' ');- } else {- console.log('Error: ' + msg);- }- console.log(backtrace());- UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);- throw new Error(msg);-}--function backtrace() {- try {- throw new Error();- } catch (e) {- return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';- }-}--function assert(cond, msg) {- if (!cond) {- error(msg);- }-}--var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {- unknown: 'unknown',- forms: 'forms',- javaScript: 'javaScript',- smask: 'smask',- shadingPattern: 'shadingPattern',- font: 'font'-};--var UnsupportedManager = PDFJS.UnsupportedManager =- (function UnsupportedManagerClosure() {- var listeners = [];- return {- listen: function (cb) {- listeners.push(cb);- },- notify: function (featureId) {- warn('Unsupported feature "' + featureId + '"');- for (var i = 0, ii = listeners.length; i < ii; i++) {- listeners[i](featureId);- }- }- };-})();--// Combines two URLs. The baseUrl shall be absolute URL. If the url is an-// absolute URL, it will be returned as is.-function combineUrl(baseUrl, url) {- if (!url) {- return baseUrl;- }- if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {- return url;- }- var i;- if (url.charAt(0) == '/') {- // absolute path- i = baseUrl.indexOf('://');- if (url.charAt(1) === '/') {- ++i;- } else {- i = baseUrl.indexOf('/', i + 3);- }- return baseUrl.substring(0, i) + url;- } else {- // relative path- var pathLength = baseUrl.length;- i = baseUrl.lastIndexOf('#');- pathLength = i >= 0 ? i : pathLength;- i = baseUrl.lastIndexOf('?', pathLength);- pathLength = i >= 0 ? i : pathLength;- var prefixLength = baseUrl.lastIndexOf('/', pathLength);- return baseUrl.substring(0, prefixLength + 1) + url;- }-}--// Validates if URL is safe and allowed, e.g. to avoid XSS.-function isValidUrl(url, allowRelative) {- if (!url) {- return false;- }- // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)- // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )- var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);- if (!protocol) {- return allowRelative;- }- protocol = protocol[0].toLowerCase();- switch (protocol) {- case 'http':- case 'https':- case 'ftp':- case 'mailto':- return true;- default:- return false;- }-}-PDFJS.isValidUrl = isValidUrl;--function shadow(obj, prop, value) {- Object.defineProperty(obj, prop, { value: value,- enumerable: true,- configurable: true,- writable: false });- return value;-}--var PasswordResponses = PDFJS.PasswordResponses = {- NEED_PASSWORD: 1,- INCORRECT_PASSWORD: 2-};--var PasswordException = (function PasswordExceptionClosure() {- function PasswordException(msg, code) {- this.name = 'PasswordException';- this.message = msg;- this.code = code;- }-- PasswordException.prototype = new Error();- PasswordException.constructor = PasswordException;-- return PasswordException;-})();--var UnknownErrorException = (function UnknownErrorExceptionClosure() {- function UnknownErrorException(msg, details) {- this.name = 'UnknownErrorException';- this.message = msg;- this.details = details;- }-- UnknownErrorException.prototype = new Error();- UnknownErrorException.constructor = UnknownErrorException;-- return UnknownErrorException;-})();--var InvalidPDFException = (function InvalidPDFExceptionClosure() {- function InvalidPDFException(msg) {- this.name = 'InvalidPDFException';- this.message = msg;- }-- InvalidPDFException.prototype = new Error();- InvalidPDFException.constructor = InvalidPDFException;-- return InvalidPDFException;-})();--var MissingPDFException = (function MissingPDFExceptionClosure() {- function MissingPDFException(msg) {- this.name = 'MissingPDFException';- this.message = msg;- }-- MissingPDFException.prototype = new Error();- MissingPDFException.constructor = MissingPDFException;-- return MissingPDFException;-})();--var NotImplementedException = (function NotImplementedExceptionClosure() {- function NotImplementedException(msg) {- this.message = msg;- }-- NotImplementedException.prototype = new Error();- NotImplementedException.prototype.name = 'NotImplementedException';- NotImplementedException.constructor = NotImplementedException;-- return NotImplementedException;-})();--var MissingDataException = (function MissingDataExceptionClosure() {- function MissingDataException(begin, end) {- this.begin = begin;- this.end = end;- this.message = 'Missing data [' + begin + ', ' + end + ')';- }-- MissingDataException.prototype = new Error();- MissingDataException.prototype.name = 'MissingDataException';- MissingDataException.constructor = MissingDataException;-- return MissingDataException;-})();--var XRefParseException = (function XRefParseExceptionClosure() {- function XRefParseException(msg) {- this.message = msg;- }-- XRefParseException.prototype = new Error();- XRefParseException.prototype.name = 'XRefParseException';- XRefParseException.constructor = XRefParseException;-- return XRefParseException;-})();---function bytesToString(bytes) {- var length = bytes.length;- var MAX_ARGUMENT_COUNT = 8192;- if (length < MAX_ARGUMENT_COUNT) {- return String.fromCharCode.apply(null, bytes);- }- var strBuf = [];- for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {- var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);- var chunk = bytes.subarray(i, chunkEnd);- strBuf.push(String.fromCharCode.apply(null, chunk));- }- return strBuf.join('');-}--function stringToArray(str) {- var length = str.length;- var array = [];- for (var i = 0; i < length; ++i) {- array[i] = str.charCodeAt(i);- }- return array;-}--function stringToBytes(str) {- var length = str.length;- var bytes = new Uint8Array(length);- for (var i = 0; i < length; ++i) {- bytes[i] = str.charCodeAt(i) & 0xFF;- }- return bytes;-}--function string32(value) {- return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,- (value >> 8) & 0xff, value & 0xff);-}--// Lazy test the endianness of the platform-// NOTE: This will be 'true' for simulated TypedArrays-function isLittleEndian() {- var buffer8 = new Uint8Array(2);- buffer8[0] = 1;- var buffer16 = new Uint16Array(buffer8.buffer);- return (buffer16[0] === 1);-}--Object.defineProperty(PDFJS, 'isLittleEndian', {- configurable: true,- get: function PDFJS_isLittleEndian() {- return shadow(PDFJS, 'isLittleEndian', isLittleEndian());- }-});-- // Lazy test if the userAgant support CanvasTypedArrays-function hasCanvasTypedArrays() {- var canvas = document.createElement('canvas');- canvas.width = canvas.height = 1;- var ctx = canvas.getContext('2d');- var imageData = ctx.createImageData(1, 1);- return (typeof imageData.data.buffer !== 'undefined');-}--Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {- configurable: true,- get: function PDFJS_hasCanvasTypedArrays() {- return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());- }-});--var Uint32ArrayView = (function Uint32ArrayViewClosure() {-- function Uint32ArrayView(buffer, length) {- this.buffer = buffer;- this.byteLength = buffer.length;- this.length = length === undefined ? (this.byteLength >> 2) : length;- ensureUint32ArrayViewProps(this.length);- }- Uint32ArrayView.prototype = Object.create(null);-- var uint32ArrayViewSetters = 0;- function createUint32ArrayProp(index) {- return {- get: function () {- var buffer = this.buffer, offset = index << 2;- return (buffer[offset] | (buffer[offset + 1] << 8) |- (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;- },- set: function (value) {- var buffer = this.buffer, offset = index << 2;- buffer[offset] = value & 255;- buffer[offset + 1] = (value >> 8) & 255;- buffer[offset + 2] = (value >> 16) & 255;- buffer[offset + 3] = (value >>> 24) & 255;- }- };- }-- function ensureUint32ArrayViewProps(length) {- while (uint32ArrayViewSetters < length) {- Object.defineProperty(Uint32ArrayView.prototype,- uint32ArrayViewSetters,- createUint32ArrayProp(uint32ArrayViewSetters));- uint32ArrayViewSetters++;- }- }-- return Uint32ArrayView;-})();--var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];--var Util = PDFJS.Util = (function UtilClosure() {- function Util() {}-- Util.makeCssRgb = function Util_makeCssRgb(rgb) {- return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';- };-- Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) {- var rgb = ColorSpace.singletons.cmyk.getRgb(cmyk, 0);- return Util.makeCssRgb(rgb);- };-- // Concatenates two transformation matrices together and returns the result.- Util.transform = function Util_transform(m1, m2) {- return [- m1[0] * m2[0] + m1[2] * m2[1],- m1[1] * m2[0] + m1[3] * m2[1],- m1[0] * m2[2] + m1[2] * m2[3],- m1[1] * m2[2] + m1[3] * m2[3],- m1[0] * m2[4] + m1[2] * m2[5] + m1[4],- m1[1] * m2[4] + m1[3] * m2[5] + m1[5]- ];- };-- // For 2d affine transforms- Util.applyTransform = function Util_applyTransform(p, m) {- var xt = p[0] * m[0] + p[1] * m[2] + m[4];- var yt = p[0] * m[1] + p[1] * m[3] + m[5];- return [xt, yt];- };-- Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {- var d = m[0] * m[3] - m[1] * m[2];- var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;- var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;- return [xt, yt];- };-- // Applies the transform to the rectangle and finds the minimum axially- // aligned bounding box.- Util.getAxialAlignedBoundingBox =- function Util_getAxialAlignedBoundingBox(r, m) {-- var p1 = Util.applyTransform(r, m);- var p2 = Util.applyTransform(r.slice(2, 4), m);- var p3 = Util.applyTransform([r[0], r[3]], m);- var p4 = Util.applyTransform([r[2], r[1]], m);- return [- Math.min(p1[0], p2[0], p3[0], p4[0]),- Math.min(p1[1], p2[1], p3[1], p4[1]),- Math.max(p1[0], p2[0], p3[0], p4[0]),- Math.max(p1[1], p2[1], p3[1], p4[1])- ];- };-- Util.inverseTransform = function Util_inverseTransform(m) {- var d = m[0] * m[3] - m[1] * m[2];- return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,- (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];- };-- // Apply a generic 3d matrix M on a 3-vector v:- // | a b c | | X |- // | d e f | x | Y |- // | g h i | | Z |- // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],- // with v as [X,Y,Z]- Util.apply3dTransform = function Util_apply3dTransform(m, v) {- return [- m[0] * v[0] + m[1] * v[1] + m[2] * v[2],- m[3] * v[0] + m[4] * v[1] + m[5] * v[2],- m[6] * v[0] + m[7] * v[1] + m[8] * v[2]- ];- };-- // This calculation uses Singular Value Decomposition.- // The SVD can be represented with formula A = USV. We are interested in the- // matrix S here because it represents the scale values.- Util.singularValueDecompose2dScale =- function Util_singularValueDecompose2dScale(m) {-- var transpose = [m[0], m[2], m[1], m[3]];-- // Multiply matrix m with its transpose.- var a = m[0] * transpose[0] + m[1] * transpose[2];- var b = m[0] * transpose[1] + m[1] * transpose[3];- var c = m[2] * transpose[0] + m[3] * transpose[2];- var d = m[2] * transpose[1] + m[3] * transpose[3];-- // Solve the second degree polynomial to get roots.- var first = (a + d) / 2;- var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;- var sx = first + second || 1;- var sy = first - second || 1;-- // Scale values are the square roots of the eigenvalues.- return [Math.sqrt(sx), Math.sqrt(sy)];- };-- // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)- // For coordinate systems whose origin lies in the bottom-left, this- // means normalization to (BL,TR) ordering. For systems with origin in the- // top-left, this means (TL,BR) ordering.- Util.normalizeRect = function Util_normalizeRect(rect) {- var r = rect.slice(0); // clone rect- if (rect[0] > rect[2]) {- r[0] = rect[2];- r[2] = rect[0];- }- if (rect[1] > rect[3]) {- r[1] = rect[3];- r[3] = rect[1];- }- return r;- };-- // Returns a rectangle [x1, y1, x2, y2] corresponding to the- // intersection of rect1 and rect2. If no intersection, returns 'false'- // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]- Util.intersect = function Util_intersect(rect1, rect2) {- function compare(a, b) {- return a - b;- }-- // Order points along the axes- var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),- orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),- result = [];-- rect1 = Util.normalizeRect(rect1);- rect2 = Util.normalizeRect(rect2);-- // X: first and second points belong to different rectangles?- if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||- (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {- // Intersection must be between second and third points- result[0] = orderedX[1];- result[2] = orderedX[2];- } else {- return false;- }-- // Y: first and second points belong to different rectangles?- if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||- (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {- // Intersection must be between second and third points- result[1] = orderedY[1];- result[3] = orderedY[2];- } else {- return false;- }-- return result;- };-- Util.sign = function Util_sign(num) {- return num < 0 ? -1 : 1;- };-- // TODO(mack): Rename appendToArray- Util.concatenateToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.push.apply(arr1, arr2);- };-- Util.prependToArray = function concatenateToArray(arr1, arr2) {- Array.prototype.unshift.apply(arr1, arr2);- };-- Util.extendObj = function extendObj(obj1, obj2) {- for (var key in obj2) {- obj1[key] = obj2[key];- }- };-- Util.getInheritableProperty = function Util_getInheritableProperty(dict,- name) {- while (dict && !dict.has(name)) {- dict = dict.get('Parent');- }- if (!dict) {- return null;- }- return dict.get(name);- };-- Util.inherit = function Util_inherit(sub, base, prototype) {- sub.prototype = Object.create(base.prototype);- sub.prototype.constructor = sub;- for (var prop in prototype) {- sub.prototype[prop] = prototype[prop];- }- };-- Util.loadScript = function Util_loadScript(src, callback) {- var script = document.createElement('script');- var loaded = false;- script.setAttribute('src', src);- if (callback) {- script.onload = function() {- if (!loaded) {- callback();- }- loaded = true;- };- }- document.getElementsByTagName('head')[0].appendChild(script);- };-- return Util;-})();--var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {- function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {- this.viewBox = viewBox;- this.scale = scale;- this.rotation = rotation;- this.offsetX = offsetX;- this.offsetY = offsetY;-- // creating transform to convert pdf coordinate system to the normal- // canvas like coordinates taking in account scale and rotation- var centerX = (viewBox[2] + viewBox[0]) / 2;- var centerY = (viewBox[3] + viewBox[1]) / 2;- var rotateA, rotateB, rotateC, rotateD;- rotation = rotation % 360;- rotation = rotation < 0 ? rotation + 360 : rotation;- switch (rotation) {- case 180:- rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;- break;- case 90:- rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;- break;- case 270:- rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;- break;- //case 0:- default:- rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;- break;- }-- if (dontFlip) {- rotateC = -rotateC; rotateD = -rotateD;- }-- var offsetCanvasX, offsetCanvasY;- var width, height;- if (rotateA === 0) {- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;- width = Math.abs(viewBox[3] - viewBox[1]) * scale;- height = Math.abs(viewBox[2] - viewBox[0]) * scale;- } else {- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;- width = Math.abs(viewBox[2] - viewBox[0]) * scale;- height = Math.abs(viewBox[3] - viewBox[1]) * scale;- }- // creating transform for the following operations:- // translate(-centerX, -centerY), rotate and flip vertically,- // scale, and translate(offsetCanvasX, offsetCanvasY)- this.transform = [- rotateA * scale,- rotateB * scale,- rotateC * scale,- rotateD * scale,- offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,- offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY- ];-- this.width = width;- this.height = height;- this.fontScale = scale;- }- PageViewport.prototype = {- clone: function PageViewPort_clone(args) {- args = args || {};- var scale = 'scale' in args ? args.scale : this.scale;- var rotation = 'rotation' in args ? args.rotation : this.rotation;- return new PageViewport(this.viewBox.slice(), scale, rotation,- this.offsetX, this.offsetY, args.dontFlip);- },- convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {- return Util.applyTransform([x, y], this.transform);- },- convertToViewportRectangle:- function PageViewport_convertToViewportRectangle(rect) {- var tl = Util.applyTransform([rect[0], rect[1]], this.transform);- var br = Util.applyTransform([rect[2], rect[3]], this.transform);- return [tl[0], tl[1], br[0], br[1]];- },- convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {- return Util.applyInverseTransform([x, y], this.transform);- }- };- return PageViewport;-})();--var PDFStringTranslateTable = [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,- 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,- 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,- 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC-];--function stringToPDFString(str) {- var i, n = str.length, strBuf = [];- if (str[0] === '\xFE' && str[1] === '\xFF') {- // UTF16BE BOM- for (i = 2; i < n; i += 2) {- strBuf.push(String.fromCharCode(- (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));- }- } else {- for (i = 0; i < n; ++i) {- var code = PDFStringTranslateTable[str.charCodeAt(i)];- strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));- }- }- return strBuf.join('');-}--function stringToUTF8String(str) {- return decodeURIComponent(escape(str));-}--function isEmptyObj(obj) {- for (var key in obj) {- return false;- }- return true;-}--function isBool(v) {- return typeof v == 'boolean';-}--function isInt(v) {- return typeof v == 'number' && ((v | 0) == v);-}--function isNum(v) {- return typeof v == 'number';-}--function isString(v) {- return typeof v == 'string';-}--function isNull(v) {- return v === null;-}--function isName(v) {- return v instanceof Name;-}--function isCmd(v, cmd) {- return v instanceof Cmd && (!cmd || v.cmd == cmd);-}--function isDict(v, type) {- if (!(v instanceof Dict)) {- return false;- }- if (!type) {- return true;- }- var dictType = v.get('Type');- return isName(dictType) && dictType.name == type;-}--function isArray(v) {- return v instanceof Array;-}--function isStream(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('getBytes' in v);-}--function isArrayBuffer(v) {- return typeof v == 'object' && v !== null && v !== undefined &&- ('byteLength' in v);-}--function isRef(v) {- return v instanceof Ref;-}--function isPDFFunction(v) {- var fnDict;- if (typeof v != 'object') {- return false;- } else if (isDict(v)) {- fnDict = v;- } else if (isStream(v)) {- fnDict = v.dict;- } else {- return false;- }- return fnDict.has('FunctionType');-}--/**- * Legacy support for PDFJS Promise implementation.- * TODO remove eventually- * @ignore- */-var LegacyPromise = PDFJS.LegacyPromise = (function LegacyPromiseClosure() {- return function LegacyPromise() {- var resolve, reject;- var promise = new Promise(function (resolve_, reject_) {- resolve = resolve_;- reject = reject_;- });- promise.resolve = resolve;- promise.reject = reject;- return promise;- };-})();--/**- * Polyfill for Promises:- * The following promise implementation tries to generally implment the- * Promise/A+ spec. Some notable differences from other promise libaries are:- * - There currently isn't a seperate deferred and promise object.- * - Unhandled rejections eventually show an error if they aren't handled.- *- * Based off of the work in:- * https://bugzilla.mozilla.org/show_bug.cgi?id=810490- */-(function PromiseClosure() {- if (globalScope.Promise) {- // Promises existing in the DOM/Worker, checking presence of all/resolve- if (typeof globalScope.Promise.all !== 'function') {- globalScope.Promise.all = function (iterable) {- var count = 0, results = [], resolve, reject;- var promise = new globalScope.Promise(function (resolve_, reject_) {- resolve = resolve_;- reject = reject_;- });- iterable.forEach(function (p, i) {- count++;- p.then(function (result) {- results[i] = result;- count--;- if (count === 0) {- resolve(results);- }- }, reject);- });- if (count === 0) {- resolve(results);- }- return promise;- };- }- if (typeof globalScope.Promise.resolve !== 'function') {- globalScope.Promise.resolve = function (x) {- return new globalScope.Promise(function (resolve) { resolve(x); });- };- }- return;- }- var STATUS_PENDING = 0;- var STATUS_RESOLVED = 1;- var STATUS_REJECTED = 2;-- // In an attempt to avoid silent exceptions, unhandled rejections are- // tracked and if they aren't handled in a certain amount of time an- // error is logged.- var REJECTION_TIMEOUT = 500;-- var HandlerManager = {- handlers: [],- running: false,- unhandledRejections: [],- pendingRejectionCheck: false,-- scheduleHandlers: function scheduleHandlers(promise) {- if (promise._status == STATUS_PENDING) {- return;- }-- this.handlers = this.handlers.concat(promise._handlers);- promise._handlers = [];-- if (this.running) {- return;- }- this.running = true;-- setTimeout(this.runHandlers.bind(this), 0);- },-- runHandlers: function runHandlers() {- var RUN_TIMEOUT = 1; // ms- var timeoutAt = Date.now() + RUN_TIMEOUT;- while (this.handlers.length > 0) {- var handler = this.handlers.shift();-- var nextStatus = handler.thisPromise._status;- var nextValue = handler.thisPromise._value;-- try {- if (nextStatus === STATUS_RESOLVED) {- if (typeof(handler.onResolve) == 'function') {- nextValue = handler.onResolve(nextValue);- }- } else if (typeof(handler.onReject) === 'function') {- nextValue = handler.onReject(nextValue);- nextStatus = STATUS_RESOLVED;-- if (handler.thisPromise._unhandledRejection) {- this.removeUnhandeledRejection(handler.thisPromise);- }- }- } catch (ex) {- nextStatus = STATUS_REJECTED;- nextValue = ex;- }-- handler.nextPromise._updateStatus(nextStatus, nextValue);- if (Date.now() >= timeoutAt) {- break;- }- }-- if (this.handlers.length > 0) {- setTimeout(this.runHandlers.bind(this), 0);- return;- }-- this.running = false;- },-- addUnhandledRejection: function addUnhandledRejection(promise) {- this.unhandledRejections.push({- promise: promise,- time: Date.now()- });- this.scheduleRejectionCheck();- },-- removeUnhandeledRejection: function removeUnhandeledRejection(promise) {- promise._unhandledRejection = false;- for (var i = 0; i < this.unhandledRejections.length; i++) {- if (this.unhandledRejections[i].promise === promise) {- this.unhandledRejections.splice(i);- i--;- }- }- },-- scheduleRejectionCheck: function scheduleRejectionCheck() {- if (this.pendingRejectionCheck) {- return;- }- this.pendingRejectionCheck = true;- setTimeout(function rejectionCheck() {- this.pendingRejectionCheck = false;- var now = Date.now();- for (var i = 0; i < this.unhandledRejections.length; i++) {- if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {- var unhandled = this.unhandledRejections[i].promise._value;- var msg = 'Unhandled rejection: ' + unhandled;- if (unhandled.stack) {- msg += '\n' + unhandled.stack;- }- warn(msg);- this.unhandledRejections.splice(i);- i--;- }- }- if (this.unhandledRejections.length) {- this.scheduleRejectionCheck();- }- }.bind(this), REJECTION_TIMEOUT);- }- };-- function Promise(resolver) {- this._status = STATUS_PENDING;- this._handlers = [];- resolver.call(this, this._resolve.bind(this), this._reject.bind(this));- }- /**- * Builds a promise that is resolved when all the passed in promises are- * resolved.- * @param {array} array of data and/or promises to wait for.- * @return {Promise} New dependant promise.- */- Promise.all = function Promise_all(promises) {- var resolveAll, rejectAll;- var deferred = new Promise(function (resolve, reject) {- resolveAll = resolve;- rejectAll = reject;- });- var unresolved = promises.length;- var results = [];- if (unresolved === 0) {- resolveAll(results);- return deferred;- }- function reject(reason) {- if (deferred._status === STATUS_REJECTED) {- return;- }- results = [];- rejectAll(reason);- }- for (var i = 0, ii = promises.length; i < ii; ++i) {- var promise = promises[i];- var resolve = (function(i) {- return function(value) {- if (deferred._status === STATUS_REJECTED) {- return;- }- results[i] = value;- unresolved--;- if (unresolved === 0) {- resolveAll(results);- }- };- })(i);- if (Promise.isPromise(promise)) {- promise.then(resolve, reject);- } else {- resolve(promise);- }- }- return deferred;- };-- /**- * Checks if the value is likely a promise (has a 'then' function).- * @return {boolean} true if x is thenable- */- Promise.isPromise = function Promise_isPromise(value) {- return value && typeof value.then === 'function';- };- /**- * Creates resolved promise- * @param x resolve value- * @returns {Promise}- */- Promise.resolve = function Promise_resolve(x) {- return new Promise(function (resolve) { resolve(x); });- };-- Promise.prototype = {- _status: null,- _value: null,- _handlers: null,- _unhandledRejection: null,-- _updateStatus: function Promise__updateStatus(status, value) {- if (this._status === STATUS_RESOLVED ||- this._status === STATUS_REJECTED) {- return;- }-- if (status == STATUS_RESOLVED &&- Promise.isPromise(value)) {- value.then(this._updateStatus.bind(this, STATUS_RESOLVED),- this._updateStatus.bind(this, STATUS_REJECTED));- return;- }-- this._status = status;- this._value = value;-- if (status === STATUS_REJECTED && this._handlers.length === 0) {- this._unhandledRejection = true;- HandlerManager.addUnhandledRejection(this);- }-- HandlerManager.scheduleHandlers(this);- },-- _resolve: function Promise_resolve(value) {- this._updateStatus(STATUS_RESOLVED, value);- },-- _reject: function Promise_reject(reason) {- this._updateStatus(STATUS_REJECTED, reason);- },-- then: function Promise_then(onResolve, onReject) {- var nextPromise = new Promise(function (resolve, reject) {- this.resolve = reject;- this.reject = reject;- });- this._handlers.push({- thisPromise: this,- onResolve: onResolve,- onReject: onReject,- nextPromise: nextPromise- });- HandlerManager.scheduleHandlers(this);- return nextPromise;- }- };-- globalScope.Promise = Promise;-})();--var StatTimer = (function StatTimerClosure() {- function rpad(str, pad, length) {- while (str.length < length) {- str += pad;- }- return str;- }- function StatTimer() {- this.started = {};- this.times = [];- this.enabled = true;- }- StatTimer.prototype = {- time: function StatTimer_time(name) {- if (!this.enabled) {- return;- }- if (name in this.started) {- warn('Timer is already running for ' + name);- }- this.started[name] = Date.now();- },- timeEnd: function StatTimer_timeEnd(name) {- if (!this.enabled) {- return;- }- if (!(name in this.started)) {- warn('Timer has not been started for ' + name);- }- this.times.push({- 'name': name,- 'start': this.started[name],- 'end': Date.now()- });- // Remove timer from started so it can be called again.- delete this.started[name];- },- toString: function StatTimer_toString() {- var i, ii;- var times = this.times;- var out = '';- // Find the longest name for padding purposes.- var longest = 0;- for (i = 0, ii = times.length; i < ii; ++i) {- var name = times[i]['name'];- if (name.length > longest) {- longest = name.length;- }- }- for (i = 0, ii = times.length; i < ii; ++i) {- var span = times[i];- var duration = span.end - span.start;- out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';- }- return out;- }- };- return StatTimer;-})();--PDFJS.createBlob = function createBlob(data, contentType) {- if (typeof Blob !== 'undefined') {- return new Blob([data], { type: contentType });- }- // Blob builder is deprecated in FF14 and removed in FF18.- var bb = new MozBlobBuilder();- bb.append(data);- return bb.getBlob(contentType);-};--PDFJS.createObjectURL = (function createObjectURLClosure() {- // Blob/createObjectURL is not available, falling back to data schema.- var digits =- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';-- return function createObjectURL(data, contentType) {- if (!PDFJS.disableCreateObjectURL &&- typeof URL !== 'undefined' && URL.createObjectURL) {- var blob = PDFJS.createBlob(data, contentType);- return URL.createObjectURL(blob);- }-- var buffer = 'data:' + contentType + ';base64,';- for (var i = 0, ii = data.length; i < ii; i += 3) {- var b1 = data[i] & 0xFF;- var b2 = data[i + 1] & 0xFF;- var b3 = data[i + 2] & 0xFF;- var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);- var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;- var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;- buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];- }- return buffer;- };-})();--function MessageHandler(name, comObj) {- this.name = name;- this.comObj = comObj;- this.callbackIndex = 1;- this.postMessageTransfers = true;- var callbacks = this.callbacks = {};- var ah = this.actionHandler = {};-- ah['console_log'] = [function ahConsoleLog(data) {- console.log.apply(console, data);- }];- ah['console_error'] = [function ahConsoleError(data) {- console.error.apply(console, data);- }];- ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {- UnsupportedManager.notify(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 {- error('Cannot resolve callback ' + callbackId);- }- } else if (data.action in ah) {- var action = ah[data.action];- if (data.callbackId) {- var deferred = {};- var promise = new Promise(function (resolve, reject) {- deferred.resolve = resolve;- deferred.reject = reject;- });- deferred.promise = promise;- promise.then(function(resolvedData) {- comObj.postMessage({- isReply: true,- callbackId: data.callbackId,- data: resolvedData- });- });- action[0].call(action[1], data.data, deferred);- } else {- action[0].call(action[1], data.data);- }- } else {- error('Unkown action from worker: ' + data.action);- }- };-}--MessageHandler.prototype = {- on: function messageHandlerOn(actionName, handler, scope) {- var ah = this.actionHandler;- if (ah[actionName]) {- 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.- * @param {Array} [transfers] Optional list of transfers/ArrayBuffers- */- send: function messageHandlerSend(actionName, data, callback, transfers) {- var message = {- action: actionName,- data: data- };- if (callback) {- var callbackId = this.callbackIndex++;- this.callbacks[callbackId] = callback;- message.callbackId = callbackId;- }- if (transfers && this.postMessageTransfers) {- this.comObj.postMessage(message, transfers);- } else {- this.comObj.postMessage(message);- }- }-};--function loadJpegStream(id, imageUrl, objs) {- var img = new Image();- img.onload = (function loadJpegStream_onloadClosure() {- objs.resolve(id, img);- });- img.src = imageUrl;-}---var ColorSpace = (function ColorSpaceClosure() {- // Constructor should define this.numComps, this.defaultColor, this.name- function ColorSpace() {- error('should not call ColorSpace constructor');- }-- ColorSpace.prototype = {- /**- * Converts the color value to the RGB color. The color components are- * located in the src array starting from the srcOffset. Returns the array- * of the rgb components, each value ranging from [0,255].- */- getRgb: function ColorSpace_getRgb(src, srcOffset) {- var rgb = new Uint8Array(3);- this.getRgbItem(src, srcOffset, rgb, 0);- return rgb;- },- /**- * Converts the color value to the RGB color, similar to the getRgb method.- * The result placed into the dest array starting from the destOffset.- */- getRgbItem: function ColorSpace_getRgbItem(src, srcOffset,- dest, destOffset) {- error('Should not call ColorSpace.getRgbItem');- },- /**- * Converts the specified number of the color values to the RGB colors.- * The colors are located in the src array starting from the srcOffset.- * The result is placed into the dest array starting from the destOffset.- * The src array items shall be in [0,2^bits) range, the dest array items- * will be in [0,255] range. alpha01 indicates how many alpha components- * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA- * array).- */- getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- error('Should not call ColorSpace.getRgbBuffer');- },- /**- * Determines the number of bytes required to store the result of the- * conversion done by the getRgbBuffer method. As in getRgbBuffer,- * |alpha01| is either 0 (RGB output) or 1 (RGBA output).- */- getOutputLength: function ColorSpace_getOutputLength(inputLength,- alpha01) {- error('Should not call ColorSpace.getOutputLength');- },- /**- * Returns true if source data will be equal the result/output data.- */- isPassthrough: function ColorSpace_isPassthrough(bits) {- return false;- },- /**- * Fills in the RGB colors in the destination buffer. alpha01 indicates- * how many alpha components there are in the dest array; it will be either- * 0 (RGB array) or 1 (RGBA array).- */- fillRgb: function ColorSpace_fillRgb(dest, originalWidth,- originalHeight, width, height,- actualHeight, bpc, comps, alpha01) {- var count = originalWidth * originalHeight;- var rgbBuf = null;- var numComponentColors = 1 << bpc;- var needsResizing = originalHeight != height || originalWidth != width;- var i, ii;-- if (this.isPassthrough(bpc)) {- rgbBuf = comps;- } else if (this.numComps === 1 && count > numComponentColors &&- this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') {- // Optimization: create a color map when there is just one component and- // we are converting more colors than the size of the color map. We- // don't build the map if the colorspace is gray or rgb since those- // methods are faster than building a map. This mainly offers big speed- // ups for indexed and alternate colorspaces.- //- // TODO it may be worth while to cache the color map. While running- // testing I never hit a cache so I will leave that out for now (perhaps- // we are reparsing colorspaces too much?).- var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) :- new Uint16Array(numComponentColors);- var key;- for (i = 0; i < numComponentColors; i++) {- allColors[i] = i;- }- var colorMap = new Uint8Array(numComponentColors * 3);- this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc,- /* alpha01 = */ 0);-- var destPos, rgbPos;- if (!needsResizing) {- // Fill in the RGB values directly into |dest|.- destPos = 0;- for (i = 0; i < count; ++i) {- key = comps[i] * 3;- dest[destPos++] = colorMap[key];- dest[destPos++] = colorMap[key + 1];- dest[destPos++] = colorMap[key + 2];- destPos += alpha01;- }- } else {- rgbBuf = new Uint8Array(count * 3);- rgbPos = 0;- for (i = 0; i < count; ++i) {- key = comps[i] * 3;- rgbBuf[rgbPos++] = colorMap[key];- rgbBuf[rgbPos++] = colorMap[key + 1];- rgbBuf[rgbPos++] = colorMap[key + 2];- }- }- } else {- if (!needsResizing) {- // Fill in the RGB values directly into |dest|.- this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc,- alpha01);- } else {- rgbBuf = new Uint8Array(count * 3);- this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc,- /* alpha01 = */ 0);- }- }-- if (rgbBuf) {- if (needsResizing) {- rgbBuf = PDFImage.resize(rgbBuf, bpc, 3, originalWidth,- originalHeight, width, height);- }- rgbPos = 0;- destPos = 0;- for (i = 0, ii = width * actualHeight; i < ii; i++) {- dest[destPos++] = rgbBuf[rgbPos++];- dest[destPos++] = rgbBuf[rgbPos++];- dest[destPos++] = rgbBuf[rgbPos++];- destPos += alpha01;- }- }- },- /**- * True if the colorspace has components in the default range of [0, 1].- * This should be true for all colorspaces except for lab color spaces- * which are [0,100], [-128, 127], [-128, 127].- */- usesZeroToOneRange: true- };-- ColorSpace.parse = function ColorSpace_parse(cs, xref, res) {- var IR = ColorSpace.parseToIR(cs, xref, res);- if (IR instanceof AlternateCS) {- return IR;- }- return ColorSpace.fromIR(IR);- };-- ColorSpace.fromIR = function ColorSpace_fromIR(IR) {- var name = isArray(IR) ? IR[0] : IR;- var whitePoint, blackPoint;-- switch (name) {- case 'DeviceGrayCS':- return this.singletons.gray;- case 'DeviceRgbCS':- return this.singletons.rgb;- case 'DeviceCmykCS':- return this.singletons.cmyk;- case 'CalGrayCS':- whitePoint = IR[1].WhitePoint;- blackPoint = IR[1].BlackPoint;- var gamma = IR[1].Gamma;- return new CalGrayCS(whitePoint, blackPoint, gamma);- case 'PatternCS':- var basePatternCS = IR[1];- if (basePatternCS) {- basePatternCS = ColorSpace.fromIR(basePatternCS);- }- return new PatternCS(basePatternCS);- case 'IndexedCS':- var baseIndexedCS = IR[1];- var hiVal = IR[2];- var lookup = IR[3];- return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup);- case 'AlternateCS':- var numComps = IR[1];- var alt = IR[2];- var tintFnIR = IR[3];-- return new AlternateCS(numComps, ColorSpace.fromIR(alt),- PDFFunction.fromIR(tintFnIR));- case 'LabCS':- whitePoint = IR[1].WhitePoint;- blackPoint = IR[1].BlackPoint;- var range = IR[1].Range;- return new LabCS(whitePoint, blackPoint, range);- default:- error('Unkown name ' + name);- }- return null;- };-- ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) {- if (isName(cs)) {- var colorSpaces = res.get('ColorSpace');- if (isDict(colorSpaces)) {- var refcs = colorSpaces.get(cs.name);- if (refcs) {- cs = refcs;- }- }- }-- cs = xref.fetchIfRef(cs);- var mode;-- if (isName(cs)) {- mode = cs.name;- this.mode = mode;-- switch (mode) {- case 'DeviceGray':- case 'G':- return 'DeviceGrayCS';- case 'DeviceRGB':- case 'RGB':- return 'DeviceRgbCS';- case 'DeviceCMYK':- case 'CMYK':- return 'DeviceCmykCS';- case 'Pattern':- return ['PatternCS', null];- default:- error('unrecognized colorspace ' + mode);- }- } else if (isArray(cs)) {- mode = cs[0].name;- this.mode = mode;- var numComps, params;-- switch (mode) {- case 'DeviceGray':- case 'G':- return 'DeviceGrayCS';- case 'DeviceRGB':- case 'RGB':- return 'DeviceRgbCS';- case 'DeviceCMYK':- case 'CMYK':- return 'DeviceCmykCS';- case 'CalGray':- params = cs[1].getAll();- return ['CalGrayCS', params];- case 'CalRGB':- return 'DeviceRgbCS';- case 'ICCBased':- var stream = xref.fetchIfRef(cs[1]);- var dict = stream.dict;- numComps = dict.get('N');- if (numComps == 1) {- return 'DeviceGrayCS';- } else if (numComps == 3) {- return 'DeviceRgbCS';- } else if (numComps == 4) {- return 'DeviceCmykCS';- }- break;- case 'Pattern':- var basePatternCS = cs[1];- if (basePatternCS) {- basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res);- }- return ['PatternCS', basePatternCS];- case 'Indexed':- case 'I':- var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res);- var hiVal = cs[2] + 1;- var lookup = xref.fetchIfRef(cs[3]);- if (isStream(lookup)) {- lookup = lookup.getBytes();- }- return ['IndexedCS', baseIndexedCS, hiVal, lookup];- case 'Separation':- case 'DeviceN':- var name = cs[1];- numComps = 1;- if (isName(name)) {- numComps = 1;- } else if (isArray(name)) {- numComps = name.length;- }- var alt = ColorSpace.parseToIR(cs[2], xref, res);- var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3]));- return ['AlternateCS', numComps, alt, tintFnIR];- case 'Lab':- params = cs[1].getAll();- return ['LabCS', params];- default:- error('unimplemented color space object "' + mode + '"');- }- } else {- error('unrecognized color space object: "' + cs + '"');- }- return null;- };- /**- * Checks if a decode map matches the default decode map for a color space.- * This handles the general decode maps where there are two values per- * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color.- * This does not handle Lab, Indexed, or Pattern decode maps since they are- * slightly different.- * @param {Array} decode Decode map (usually from an image).- * @param {Number} n Number of components the color space has.- */- ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) {- if (!decode) {- return true;- }-- if (n * 2 !== decode.length) {- warn('The decode map is not the correct length');- return true;- }- for (var i = 0, ii = decode.length; i < ii; i += 2) {- if (decode[i] !== 0 || decode[i + 1] != 1) {- return false;- }- }- return true;- };-- ColorSpace.singletons = {- get gray() {- return shadow(this, 'gray', new DeviceGrayCS());- },- get rgb() {- return shadow(this, 'rgb', new DeviceRgbCS());- },- get cmyk() {- return shadow(this, 'cmyk', new DeviceCmykCS());- }- };-- return ColorSpace;-})();--/**- * Alternate color space handles both Separation and DeviceN color spaces. A- * Separation color space is actually just a DeviceN with one color component.- * Both color spaces use a tinting function to convert colors to a base color- * space.- */-var AlternateCS = (function AlternateCSClosure() {- function AlternateCS(numComps, base, tintFn) {- this.name = 'Alternate';- this.numComps = numComps;- this.defaultColor = new Float32Array(numComps);- for (var i = 0; i < numComps; ++i) {- this.defaultColor[i] = 1;- }- this.base = base;- this.tintFn = tintFn;- }-- AlternateCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function AlternateCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var baseNumComps = this.base.numComps;- var input = 'subarray' in src ?- src.subarray(srcOffset, srcOffset + this.numComps) :- Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps);- var tinted = this.tintFn(input);- this.base.getRgbItem(tinted, 0, dest, destOffset);- },- getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var tintFn = this.tintFn;- var base = this.base;- var scale = 1 / ((1 << bits) - 1);- var baseNumComps = base.numComps;- var usesZeroToOneRange = base.usesZeroToOneRange;- var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) &&- alpha01 === 0;- var pos = isPassthrough ? destOffset : 0;- var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count);- var numComps = this.numComps;-- var scaled = new Float32Array(numComps);- var i, j;- for (i = 0; i < count; i++) {- for (j = 0; j < numComps; j++) {- scaled[j] = src[srcOffset++] * scale;- }- var tinted = tintFn(scaled);- if (usesZeroToOneRange) {- for (j = 0; j < baseNumComps; j++) {- baseBuf[pos++] = tinted[j] * 255;- }- } else {- base.getRgbItem(tinted, 0, baseBuf, pos);- pos += baseNumComps;- }- }- if (!isPassthrough) {- base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);- }- },- getOutputLength: function AlternateCS_getOutputLength(inputLength,- alpha01) {- return this.base.getOutputLength(inputLength *- this.base.numComps / this.numComps,- alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };-- return AlternateCS;-})();--var PatternCS = (function PatternCSClosure() {- function PatternCS(baseCS) {- this.name = 'Pattern';- this.base = baseCS;- }- PatternCS.prototype = {};-- return PatternCS;-})();--var IndexedCS = (function IndexedCSClosure() {- function IndexedCS(base, highVal, lookup) {- this.name = 'Indexed';- this.numComps = 1;- this.defaultColor = new Uint8Array([0]);- this.base = base;- this.highVal = highVal;-- var baseNumComps = base.numComps;- var length = baseNumComps * highVal;- var lookupArray;-- if (isStream(lookup)) {- lookupArray = new Uint8Array(length);- var bytes = lookup.getBytes(length);- lookupArray.set(bytes);- } else if (isString(lookup)) {- lookupArray = new Uint8Array(length);- for (var i = 0; i < length; ++i) {- lookupArray[i] = lookup.charCodeAt(i);- }- } else if (lookup instanceof Uint8Array || lookup instanceof Array) {- lookupArray = lookup;- } else {- error('Unrecognized lookup table: ' + lookup);- }- this.lookup = lookupArray;- }-- IndexedCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function IndexedCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var numComps = this.base.numComps;- var start = src[srcOffset] * numComps;- this.base.getRgbItem(this.lookup, start, dest, destOffset);- },- getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var base = this.base;- var numComps = base.numComps;- var outputDelta = base.getOutputLength(numComps, alpha01);- var lookup = this.lookup;-- for (var i = 0; i < count; ++i) {- var lookupPos = src[srcOffset++] * numComps;- base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);- destOffset += outputDelta;- }- },- getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) {- return this.base.getOutputLength(inputLength * this.base.numComps,- alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) {- // indexed color maps shouldn't be changed- return true;- },- usesZeroToOneRange: true- };- return IndexedCS;-})();--var DeviceGrayCS = (function DeviceGrayCSClosure() {- function DeviceGrayCS() {- this.name = 'DeviceGray';- this.numComps = 1;- this.defaultColor = new Float32Array([0]);- }-- DeviceGrayCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var c = (src[srcOffset] * 255) | 0;- c = c < 0 ? 0 : c > 255 ? 255 : c;- dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;- },- getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 255 / ((1 << bits) - 1);- var j = srcOffset, q = destOffset;- for (var i = 0; i < count; ++i) {- var c = (scale * src[j++]) | 0;- dest[q++] = c;- dest[q++] = c;- dest[q++] = c;- q += alpha01;- }- },- getOutputLength: function DeviceGrayCS_getOutputLength(inputLength,- alpha01) {- return inputLength * (3 + alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return DeviceGrayCS;-})();--var DeviceRgbCS = (function DeviceRgbCSClosure() {- function DeviceRgbCS() {- this.name = 'DeviceRGB';- this.numComps = 3;- this.defaultColor = new Float32Array([0, 0, 0]);- }- DeviceRgbCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset,- dest, destOffset) {- var r = (src[srcOffset] * 255) | 0;- var g = (src[srcOffset + 1] * 255) | 0;- var b = (src[srcOffset + 2] * 255) | 0;- dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r;- dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g;- dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b;- },- getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- if (bits === 8 && alpha01 === 0) {- dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);- return;- }- var scale = 255 / ((1 << bits) - 1);- var j = srcOffset, q = destOffset;- for (var i = 0; i < count; ++i) {- dest[q++] = (scale * src[j++]) | 0;- dest[q++] = (scale * src[j++]) | 0;- dest[q++] = (scale * src[j++]) | 0;- q += alpha01;- }- },- getOutputLength: function DeviceRgbCS_getOutputLength(inputLength,- alpha01) {- return (inputLength * (3 + alpha01) / 3) | 0;- },- isPassthrough: function DeviceRgbCS_isPassthrough(bits) {- return bits == 8;- },- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return DeviceRgbCS;-})();--var DeviceCmykCS = (function DeviceCmykCSClosure() {- // The coefficients below was found using numerical analysis: the method of- // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,- // where color_value is the tabular value from the table of sampled RGB colors- // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding- // CMYK color conversion using the estimation below:- // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255- function convertToRgb(src, srcOffset, srcScale, dest, destOffset) {- var c = src[srcOffset + 0] * srcScale;- var m = src[srcOffset + 1] * srcScale;- var y = src[srcOffset + 2] * srcScale;- var k = src[srcOffset + 3] * srcScale;-- var r =- c * (-4.387332384609988 * c + 54.48615194189176 * m +- 18.82290502165302 * y + 212.25662451639585 * k +- -285.2331026137004) +- m * (1.7149763477362134 * m - 5.6096736904047315 * y +- -17.873870861415444 * k - 5.497006427196366) +- y * (-2.5217340131683033 * y - 21.248923337353073 * k +- 17.5119270841813) +- k * (-21.86122147463605 * k - 189.48180835922747) + 255;- var g =- c * (8.841041422036149 * c + 60.118027045597366 * m +- 6.871425592049007 * y + 31.159100130055922 * k +- -79.2970844816548) +- m * (-15.310361306967817 * m + 17.575251261109482 * y +- 131.35250912493976 * k - 190.9453302588951) +- y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +- k * (-20.737325471181034 * k - 187.80453709719578) + 255;- var b =- c * (0.8842522430003296 * c + 8.078677503112928 * m +- 30.89978309703729 * y - 0.23883238689178934 * k +- -14.183576799673286) +- m * (10.49593273432072 * m + 63.02378494754052 * y +- 50.606957656360734 * k - 112.23884253719248) +- y * (0.03296041114873217 * y + 115.60384449646641 * k +- -193.58209356861505) +- k * (-22.33816807309886 * k - 180.12613974708367) + 255;-- dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r;- dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g;- dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b;- }-- function DeviceCmykCS() {- this.name = 'DeviceCMYK';- this.numComps = 4;- this.defaultColor = new Float32Array([0, 0, 0, 1]);- }- DeviceCmykCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset,- dest, destOffset) {- convertToRgb(src, srcOffset, 1, dest, destOffset);- },- getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 1 / ((1 << bits) - 1);- for (var i = 0; i < count; i++) {- convertToRgb(src, srcOffset, scale, dest, destOffset);- srcOffset += 4;- destOffset += 3 + alpha01;- }- },- getOutputLength: function DeviceCmykCS_getOutputLength(inputLength,- alpha01) {- return (inputLength / 4 * (3 + alpha01)) | 0;- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };-- return DeviceCmykCS;-})();--//-// CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245-//-var CalGrayCS = (function CalGrayCSClosure() {- function CalGrayCS(whitePoint, blackPoint, gamma) {- this.name = 'CalGray';- this.numComps = 1;- this.defaultColor = new Float32Array([0]);-- if (!whitePoint) {- error('WhitePoint missing - required for color space CalGray');- }- blackPoint = blackPoint || [0, 0, 0];- gamma = gamma || 1;-- // Translate arguments to spec variables.- this.XW = whitePoint[0];- this.YW = whitePoint[1];- this.ZW = whitePoint[2];-- this.XB = blackPoint[0];- this.YB = blackPoint[1];- this.ZB = blackPoint[2];-- this.G = gamma;-- // Validate variables as per spec.- if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {- error('Invalid WhitePoint components for ' + this.name +- ', no fallback available');- }-- if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {- info('Invalid BlackPoint for ' + this.name + ', falling back to default');- this.XB = this.YB = this.ZB = 0;- }-- if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {- warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB +- ', ZB: ' + this.ZB + ', only default values are supported.');- }-- if (this.G < 1) {- info('Invalid Gamma: ' + this.G + ' for ' + this.name +- ', falling back to default');- this.G = 1;- }- }-- function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) {- // A represents a gray component of a calibrated gray space.- // A <---> AG in the spec- var A = src[srcOffset] * scale;- var AG = Math.pow(A, cs.G);-- // Computes intermediate variables M, L, N as per spec.- // Except if other than default BlackPoint values are used.- var M = cs.XW * AG;- var L = cs.YW * AG;- var N = cs.ZW * AG;-- // Decode XYZ, as per spec.- var X = M;- var Y = L;- var Z = N;-- // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.- // This yields values in range [0, 100].- var Lstar = Math.max(116 * Math.pow(Y, 1 / 3) - 16, 0);-- // Convert values to rgb range [0, 255].- dest[destOffset] = Lstar * 255 / 100;- dest[destOffset + 1] = Lstar * 255 / 100;- dest[destOffset + 2] = Lstar * 255 / 100;- }-- CalGrayCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset,- dest, destOffset) {- convertToRgb(this, src, srcOffset, dest, destOffset, 1);- },- getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var scale = 1 / ((1 << bits) - 1);-- for (var i = 0; i < count; ++i) {- convertToRgb(this, src, srcOffset, dest, destOffset, scale);- srcOffset += 1;- destOffset += 3 + alpha01;- }- },- getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) {- return inputLength * (3 + alpha01);- },- isPassthrough: ColorSpace.prototype.isPassthrough,- fillRgb: ColorSpace.prototype.fillRgb,- isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) {- return ColorSpace.isDefaultDecode(decodeMap, this.numComps);- },- usesZeroToOneRange: true- };- return CalGrayCS;-})();--//-// LabCS: Based on "PDF Reference, Sixth Ed", p.250-//-var LabCS = (function LabCSClosure() {- function LabCS(whitePoint, blackPoint, range) {- this.name = 'Lab';- this.numComps = 3;- this.defaultColor = new Float32Array([0, 0, 0]);-- if (!whitePoint) {- error('WhitePoint missing - required for color space Lab');- }- blackPoint = blackPoint || [0, 0, 0];- range = range || [-100, 100, -100, 100];-- // Translate args to spec variables- this.XW = whitePoint[0];- this.YW = whitePoint[1];- this.ZW = whitePoint[2];- this.amin = range[0];- this.amax = range[1];- this.bmin = range[2];- this.bmax = range[3];-- // These are here just for completeness - the spec doesn't offer any- // formulas that use BlackPoint in Lab- this.XB = blackPoint[0];- this.YB = blackPoint[1];- this.ZB = blackPoint[2];-- // Validate vars as per spec- if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {- error('Invalid WhitePoint components, no fallback available');- }-- if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {- info('Invalid BlackPoint, falling back to default');- this.XB = this.YB = this.ZB = 0;- }-- if (this.amin > this.amax || this.bmin > this.bmax) {- info('Invalid Range, falling back to defaults');- this.amin = -100;- this.amax = 100;- this.bmin = -100;- this.bmax = 100;- }- }-- // Function g(x) from spec- function fn_g(x) {- if (x >= 6 / 29) {- return x * x * x;- } else {- return (108 / 841) * (x - 4 / 29);- }- }-- function decode(value, high1, low2, high2) {- return low2 + (value) * (high2 - low2) / (high1);- }-- // If decoding is needed maxVal should be 2^bits per component - 1.- function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {- // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]- // not the usual [0, 1]. If a command like setFillColor is used the src- // values will already be within the correct range. However, if we are- // converting an image we have to map the values to the correct range given- // above.- // Ls,as,bs <---> L*,a*,b* in the spec- var Ls = src[srcOffset];- var as = src[srcOffset + 1];- var bs = src[srcOffset + 2];- if (maxVal !== false) {- Ls = decode(Ls, maxVal, 0, 100);- as = decode(as, maxVal, cs.amin, cs.amax);- bs = decode(bs, maxVal, cs.bmin, cs.bmax);- }-- // Adjust limits of 'as' and 'bs'- as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as;- bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs;-- // Computes intermediate variables X,Y,Z as per spec- var M = (Ls + 16) / 116;- var L = M + (as / 500);- var N = M - (bs / 200);-- var X = cs.XW * fn_g(L);- var Y = cs.YW * fn_g(M);- var Z = cs.ZW * fn_g(N);-- var r, g, b;- // Using different conversions for D50 and D65 white points,- // per http://www.color.org/srgb.pdf- if (cs.ZW < 1) {- // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)- r = X * 3.1339 + Y * -1.6170 + Z * -0.4906;- g = X * -0.9785 + Y * 1.9160 + Z * 0.0333;- b = X * 0.0720 + Y * -0.2290 + Z * 1.4057;- } else {- // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)- r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;- g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;- b = X * 0.0557 + Y * -0.2040 + Z * 1.0570;- }- // clamp color values to [0,1] range then convert to [0,255] range.- dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0;- dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0;- dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0;- }-- LabCS.prototype = {- getRgb: ColorSpace.prototype.getRgb,- getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) {- convertToRgb(this, src, srcOffset, false, dest, destOffset);- },- getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count,- dest, destOffset, bits,- alpha01) {- var maxVal = (1 << bits) - 1;- for (var i = 0; i < count; i++) {- convertToRgb(this, src, srcOffset, maxVal, dest, destOffset);- srcOffset += 3;- destOffset += 3 + alpha01;- }- },- getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) {- return (inputLength * (3 + alpha01) / 3) | 0;- },- isPassthrough: ColorSpace.prototype.isPassthrough,- isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) {- // XXX: Decoding is handled with the lab conversion because of the strange- // ranges that are used.- return true;- },- usesZeroToOneRange: false- };- return LabCS;-})();----var PDFFunction = (function PDFFunctionClosure() {- var CONSTRUCT_SAMPLED = 0;- var CONSTRUCT_INTERPOLATED = 2;- var CONSTRUCT_STICHED = 3;- var CONSTRUCT_POSTSCRIPT = 4;-- return {- getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps,- str) {- var i, ii;- var length = 1;- for (i = 0, ii = size.length; i < ii; i++) {- length *= size[i];- }- length *= outputSize;-- var array = [];- var codeSize = 0;- var codeBuf = 0;- // 32 is a valid bps so shifting won't work- var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1);-- var strBytes = str.getBytes((length * bps + 7) / 8);- var strIdx = 0;- for (i = 0; i < length; i++) {- while (codeSize < bps) {- codeBuf <<= 8;- codeBuf |= strBytes[strIdx++];- codeSize += 8;- }- codeSize -= bps;- array.push((codeBuf >> codeSize) * sampleMul);- codeBuf &= (1 << codeSize) - 1;- }- return array;- },-- getIR: function PDFFunction_getIR(xref, fn) {- var dict = fn.dict;- if (!dict) {- dict = fn;- }-- var types = [this.constructSampled,- null,- this.constructInterpolated,- this.constructStiched,- this.constructPostScript];-- var typeNum = dict.get('FunctionType');- var typeFn = types[typeNum];- if (!typeFn) {- error('Unknown type of function');- }-- return typeFn.call(this, fn, dict, xref);- },-- fromIR: function PDFFunction_fromIR(IR) {- var type = IR[0];- switch (type) {- case CONSTRUCT_SAMPLED:- return this.constructSampledFromIR(IR);- case CONSTRUCT_INTERPOLATED:- return this.constructInterpolatedFromIR(IR);- case CONSTRUCT_STICHED:- return this.constructStichedFromIR(IR);- //case CONSTRUCT_POSTSCRIPT:- default:- return this.constructPostScriptFromIR(IR);- }- },-- parse: function PDFFunction_parse(xref, fn) {- var IR = this.getIR(xref, fn);- return this.fromIR(IR);- },-- constructSampled: function PDFFunction_constructSampled(str, dict) {- function toMultiArray(arr) {- var inputLength = arr.length;- var outputLength = arr.length / 2;- var out = [];- var index = 0;- for (var i = 0; i < inputLength; i += 2) {- out[index] = [arr[i], arr[i + 1]];- ++index;- }- return out;- }- var domain = dict.get('Domain');- var range = dict.get('Range');-- if (!domain || !range) {- error('No domain or range');- }-- var inputSize = domain.length / 2;- var outputSize = range.length / 2;-- domain = toMultiArray(domain);- range = toMultiArray(range);-- var size = dict.get('Size');- var bps = dict.get('BitsPerSample');- var order = dict.get('Order') || 1;- if (order !== 1) {- // No description how cubic spline interpolation works in PDF32000:2008- // As in poppler, ignoring order, linear interpolation may work as good- info('No support for cubic spline interpolation: ' + order);- }-- var encode = dict.get('Encode');- if (!encode) {- encode = [];- for (var i = 0; i < inputSize; ++i) {- encode.push(0);- encode.push(size[i] - 1);- }- }- encode = toMultiArray(encode);-- var decode = dict.get('Decode');- if (!decode) {- decode = range;- } else {- decode = toMultiArray(decode);- }-- var samples = this.getSampleArray(size, outputSize, bps, str);-- return [- CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size,- outputSize, Math.pow(2, bps) - 1, range- ];- },-- constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) {- // See chapter 3, page 109 of the PDF reference- function interpolate(x, xmin, xmax, ymin, ymax) {- return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin)));- }-- return function constructSampledFromIRResult(args) {- // See chapter 3, page 110 of the PDF reference.- var m = IR[1];- var domain = IR[2];- var encode = IR[3];- var decode = IR[4];- var samples = IR[5];- var size = IR[6];- var n = IR[7];- var mask = IR[8];- var range = IR[9];-- if (m != args.length) {- error('Incorrect number of arguments: ' + m + ' != ' +- args.length);- }-- var x = args;-- // Building the cube vertices: its part and sample index- // http://rjwagner49.com/Mathematics/Interpolation.pdf- var cubeVertices = 1 << m;- var cubeN = new Float64Array(cubeVertices);- var cubeVertex = new Uint32Array(cubeVertices);- var i, j;- for (j = 0; j < cubeVertices; j++) {- cubeN[j] = 1;- }-- var k = n, pos = 1;- // Map x_i to y_j for 0 <= i < m using the sampled function.- for (i = 0; i < m; ++i) {- // x_i' = min(max(x_i, Domain_2i), Domain_2i+1)- var domain_2i = domain[i][0];- var domain_2i_1 = domain[i][1];- var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1);-- // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1,- // Encode_2i, Encode_2i+1)- var e = interpolate(xi, domain_2i, domain_2i_1,- encode[i][0], encode[i][1]);-- // e_i' = min(max(e_i, 0), Size_i - 1)- var size_i = size[i];- e = Math.min(Math.max(e, 0), size_i - 1);-- // Adjusting the cube: N and vertex sample index- var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1;- var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0);- var n1 = e - e0; // (e - e0) / (e1 - e0);- var offset0 = e0 * k;- var offset1 = offset0 + k; // e1 * k- for (j = 0; j < cubeVertices; j++) {- if (j & pos) {- cubeN[j] *= n1;- cubeVertex[j] += offset1;- } else {- cubeN[j] *= n0;- cubeVertex[j] += offset0;- }- }-- k *= size_i;- pos <<= 1;- }-- var y = new Float64Array(n);- for (j = 0; j < n; ++j) {- // Sum all cube vertices' samples portions- var rj = 0;- for (i = 0; i < cubeVertices; i++) {- rj += samples[cubeVertex[i] + j] * cubeN[i];- }-- // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1,- // Decode_2j, Decode_2j+1)- rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);-- // y_j = min(max(r_j, range_2j), range_2j+1)- y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);- }-- return y;- };- },-- constructInterpolated: function PDFFunction_constructInterpolated(str,- dict) {- var c0 = dict.get('C0') || [0];- var c1 = dict.get('C1') || [1];- var n = dict.get('N');-- if (!isArray(c0) || !isArray(c1)) {- error('Illegal dictionary for interpolated function');- }-- var length = c0.length;- var diff = [];- for (var i = 0; i < length; ++i) {- diff.push(c1[i] - c0[i]);- }-- return [CONSTRUCT_INTERPOLATED, c0, diff, n];- },-- constructInterpolatedFromIR:- function PDFFunction_constructInterpolatedFromIR(IR) {- var c0 = IR[1];- var diff = IR[2];- var n = IR[3];-- var length = diff.length;-- return function constructInterpolatedFromIRResult(args) {- var x = n == 1 ? args[0] : Math.pow(args[0], n);-- var out = [];- for (var j = 0; j < length; ++j) {- out.push(c0[j] + (x * diff[j]));- }-- return out;-- };- },-- constructStiched: function PDFFunction_constructStiched(fn, dict, xref) {- var domain = dict.get('Domain');-- if (!domain) {- error('No domain');- }-- var inputSize = domain.length / 2;- if (inputSize != 1) {- error('Bad domain for stiched function');- }-- var fnRefs = dict.get('Functions');- var fns = [];- for (var i = 0, ii = fnRefs.length; i < ii; ++i) {- fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i])));- }-- var bounds = dict.get('Bounds');- var encode = dict.get('Encode');-- return [CONSTRUCT_STICHED, domain, bounds, encode, fns];- },-- constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) {- var domain = IR[1];- var bounds = IR[2];- var encode = IR[3];- var fnsIR = IR[4];- var fns = [];-- for (var i = 0, ii = fnsIR.length; i < ii; i++) {- fns.push(PDFFunction.fromIR(fnsIR[i]));- }-- return function constructStichedFromIRResult(args) {- var clip = function constructStichedFromIRClip(v, min, max) {- if (v > max) {- v = max;- } else if (v < min) {- v = min;- }- return v;- };-- // clip to domain- var v = clip(args[0], domain[0], domain[1]);- // calulate which bound the value is in- for (var i = 0, ii = bounds.length; i < ii; ++i) {- if (v < bounds[i]) {- break;- }- }-- // encode value into domain of function- var dmin = domain[0];- if (i > 0) {- dmin = bounds[i - 1];- }- var dmax = domain[1];- if (i < bounds.length) {- dmax = bounds[i];- }-- var rmin = encode[2 * i];- var rmax = encode[2 * i + 1];-- var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);-- // call the appropriate function- return fns[i]([v2]);- };- },-- constructPostScript: function PDFFunction_constructPostScript(fn, dict,- xref) {- var domain = dict.get('Domain');- var range = dict.get('Range');-- if (!domain) {- error('No domain.');- }-- if (!range) {- error('No range.');- }-- var lexer = new PostScriptLexer(fn);- var parser = new PostScriptParser(lexer);- var code = parser.parse();-- return [CONSTRUCT_POSTSCRIPT, domain, range, code];- },-- constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR(- IR) {- var domain = IR[1];- var range = IR[2];- var code = IR[3];- var numOutputs = range.length / 2;- var evaluator = new PostScriptEvaluator(code);- // Cache the values for a big speed up, the cache size is limited though- // since the number of possible values can be huge from a PS function.- var cache = new FunctionCache();- return function constructPostScriptFromIRResult(args) {- var initialStack = [];- for (var i = 0, ii = (domain.length / 2); i < ii; ++i) {- initialStack.push(args[i]);- }-- var key = initialStack.join('_');- if (cache.has(key)) {- return cache.get(key);- }-- var stack = evaluator.execute(initialStack);- var transformed = [];- for (i = numOutputs - 1; i >= 0; --i) {- var out = stack.pop();- var rangeIndex = 2 * i;- if (out < range[rangeIndex]) {- out = range[rangeIndex];- } else if (out > range[rangeIndex + 1]) {- out = range[rangeIndex + 1];- }- transformed[i] = out;- }- cache.set(key, transformed);- return transformed;- };- }- };-})();--var FunctionCache = (function FunctionCacheClosure() {- // Of 10 PDF's with type4 functions the maxium number of distinct values seen- // was 256. This still may need some tweaking in the future though.- var MAX_CACHE_SIZE = 1024;- function FunctionCache() {- this.cache = {};- this.total = 0;- }- FunctionCache.prototype = {- has: function FunctionCache_has(key) {- return key in this.cache;- },- get: function FunctionCache_get(key) {- return this.cache[key];- },- set: function FunctionCache_set(key, value) {- if (this.total < MAX_CACHE_SIZE) {- this.cache[key] = value;- this.total++;- }- }- };- return FunctionCache;-})();--var PostScriptStack = (function PostScriptStackClosure() {- var MAX_STACK_SIZE = 100;- function PostScriptStack(initialStack) {- this.stack = initialStack || [];- }-- PostScriptStack.prototype = {- push: function PostScriptStack_push(value) {- if (this.stack.length >= MAX_STACK_SIZE) {- error('PostScript function stack overflow.');- }- this.stack.push(value);- },- pop: function PostScriptStack_pop() {- if (this.stack.length <= 0) {- error('PostScript function stack underflow.');- }- return this.stack.pop();- },- copy: function PostScriptStack_copy(n) {- if (this.stack.length + n >= MAX_STACK_SIZE) {- error('PostScript function stack overflow.');- }- var stack = this.stack;- for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) {- stack.push(stack[i]);- }- },- index: function PostScriptStack_index(n) {- this.push(this.stack[this.stack.length - n - 1]);- },- // rotate the last n stack elements p times- roll: function PostScriptStack_roll(n, p) {- var stack = this.stack;- var l = stack.length - n;- var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t;- for (i = l, j = r; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;- }- for (i = l, j = c - 1; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;- }- for (i = c, j = r; i < j; i++, j--) {- t = stack[i]; stack[i] = stack[j]; stack[j] = t;- }- }- };- return PostScriptStack;-})();-var PostScriptEvaluator = (function PostScriptEvaluatorClosure() {- function PostScriptEvaluator(operators) {- this.operators = operators;- }- PostScriptEvaluator.prototype = {- execute: function PostScriptEvaluator_execute(initialStack) {- var stack = new PostScriptStack(initialStack);- var counter = 0;- var operators = this.operators;- var length = operators.length;- var operator, a, b;- while (counter < length) {- operator = operators[counter++];- if (typeof operator == 'number') {- // Operator is really an operand and should be pushed to the stack.- stack.push(operator);- continue;- }- switch (operator) {- // non standard ps operators- case 'jz': // jump if false- b = stack.pop();- a = stack.pop();- if (!a) {- counter = b;- }- break;- case 'j': // jump- a = stack.pop();- counter = a;- break;-- // all ps operators in alphabetical order (excluding if/ifelse)- case 'abs':- a = stack.pop();- stack.push(Math.abs(a));- break;- case 'add':- b = stack.pop();- a = stack.pop();- stack.push(a + b);- break;- case 'and':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a && b);- } else {- stack.push(a & b);- }- break;- case 'atan':- a = stack.pop();- stack.push(Math.atan(a));- break;- case 'bitshift':- b = stack.pop();- a = stack.pop();- if (a > 0) {- stack.push(a << b);- } else {- stack.push(a >> b);- }- break;- case 'ceiling':- a = stack.pop();- stack.push(Math.ceil(a));- break;- case 'copy':- a = stack.pop();- stack.copy(a);- break;- case 'cos':- a = stack.pop();- stack.push(Math.cos(a));- break;- case 'cvi':- a = stack.pop() | 0;- stack.push(a);- break;- case 'cvr':- // noop- break;- case 'div':- b = stack.pop();- a = stack.pop();- stack.push(a / b);- break;- case 'dup':- stack.copy(1);- break;- case 'eq':- b = stack.pop();- a = stack.pop();- stack.push(a == b);- break;- case 'exch':- stack.roll(2, 1);- break;- case 'exp':- b = stack.pop();- a = stack.pop();- stack.push(Math.pow(a, b));- break;- case 'false':- stack.push(false);- break;- case 'floor':- a = stack.pop();- stack.push(Math.floor(a));- break;- case 'ge':- b = stack.pop();- a = stack.pop();- stack.push(a >= b);- break;- case 'gt':- b = stack.pop();- a = stack.pop();- stack.push(a > b);- break;- case 'idiv':- b = stack.pop();- a = stack.pop();- stack.push((a / b) | 0);- break;- case 'index':- a = stack.pop();- stack.index(a);- break;- case 'le':- b = stack.pop();- a = stack.pop();- stack.push(a <= b);- break;- case 'ln':- a = stack.pop();- stack.push(Math.log(a));- break;- case 'log':- a = stack.pop();- stack.push(Math.log(a) / Math.LN10);- break;- case 'lt':- b = stack.pop();- a = stack.pop();- stack.push(a < b);- break;- case 'mod':- b = stack.pop();- a = stack.pop();- stack.push(a % b);- break;- case 'mul':- b = stack.pop();- a = stack.pop();- stack.push(a * b);- break;- case 'ne':- b = stack.pop();- a = stack.pop();- stack.push(a != b);- break;- case 'neg':- a = stack.pop();- stack.push(-b);- break;- case 'not':- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a && b);- } else {- stack.push(a & b);- }- break;- case 'or':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a || b);- } else {- stack.push(a | b);- }- break;- case 'pop':- stack.pop();- break;- case 'roll':- b = stack.pop();- a = stack.pop();- stack.roll(a, b);- break;- case 'round':- a = stack.pop();- stack.push(Math.round(a));- break;- case 'sin':- a = stack.pop();- stack.push(Math.sin(a));- break;- case 'sqrt':- a = stack.pop();- stack.push(Math.sqrt(a));- break;- case 'sub':- b = stack.pop();- a = stack.pop();- stack.push(a - b);- break;- case 'true':- stack.push(true);- break;- case 'truncate':- a = stack.pop();- a = a < 0 ? Math.ceil(a) : Math.floor(a);- stack.push(a);- break;- case 'xor':- b = stack.pop();- a = stack.pop();- if (isBool(a) && isBool(b)) {- stack.push(a != b);- } else {- stack.push(a ^ b);- }- break;- default:- error('Unknown operator ' + operator);- break;- }- }- return stack.stack;- }- };- return PostScriptEvaluator;-})();---var HIGHLIGHT_OFFSET = 4; // px-var SUPPORTED_TYPES = ['Link', 'Text', 'Widget'];--var Annotation = (function AnnotationClosure() {- // 12.5.5: Algorithm: Appearance streams- function getTransformMatrix(rect, bbox, matrix) {- var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix);- var minX = bounds[0];- var minY = bounds[1];- var maxX = bounds[2];- var maxY = bounds[3];-- if (minX === maxX || minY === maxY) {- // From real-life file, bbox was [0, 0, 0, 0]. In this case,- // just apply the transform for rect- return [1, 0, 0, 1, rect[0], rect[1]];- }-- var xRatio = (rect[2] - rect[0]) / (maxX - minX);- var yRatio = (rect[3] - rect[1]) / (maxY - minY);- return [- xRatio,- 0,- 0,- yRatio,- rect[0] - minX * xRatio,- rect[1] - minY * yRatio- ];- }-- function getDefaultAppearance(dict) {- var appearanceState = dict.get('AP');- if (!isDict(appearanceState)) {- return;- }-- var appearance;- var appearances = appearanceState.get('N');- if (isDict(appearances)) {- var as = dict.get('AS');- if (as && appearances.has(as.name)) {- appearance = appearances.get(as.name);- }- } else {- appearance = appearances;- }- return appearance;- }-- function Annotation(params) {- if (params.data) {- this.data = params.data;- return;- }-- var dict = params.dict;- var data = this.data = {};-- data.subtype = dict.get('Subtype').name;- var rect = dict.get('Rect') || [0, 0, 0, 0];- data.rect = Util.normalizeRect(rect);- data.annotationFlags = dict.get('F');-- var color = dict.get('C');- if (isArray(color) && color.length === 3) {- // TODO(mack): currently only supporting rgb; need support different- // colorspaces- data.color = color;- } else {- data.color = [0, 0, 0];- }-- // Some types of annotations have border style dict which has more- // info than the border array- if (dict.has('BS')) {- var borderStyle = dict.get('BS');- data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1;- } else {- var borderArray = dict.get('Border') || [0, 0, 1];- data.borderWidth = borderArray[2] || 0;-- // TODO: implement proper support for annotations with line dash patterns.- var dashArray = borderArray[3];- if (data.borderWidth > 0 && dashArray && isArray(dashArray)) {- var dashArrayLength = dashArray.length;- if (dashArrayLength > 0) {- // According to the PDF specification: the elements in a dashArray- // shall be numbers that are nonnegative and not all equal to zero.- var isInvalid = false;- var numPositive = 0;- for (var i = 0; i < dashArrayLength; i++) {- var validNumber = (+dashArray[i] >= 0);- if (!validNumber) {- isInvalid = true;- break;- } else if (dashArray[i] > 0) {- numPositive++;- }- }- if (isInvalid || numPositive === 0) {- data.borderWidth = 0;- }- }- }- }-- this.appearance = getDefaultAppearance(dict);- data.hasAppearance = !!this.appearance;- }-- Annotation.prototype = {-- getData: function Annotation_getData() {- return this.data;- },-- hasHtml: function Annotation_hasHtml() {- return false;- },-- getHtmlElement: function Annotation_getHtmlElement(commonObjs) {- throw new NotImplementedException(- 'getHtmlElement() should be implemented in subclass');- },-- // TODO(mack): Remove this, it's not really that helpful.- getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect,- borderWidth) {- assert(!isWorker,- 'getEmptyContainer() should be called from main thread');-- var bWidth = borderWidth || 0;-- rect = rect || this.data.rect;- var element = document.createElement(tagName);- element.style.borderWidth = bWidth + 'px';- var width = rect[2] - rect[0] - 2 * bWidth;- var height = rect[3] - rect[1] - 2 * bWidth;- element.style.width = width + 'px';- element.style.height = height + 'px';- return element;- },-- isInvisible: function Annotation_isInvisible() {- var data = this.data;- if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) {- return false;- } else {- return !!(data &&- data.annotationFlags && // Default: not invisible- data.annotationFlags & 0x1); // Invisible- }- },-- isViewable: function Annotation_isViewable() {- var data = this.data;- return !!(!this.isInvisible() &&- data &&- (!data.annotationFlags ||- !(data.annotationFlags & 0x22)) && // Hidden or NoView- data.rect); // rectangle is nessessary- },-- isPrintable: function Annotation_isPrintable() {- var data = this.data;- return !!(!this.isInvisible() &&- data &&- data.annotationFlags && // Default: not printable- data.annotationFlags & 0x4 && // Print- data.rect); // rectangle is nessessary- },-- loadResources: function(keys) {- var promise = new LegacyPromise();- this.appearance.dict.getAsync('Resources').then(function(resources) {- if (!resources) {- promise.resolve();- return;- }- var objectLoader = new ObjectLoader(resources.map,- keys,- resources.xref);- objectLoader.load().then(function() {- promise.resolve(resources);- });- }.bind(this));-- return promise;- },-- getOperatorList: function Annotation_getOperatorList(evaluator) {-- var promise = new LegacyPromise();-- if (!this.appearance) {- promise.resolve(new OperatorList());- return promise;- }-- var data = this.data;-- var appearanceDict = this.appearance.dict;- var resourcesPromise = this.loadResources([- 'ExtGState',- 'ColorSpace',- 'Pattern',- 'Shading',- 'XObject',- 'Font'- // ProcSet- // Properties- ]);- var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1];- var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0];- var transform = getTransformMatrix(data.rect, bbox, matrix);-- var border = data.border;-- resourcesPromise.then(function(resources) {- var opList = new OperatorList();- opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]);- evaluator.getOperatorList(this.appearance, resources, opList);- opList.addOp(OPS.endAnnotation, []);- promise.resolve(opList);-- this.appearance.reset();- }.bind(this));-- return promise;- }- };-- Annotation.getConstructor =- function Annotation_getConstructor(subtype, fieldType) {-- if (!subtype) {- return;- }-- // TODO(mack): Implement FreeText annotations- if (subtype === 'Link') {- return LinkAnnotation;- } else if (subtype === 'Text') {- return TextAnnotation;- } else if (subtype === 'Widget') {- if (!fieldType) {- return;- }-- if (fieldType === 'Tx') {- return TextWidgetAnnotation;- } else {- return WidgetAnnotation;- }- } else {- return Annotation;- }- };-- // TODO(mack): Support loading annotation from data- Annotation.fromData = function Annotation_fromData(data) {- var subtype = data.subtype;- var fieldType = data.fieldType;- var Constructor = Annotation.getConstructor(subtype, fieldType);- if (Constructor) {- return new Constructor({ data: data });- }- };-- Annotation.fromRef = function Annotation_fromRef(xref, ref) {-- var dict = xref.fetchIfRef(ref);- if (!isDict(dict)) {- return;- }-- var subtype = dict.get('Subtype');- subtype = isName(subtype) ? subtype.name : '';- if (!subtype) {- return;- }-- var fieldType = Util.getInheritableProperty(dict, 'FT');- fieldType = isName(fieldType) ? fieldType.name : '';-- var Constructor = Annotation.getConstructor(subtype, fieldType);- if (!Constructor) {- return;- }-- var params = {- dict: dict,- ref: ref,- };-- var annotation = new Constructor(params);-- if (annotation.isViewable() || annotation.isPrintable()) {- return annotation;- } else {- warn('unimplemented annotation type: ' + subtype);- }- };-- Annotation.appendToOperatorList = function Annotation_appendToOperatorList(- annotations, opList, pdfManager, partialEvaluator, intent) {-- function reject(e) {- annotationsReadyPromise.reject(e);- }-- var annotationsReadyPromise = new LegacyPromise();-- var annotationPromises = [];- for (var i = 0, n = annotations.length; i < n; ++i) {- if (intent === 'display' && annotations[i].isViewable() ||- intent === 'print' && annotations[i].isPrintable()) {- annotationPromises.push(- annotations[i].getOperatorList(partialEvaluator));- }- }- Promise.all(annotationPromises).then(function(datas) {- opList.addOp(OPS.beginAnnotations, []);- for (var i = 0, n = datas.length; i < n; ++i) {- var annotOpList = datas[i];- opList.addOpList(annotOpList);- }- opList.addOp(OPS.endAnnotations, []);- annotationsReadyPromise.resolve();- }, reject);-- return annotationsReadyPromise;- };-- return Annotation;-})();-PDFJS.Annotation = Annotation;---var WidgetAnnotation = (function WidgetAnnotationClosure() {-- function WidgetAnnotation(params) {- Annotation.call(this, params);-- if (params.data) {- return;- }-- var dict = params.dict;- var data = this.data;-- data.fieldValue = stringToPDFString(- Util.getInheritableProperty(dict, 'V') || '');- data.alternativeText = stringToPDFString(dict.get('TU') || '');- data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || '';- var fieldType = Util.getInheritableProperty(dict, 'FT');- data.fieldType = isName(fieldType) ? fieldType.name : '';- data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0;- this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty;-- // Building the full field name by collecting the field and- // its ancestors 'T' data and joining them using '.'.- var fieldName = [];- var namedItem = dict;- var ref = params.ref;- while (namedItem) {- var parent = namedItem.get('Parent');- var parentRef = namedItem.getRaw('Parent');- var name = namedItem.get('T');- if (name) {- fieldName.unshift(stringToPDFString(name));- } else {- // The field name is absent, that means more than one field- // with the same name may exist. Replacing the empty name- // with the '`' plus index in the parent's 'Kids' array.- // This is not in the PDF spec but necessary to id the- // the input controls.- var kids = parent.get('Kids');- var j, jj;- for (j = 0, jj = kids.length; j < jj; j++) {- var kidRef = kids[j];- if (kidRef.num == ref.num && kidRef.gen == ref.gen) {- break;- }- }- fieldName.unshift('`' + j);- }- namedItem = parent;- ref = parentRef;- }- data.fullName = fieldName.join('.');- }-- var parent = Annotation.prototype;- Util.inherit(WidgetAnnotation, Annotation, {- isViewable: function WidgetAnnotation_isViewable() {- if (this.data.fieldType === 'Sig') {- warn('unimplemented annotation type: Widget signature');- return false;- }-- return parent.isViewable.call(this);- }- });-- return WidgetAnnotation;-})();--var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() {- function TextWidgetAnnotation(params) {- WidgetAnnotation.call(this, params);-- if (params.data) {- return;- }-- this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q');- }-- // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()- function setTextStyles(element, item, fontObj) {-- var style = element.style;- style.fontSize = item.fontSize + 'px';- style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';-- if (!fontObj) {- return;- }-- style.fontWeight = fontObj.black ?- (fontObj.bold ? 'bolder' : 'bold') :- (fontObj.bold ? 'bold' : 'normal');- style.fontStyle = fontObj.italic ? 'italic' : 'normal';-- var fontName = fontObj.loadedName;- var fontFamily = fontName ? '"' + fontName + '", ' : '';- // Use a reasonable default font if the font doesn't specify a fallback- var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';- style.fontFamily = fontFamily + fallbackName;- }--- var parent = WidgetAnnotation.prototype;- Util.inherit(TextWidgetAnnotation, WidgetAnnotation, {- hasHtml: function TextWidgetAnnotation_hasHtml() {- return !this.data.hasAppearance && !!this.data.fieldValue;- },-- getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');-- var item = this.data;-- var element = this.getEmptyContainer('div');- element.style.display = 'table';-- var content = document.createElement('div');- content.textContent = item.fieldValue;- var textAlignment = item.textAlignment;- content.style.textAlign = ['left', 'center', 'right'][textAlignment];- content.style.verticalAlign = 'middle';- content.style.display = 'table-cell';-- var fontObj = item.fontRefName ?- commonObjs.getData(item.fontRefName) : null;- var cssRules = setTextStyles(content, item, fontObj);-- element.appendChild(content);-- return element;- },-- getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) {- if (this.appearance) {- return Annotation.prototype.getOperatorList.call(this, evaluator);- }-- var promise = new LegacyPromise();- var opList = new OperatorList();- var data = this.data;-- // Even if there is an appearance stream, ignore it. This is the- // behaviour used by Adobe Reader.-- var defaultAppearance = data.defaultAppearance;- if (!defaultAppearance) {- promise.resolve(opList);- return promise;- }-- // Include any font resources found in the default appearance-- var stream = new Stream(stringToBytes(defaultAppearance));- evaluator.getOperatorList(stream, this.fieldResources, opList);- var appearanceFnArray = opList.fnArray;- var appearanceArgsArray = opList.argsArray;- var fnArray = [];- var argsArray = [];-- // TODO(mack): Add support for stroke color- data.rgb = [0, 0, 0];- // TODO THIS DOESN'T MAKE ANY SENSE SINCE THE fnArray IS EMPTY!- for (var i = 0, n = fnArray.length; i < n; ++i) {- var fnId = appearanceFnArray[i];- var args = appearanceArgsArray[i];-- if (fnId === OPS.setFont) {- data.fontRefName = args[0];- var size = args[1];- if (size < 0) {- data.fontDirection = -1;- data.fontSize = -size;- } else {- data.fontDirection = 1;- data.fontSize = size;- }- } else if (fnId === OPS.setFillRGBColor) {- data.rgb = args;- } else if (fnId === OPS.setFillGray) {- var rgbValue = args[0] * 255;- data.rgb = [rgbValue, rgbValue, rgbValue];- }- }- promise.resolve(opList);- return promise;- }- });-- return TextWidgetAnnotation;-})();--var InteractiveAnnotation = (function InteractiveAnnotationClosure() {- function InteractiveAnnotation(params) {- Annotation.call(this, params);- }-- Util.inherit(InteractiveAnnotation, Annotation, {- hasHtml: function InteractiveAnnotation_hasHtml() {- return true;- },-- highlight: function InteractiveAnnotation_highlight() {- if (this.highlightElement &&- this.highlightElement.hasAttribute('hidden')) {- this.highlightElement.removeAttribute('hidden');- }- },-- unhighlight: function InteractiveAnnotation_unhighlight() {- if (this.highlightElement &&- !this.highlightElement.hasAttribute('hidden')) {- this.highlightElement.setAttribute('hidden', true);- }- },-- initContainer: function InteractiveAnnotation_initContainer() {-- var item = this.data;- var rect = item.rect;-- var container = this.getEmptyContainer('section', rect, item.borderWidth);- container.style.backgroundColor = item.color;-- var color = item.color;- var rgb = [];- for (var i = 0; i < 3; ++i) {- rgb[i] = Math.round(color[i] * 255);- }- item.colorCssRgb = Util.makeCssRgb(rgb);-- var highlight = document.createElement('div');- highlight.className = 'annotationHighlight';- highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px';- highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px';- highlight.setAttribute('hidden', true);-- this.highlightElement = highlight;- container.appendChild(this.highlightElement);-- return container;- }- });-- return InteractiveAnnotation;-})();--var TextAnnotation = (function TextAnnotationClosure() {- function TextAnnotation(params) {- InteractiveAnnotation.call(this, params);-- if (params.data) {- return;- }-- var dict = params.dict;- var data = this.data;-- var content = dict.get('Contents');- var title = dict.get('T');- data.content = stringToPDFString(content || '');- data.title = stringToPDFString(title || '');-- if (data.hasAppearance) {- data.name = 'NoIcon';- } else {- data.name = dict.has('Name') ? dict.get('Name').name : 'Note';- }-- if (dict.has('C')) {- data.hasBgColor = true;- }- }-- var ANNOT_MIN_SIZE = 10;-- Util.inherit(TextAnnotation, InteractiveAnnotation, {-- getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) {- assert(!isWorker, 'getHtmlElement() shall be called from main thread');-- var item = this.data;- var rect = item.rect;-- // sanity check because of OOo-generated PDFs- if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {- rect[3] = rect[1] + ANNOT_MIN_SIZE;- }- if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {- rect[2] = rect[0] + (rect[3] - rect[1]); // make it square- }-- var container = this.initContainer();- container.className = 'annotText';-- var image = document.createElement('img');- image.style.height = container.style.height;- image.style.width = container.style.width;- var iconName = item.name;- image.src = PDFJS.imageResourcesPath + 'annotation-' +- iconName.toLowerCase() + '.svg';- image.alt = '[{{type}} Annotation]';- image.dataset.l10nId = 'text_annotation_type';- image.dataset.l10nArgs = JSON.stringify({type: iconName});-- var contentWrapper = document.createElement('div');- contentWrapper.className = 'annotTextContentWrapper';- contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';- contentWrapper.style.top = '-10px';-- var content = document.createElement('div');- content.className = 'annotTextContent';- content.setAttribute('hidden', true);-- var i, ii;- if (item.hasBgColor) {- var color = item.color;- var rgb = [];- for (i = 0; i < 3; ++i) {- // Enlighten the color (70%)- var c = Math.round(color[i] * 255);- rgb[i] = Math.round((255 - c) * 0.7) + c;- }- content.style.backgroundColor = Util.makeCssRgb(rgb);- }-- var title = document.createElement('h1');- var text = document.createElement('p');- title.textContent = item.title;-- if (!item.content && !item.title) {- content.setAttribute('hidden', true);- } else {- var e = document.createElement('span');- var lines = item.content.split(/(?:\r\n?|\n)/);- for (i = 0, ii = lines.length; i < ii; ++i) {- var line = lines[i];- e.appendChild(document.createTextNode(line));- if (i < (ii - 1)) {- e.appendChild(document.createElement('br'));- }- }- text.appendChild(e);-- var pinned = false;-- var showAnnotation = function showAnnotation(pin) {- if (pin) {- pinned = true;- }- if (content.hasAttribute('hidden')) {- container.style.zIndex += 1;- content.removeAttribute('hidden');- }- };-- var hideAnnotation = function hideAnnotation(unpin) {- if (unpin) {- pinned = false;- }- if (!content.hasAttribute('hidden') && !pinned) {- container.style.zIndex -= 1;- content.setAttribute('hidden', true);- }- };-- var toggleAnnotation = function toggleAnnotation() {- if (pinned) {- hideAnnotation(true);- } else {- showAnnotation(true);- }- };-- var self = this;- image.addEventListener('click', function image_clickHandler() {- toggleAnnotation();- }, false);- image.addEventListener('mouseover', function image_mouseOverHandler() {- showAnnotation();- }, false);- image.addEventListener('mouseout', function image_mouseOutHandler() {- hideAnnotation();- }, false);-- content.addEventListener('click', function content_clickHandler() {- hideAnnotation(true);- }, false);- }-- content.appendChild(title);- content.appendChild(text);- contentWrapper.appendChild(content);- container.appendChild(image);- container.appendChild(contentWrapper);-- return container;- }- });-- return TextAnnotation;-})();--var LinkAnnotation = (function LinkAnnotationClosure() {- function LinkAnnotation(params) {- InteractiveAnnotation.call(this, params);-- if (params.data) {- return;- }-- var dict = params.dict;- var data = this.data;-- var action = dict.get('A');- if (action) {- var linkType = action.get('S').name;- if (linkType === 'URI') {- var url = action.get('URI');- if (isName(url)) {- // Some bad PDFs do not put parentheses around relative URLs.- url = '/' + url.name;- } else if (url) {- url = addDefaultProtocolToUrl(url);- }- // TODO: pdf spec mentions urls can be relative to a Base- // entry in the dictionary.- if (!isValidUrl(url, false)) {- url = '';- }- data.url = url;- } else if (linkType === 'GoTo') {- data.dest = action.get('D');- } else if (linkType === 'GoToR') {- var urlDict = action.get('F');- if (isDict(urlDict)) {- // We assume that the 'url' is a Filspec dictionary- // and fetch the url without checking any further- url = urlDict.get('F') || '';- }-- // TODO: pdf reference says that GoToR- // can also have 'NewWindow' attribute- if (!isValidUrl(url, false)) {- url = '';- }- data.url = url;- data.dest = action.get('D');- } else if (linkType === 'Named') {- data.action = action.get('N').name;- } else {- warn('unrecognized link type: ' + linkType);- }- } else if (dict.has('Dest')) {- // simple destination link- var dest = dict.get('Dest');- data.dest = isName(dest) ? dest.name : dest;- }- }-- // Lets URLs beginning with 'www.' default to using the 'http://' protocol.- function addDefaultProtocolToUrl(url) {- if (url && url.indexOf('www.') === 0) {- return ('http://' + url);- }- return url;- }-- Util.inherit(LinkAnnotation, InteractiveAnnotation, {- hasOperatorList: function LinkAnnotation_hasOperatorList() {- return false;- },-- getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) {-- var container = this.initContainer();- container.className = 'annotLink';-- var item = this.data;- var rect = item.rect;-- container.style.borderColor = item.colorCssRgb;- container.style.borderStyle = 'solid';-- var link = document.createElement('a');- link.href = link.title = this.data.url || '';-- container.appendChild(link);-- return container;- }- });-- return LinkAnnotation;-})();---/**- * The maximum allowed image size in total pixels e.g. width * height. Images- * above this value will not be drawn. Use -1 for no limit.- * @var {number}- */-PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?- -1 : PDFJS.maxImageSize);--/**- * The url of where the predefined Adobe CMaps are located. Include trailing- * slash.- * @var {string}- */-PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);--/**- * Specifies if CMaps are binary packed.- * @var {boolean}- */-PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;--/*- * By default fonts are converted to OpenType fonts and loaded via font face- * rules. If disabled, the font will be rendered using a built in font renderer- * that constructs the glyphs with primitive path commands.- * @var {boolean}- */-PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?- false : PDFJS.disableFontFace);--/**- * Path for image resources, mainly for annotation icons. Include trailing- * slash.- * @var {string}- */-PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?- '' : PDFJS.imageResourcesPath);--/**- * Disable the web worker and run all code on the main thread. This will happen- * automatically if the browser doesn't support workers or sending typed arrays- * to workers.- * @var {boolean}- */-PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?- false : PDFJS.disableWorker);--/**- * Path and filename of the worker file. Required when the worker is enabled in- * development mode. If unspecified in the production build, the worker will be- * loaded based on the location of the pdf.js file.- * @var {string}- */-PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);--/**- * Disable range request loading of PDF files. When enabled and if the server- * supports partial content requests then the PDF will be fetched in chunks.- * Enabled (false) by default.- * @var {boolean}- */-PDFJS.disableRange = (PDFJS.disableRange === undefined ?- false : PDFJS.disableRange);--/**- * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js- * will automatically keep fetching more data even if it isn't needed to display- * the current page. This default behavior can be disabled.- * @var {boolean}- */-PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?- false : PDFJS.disableAutoFetch);--/**- * Enables special hooks for debugging PDF.js.- * @var {boolean}- */-PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);--/**- * Enables transfer usage in postMessage for ArrayBuffers.- * @var {boolean}- */-PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?- true : PDFJS.postMessageTransfers);--/**- * Disables URL.createObjectURL usage.- * @var {boolean}- */-PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?- false : PDFJS.disableCreateObjectURL);--/**- * Disables WebGL usage.- * @var {boolean}- */-PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?- true : PDFJS.disableWebGL);--/**- * Controls the logging level.- * The constants from PDFJS.VERBOSITY_LEVELS should be used:- * - errors- * - warnings [default]- * - infos- * @var {number}- */-PDFJS.verbosity = (PDFJS.verbosity === undefined ?- PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);--/**- * Document initialization / loading parameters object.- *- * @typedef {Object} DocumentInitParameters- * @property {string} url - The URL of the PDF.- * @property {TypedArray} data - A typed array with PDF data.- * @property {Object} httpHeaders - Basic authentication headers.- * @property {boolean} withCredentials - Indicates whether or not cross-site- * Access-Control requests should be made using credentials such as cookies- * or authorization headers. The default is false.- * @property {string} password - For decrypting password-protected PDFs.- * @property {TypedArray} initialData - A typed array with the first portion or- * all of the pdf data. Used by the extension since some data is already- * loaded before the switch to range requests.- */--/**- * This is the main entry point for loading a PDF and interacting with it.- * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)- * is used, which means it must follow the same origin rules that any XHR does- * e.g. No cross domain requests without CORS.- *- * @param {string|TypedArray|DocumentInitParameters} source Can be a url to- * where a PDF is located, a typed array (Uint8Array) already populated with- * data or parameter object.- *- * @param {Object} pdfDataRangeTransport is optional. It is used if you want- * to manually serve range requests for data in the PDF. See viewer.js for- * an example of pdfDataRangeTransport's interface.- *- * @param {function} passwordCallback is optional. It is used to request a- * password if wrong or no password was provided. The callback receives two- * parameters: function that needs to be called with new password and reason- * (see {PasswordResponses}).- *- * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy}- * object.- */-PDFJS.getDocument = function getDocument(source,- pdfDataRangeTransport,- passwordCallback,- progressCallback) {- var workerInitializedPromise, workerReadyPromise, transport;-- if (typeof source === 'string') {- source = { url: source };- } else if (isArrayBuffer(source)) {- source = { data: source };- } else if (typeof source !== 'object') {- error('Invalid parameter in getDocument, need either Uint8Array, ' +- 'string or a parameter object');- }-- if (!source.url && !source.data) {- error('Invalid parameter array, need either .data or .url');- }-- // copy/use all keys as is except 'url' -- full path is required- var params = {};- for (var key in source) {- if (key === 'url' && typeof window !== 'undefined') {- params[key] = combineUrl(window.location.href, source[key]);- continue;- }- params[key] = source[key];- }-- workerInitializedPromise = new PDFJS.LegacyPromise();- workerReadyPromise = new PDFJS.LegacyPromise();- transport = new WorkerTransport(workerInitializedPromise, workerReadyPromise,- pdfDataRangeTransport, progressCallback);- workerInitializedPromise.then(function transportInitialized() {- transport.passwordCallback = passwordCallback;- transport.fetchDocument(params);- });- return workerReadyPromise;-};--/**- * Proxy to a PDFDocument in the worker thread. Also, contains commonly used- * properties that can be read synchronously.- * @class- */-var PDFDocumentProxy = (function PDFDocumentProxyClosure() {- function PDFDocumentProxy(pdfInfo, transport) {- this.pdfInfo = pdfInfo;- this.transport = transport;- }- PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {- /**- * @return {number} Total number of pages the PDF contains.- */- get numPages() {- return this.pdfInfo.numPages;- },- /**- * @return {string} A unique ID to identify a PDF. Not guaranteed to be- * unique.- */- get fingerprint() {- return this.pdfInfo.fingerprint;- },- /**- * @param {number} pageNumber The page number to get. The first page is 1.- * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}- * object.- */- getPage: function PDFDocumentProxy_getPage(pageNumber) {- return this.transport.getPage(pageNumber);- },- /**- * @param {{num: number, gen: number}} ref The page reference. Must have- * the 'num' and 'gen' properties.- * @return {Promise} A promise that is resolved with the page index that is- * associated with the reference.- */- getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {- return this.transport.getPageIndex(ref);- },- /**- * @return {Promise} A promise that is resolved with a lookup table for- * mapping named destinations to reference numbers.- */- getDestinations: function PDFDocumentProxy_getDestinations() {- return this.transport.getDestinations();- },- /**- * @return {Promise} A promise that is resolved with an array of all the- * JavaScript strings in the name tree.- */- getJavaScript: function PDFDocumentProxy_getJavaScript() {- var promise = new PDFJS.LegacyPromise();- var js = this.pdfInfo.javaScript;- promise.resolve(js);- return promise;- },- /**- * @return {Promise} A promise that is resolved with an {Array} that is a- * tree outline (if it has one) of the PDF. The tree is in the format of:- * [- * {- * title: string,- * bold: boolean,- * italic: boolean,- * color: rgb array,- * dest: dest obj,- * items: array of more items like this- * },- * ...- * ].- */- getOutline: function PDFDocumentProxy_getOutline() {- var promise = new PDFJS.LegacyPromise();- var outline = this.pdfInfo.outline;- promise.resolve(outline);- return promise;- },- /**- * @return {Promise} A promise that is resolved with an {Object} that has- * info and metadata properties. Info is an {Object} filled with anything- * available in the information dictionary and similarly metadata is a- * {Metadata} object with information from the metadata section of the PDF.- */- getMetadata: function PDFDocumentProxy_getMetadata() {- var promise = new PDFJS.LegacyPromise();- var info = this.pdfInfo.info;- var metadata = this.pdfInfo.metadata;- promise.resolve({- info: info,- metadata: (metadata ? new PDFJS.Metadata(metadata) : null)- });- return promise;- },- /**- * @return {Promise} A promise that is resolved with a TypedArray that has- * the raw data from the PDF.- */- getData: function PDFDocumentProxy_getData() {- var promise = new PDFJS.LegacyPromise();- this.transport.getData(promise);- return promise;- },- /**- * @return {Promise} A promise that is resolved when the document's data- * is loaded. It is resolved with an {Object} that contains the length- * property that indicates size of the PDF data in bytes.- */- getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {- return this.transport.downloadInfoPromise;- },- /**- * Cleans up resources allocated by the document, e.g. created @font-face.- */- cleanup: function PDFDocumentProxy_cleanup() {- this.transport.startCleanup();- },- /**- * Destroys current document instance and terminates worker.- */- destroy: function PDFDocumentProxy_destroy() {- this.transport.destroy();- }- };- return PDFDocumentProxy;-})();--/**- * Page text content.- *- * @typedef {Object} TextContent- * @property {array} items - array of {@link TextItem}- * @property {Object} styles - {@link TextStyles} objects, indexed by font- * name.- */--/**- * Page text content part.- *- * @typedef {Object} TextItem- * @property {string} str - text content.- * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.- * @property {array} transform - transformation matrix.- * @property {number} width - width in device space.- * @property {number} height - height in device space.- * @property {string} fontName - font name used by pdf.js for converted font.- */--/**- * Text style.- *- * @typedef {Object} TextStyle- * @property {number} ascent - font ascent.- * @property {number} descent - font descent.- * @property {boolean} vertical - text is in vertical mode.- * @property {string} fontFamily - possible font family- */--/**- * Page render parameters.- *- * @typedef {Object} RenderParameters- * @property {Object} canvasContext - A 2D context of a DOM Canvas object.- * @property {PageViewport} viewport - Rendering viewport obtained by- * calling of PDFPage.getViewport method.- * @property {string} intent - Rendering intent, can be 'display' or 'print'- * (default value is 'display').- * @property {Object} imageLayer - (optional) An object that has beginLayout,- * endLayout and appendImage functions.- * @property {function} continueCallback - (optional) A function that will be- * called each time the rendering is paused. To continue- * rendering call the function that is the first argument- * to the callback.- */--/**- * Proxy to a PDFPage in the worker thread.- * @class- */-var PDFPageProxy = (function PDFPageProxyClosure() {- function PDFPageProxy(pageInfo, transport) {- this.pageInfo = pageInfo;- this.transport = transport;- this.stats = new StatTimer();- this.stats.enabled = !!globalScope.PDFJS.enableStats;- this.commonObjs = transport.commonObjs;- this.objs = new PDFObjects();- this.cleanupAfterRender = false;- this.pendingDestroy = false;- this.intentStates = {};- }- PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {- /**- * @return {number} Page number of the page. First page is 1.- */- get pageNumber() {- return this.pageInfo.pageIndex + 1;- },- /**- * @return {number} The number of degrees the page is rotated clockwise.- */- get rotate() {- return this.pageInfo.rotate;- },- /**- * @return {Object} The reference that points to this page. It has 'num' and- * 'gen' properties.- */- get ref() {- return this.pageInfo.ref;- },- /**- * @return {Array} An array of the visible portion of the PDF page in the- * user space units - [x1, y1, x2, y2].- */- get view() {- return this.pageInfo.view;- },- /**- * @param {number} scale The desired scale of the viewport.- * @param {number} rotate Degrees to rotate the viewport. If omitted this- * defaults to the page rotation.- * @return {PageViewport} Contains 'width' and 'height' properties along- * with transforms required for rendering.- */- getViewport: function PDFPageProxy_getViewport(scale, rotate) {- if (arguments.length < 2) {- rotate = this.rotate;- }- return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);- },- /**- * @return {Promise} A promise that is resolved with an {Array} of the- * annotation objects.- */- getAnnotations: function PDFPageProxy_getAnnotations() {- if (this.annotationsPromise) {- return this.annotationsPromise;- }-- var promise = new PDFJS.LegacyPromise();- this.annotationsPromise = promise;- this.transport.getAnnotations(this.pageInfo.pageIndex);- return promise;- },- /**- * Begins the process of rendering a page to the desired context.- * @param {RenderParameters} params Page render parameters.- * @return {RenderTask} An object that contains the promise, which- * is resolved when the page finishes rendering.- */- render: function PDFPageProxy_render(params) {- var stats = this.stats;- stats.time('Overall');-- // If there was a pending destroy cancel it so no cleanup happens during- // this call to render.- this.pendingDestroy = false;-- var renderingIntent = ('intent' in params ?- (params.intent == 'print' ? 'print' : 'display') : 'display');-- if (!this.intentStates[renderingIntent]) {- this.intentStates[renderingIntent] = {};- }- var intentState = this.intentStates[renderingIntent];-- // If there is no displayReadyPromise yet, then the operatorList was never- // requested before. Make the request and create the promise.- if (!intentState.displayReadyPromise) {- intentState.receivingOperatorList = true;- intentState.displayReadyPromise = new LegacyPromise();- intentState.operatorList = {- fnArray: [],- argsArray: [],- lastChunk: false- };-- this.stats.time('Page Request');- this.transport.messageHandler.send('RenderPageRequest', {- pageIndex: this.pageNumber - 1,- intent: renderingIntent- });- }-- var internalRenderTask = new InternalRenderTask(complete, params,- this.objs,- this.commonObjs,- intentState.operatorList,- this.pageNumber);- if (!intentState.renderTasks) {- intentState.renderTasks = [];- }- intentState.renderTasks.push(internalRenderTask);- var renderTask = new RenderTask(internalRenderTask);-- var self = this;- intentState.displayReadyPromise.then(- function pageDisplayReadyPromise(transparency) {- if (self.pendingDestroy) {- complete();- return;- }- stats.time('Rendering');- internalRenderTask.initalizeGraphics(transparency);- internalRenderTask.operatorListChanged();- },- function pageDisplayReadPromiseError(reason) {- complete(reason);- }- );-- function complete(error) {- var i = intentState.renderTasks.indexOf(internalRenderTask);- if (i >= 0) {- intentState.renderTasks.splice(i, 1);- }-- if (self.cleanupAfterRender) {- self.pendingDestroy = true;- }- self._tryDestroy();-- if (error) {- renderTask.promise.reject(error);- } else {- renderTask.promise.resolve();- }- stats.timeEnd('Rendering');- stats.timeEnd('Overall');- }-- return renderTask;- },- /**- * @return {Promise} That is resolved a {@link TextContent}- * object that represent the page text content.- */- getTextContent: function PDFPageProxy_getTextContent() {- var promise = new PDFJS.LegacyPromise();- this.transport.messageHandler.send('GetTextContent', {- pageIndex: this.pageNumber - 1- },- function textContentCallback(textContent) {- promise.resolve(textContent);- }- );- return promise;- },- /**- * Destroys resources allocated by the page.- */- destroy: function PDFPageProxy_destroy() {- this.pendingDestroy = true;- this._tryDestroy();- },- /**- * For internal use only. Attempts to clean up if rendering is in a state- * where that's possible.- * @ignore- */- _tryDestroy: function PDFPageProxy__destroy() {- if (!this.pendingDestroy ||- Object.keys(this.intentStates).some(function(intent) {- var intentState = this.intentStates[intent];- return (intentState.renderTasks.length !== 0 ||- intentState.receivingOperatorList);- }, this)) {- return;- }-- Object.keys(this.intentStates).forEach(function(intent) {- delete this.intentStates[intent];- }, this);- this.objs.clear();- this.pendingDestroy = false;- },- /**- * For internal use only.- * @ignore- */- _startRenderPage: function PDFPageProxy_startRenderPage(transparency,- intent) {- var intentState = this.intentStates[intent];- intentState.displayReadyPromise.resolve(transparency);- },- /**- * For internal use only.- * @ignore- */- _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,- intent) {- var intentState = this.intentStates[intent];- var i, ii;- // Add the new chunk to the current operator list.- for (i = 0, ii = operatorListChunk.length; i < ii; i++) {- intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);- intentState.operatorList.argsArray.push(- operatorListChunk.argsArray[i]);- }- intentState.operatorList.lastChunk = operatorListChunk.lastChunk;-- // Notify all the rendering tasks there are more operators to be consumed.- for (i = 0; i < intentState.renderTasks.length; i++) {- intentState.renderTasks[i].operatorListChanged();- }-- if (operatorListChunk.lastChunk) {- intentState.receivingOperatorList = false;- this._tryDestroy();- }- }- };- return PDFPageProxy;-})();--/**- * For internal use only.- * @ignore- */-var WorkerTransport = (function WorkerTransportClosure() {- function WorkerTransport(workerInitializedPromise, workerReadyPromise,- pdfDataRangeTransport, progressCallback) {- this.pdfDataRangeTransport = pdfDataRangeTransport;-- this.workerReadyPromise = workerReadyPromise;- this.progressCallback = progressCallback;- this.commonObjs = new PDFObjects();-- this.pageCache = [];- this.pagePromises = [];- this.downloadInfoPromise = new PDFJS.LegacyPromise();- this.passwordCallback = null;-- // If worker support isn't disabled explicit and the browser has worker- // support, create a new web worker and test if it/the browser fullfills- // all requirements to run parts of pdf.js in a web worker.- // Right now, the requirement is, that an Uint8Array is still an Uint8Array- // as it arrives on the worker. Chrome added this with version 15.- if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {- var workerSrc = PDFJS.workerSrc;- if (!workerSrc) {- error('No PDFJS.workerSrc specified');- }-- try {- // Some versions of FF can't create a worker on localhost, see:- // https://bugzilla.mozilla.org/show_bug.cgi?id=683280- var worker = new Worker(workerSrc);- var messageHandler = new MessageHandler('main', worker);- this.messageHandler = messageHandler;-- messageHandler.on('test', function transportTest(data) {- var supportTypedArray = data && data.supportTypedArray;- if (supportTypedArray) {- this.worker = worker;- if (!data.supportTransfers) {- PDFJS.postMessageTransfers = false;- }- this.setupMessageHandler(messageHandler);- workerInitializedPromise.resolve();- } else {- globalScope.PDFJS.disableWorker = true;- this.loadFakeWorkerFiles().then(function() {- this.setupFakeWorker();- workerInitializedPromise.resolve();- }.bind(this));- }- }.bind(this));-- var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);- // Some versions of Opera throw a DATA_CLONE_ERR on serializing the- // typed array. Also, checking if we can use transfers.- try {- messageHandler.send('test', testObj, null, [testObj.buffer]);- } catch (ex) {- info('Cannot use postMessage transfers');- testObj[0] = 0;- messageHandler.send('test', testObj);- }- return;- } catch (e) {- info('The worker has been disabled.');- }- }- // Either workers are disabled, not supported or have thrown an exception.- // Thus, we fallback to a faked worker.- globalScope.PDFJS.disableWorker = true;- this.loadFakeWorkerFiles().then(function() {- this.setupFakeWorker();- workerInitializedPromise.resolve();- }.bind(this));- }- WorkerTransport.prototype = {- destroy: function WorkerTransport_destroy() {- this.pageCache = [];- this.pagePromises = [];- var self = this;- this.messageHandler.send('Terminate', null, function () {- FontLoader.clear();- if (self.worker) {- self.worker.terminate();- }- });- },-- loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() {- if (!PDFJS.fakeWorkerFilesLoadedPromise) {- PDFJS.fakeWorkerFilesLoadedPromise = new LegacyPromise();- // In the developer build load worker_loader which in turn loads all the- // other files and resolves the promise. In production only the- // pdf.worker.js file is needed.- Util.loadScript(PDFJS.workerSrc, function() {- PDFJS.fakeWorkerFilesLoadedPromise.resolve();- });- }- return PDFJS.fakeWorkerFilesLoadedPromise;- },-- setupFakeWorker: function WorkerTransport_setupFakeWorker() {- warn('Setting up fake worker.');- // If we don't use a worker, just post/sendMessage to the main thread.- var fakeWorker = {- postMessage: function WorkerTransport_postMessage(obj) {- fakeWorker.onmessage({data: obj});- },- terminate: function WorkerTransport_terminate() {}- };-- var messageHandler = new MessageHandler('main', fakeWorker);- this.setupMessageHandler(messageHandler);-- // If the main thread is our worker, setup the handling for the messages- // the main thread sends to it self.- PDFJS.WorkerMessageHandler.setup(messageHandler);- },-- setupMessageHandler:- function WorkerTransport_setupMessageHandler(messageHandler) {- this.messageHandler = messageHandler;-- function updatePassword(password) {- messageHandler.send('UpdatePassword', password);- }-- var pdfDataRangeTransport = this.pdfDataRangeTransport;- if (pdfDataRangeTransport) {- pdfDataRangeTransport.addRangeListener(function(begin, chunk) {- messageHandler.send('OnDataRange', {- begin: begin,- chunk: chunk- });- });-- pdfDataRangeTransport.addProgressListener(function(loaded) {- messageHandler.send('OnDataProgress', {- loaded: loaded- });- });-- messageHandler.on('RequestDataRange',- function transportDataRange(data) {- pdfDataRangeTransport.requestDataRange(data.begin, data.end);- }, this);- }-- messageHandler.on('GetDoc', function transportDoc(data) {- var pdfInfo = data.pdfInfo;- this.numPages = data.pdfInfo.numPages;- var pdfDocument = new PDFDocumentProxy(pdfInfo, this);- this.pdfDocument = pdfDocument;- this.workerReadyPromise.resolve(pdfDocument);- }, this);-- messageHandler.on('NeedPassword', function transportPassword(data) {- if (this.passwordCallback) {- return this.passwordCallback(updatePassword,- PasswordResponses.NEED_PASSWORD);- }- this.workerReadyPromise.reject(data.exception.message, data.exception);- }, this);-- messageHandler.on('IncorrectPassword', function transportBadPass(data) {- if (this.passwordCallback) {- return this.passwordCallback(updatePassword,- PasswordResponses.INCORRECT_PASSWORD);- }- this.workerReadyPromise.reject(data.exception.message, data.exception);- }, this);-- messageHandler.on('InvalidPDF', function transportInvalidPDF(data) {- this.workerReadyPromise.reject(data.exception.name, data.exception);- }, this);-- messageHandler.on('MissingPDF', function transportMissingPDF(data) {- this.workerReadyPromise.reject(data.exception.message, data.exception);- }, this);-- messageHandler.on('UnknownError', function transportUnknownError(data) {- this.workerReadyPromise.reject(data.exception.message, data.exception);- }, this);-- messageHandler.on('DataLoaded', function transportPage(data) {- this.downloadInfoPromise.resolve(data);- }, this);-- messageHandler.on('GetPage', function transportPage(data) {- var pageInfo = data.pageInfo;- var page = new PDFPageProxy(pageInfo, this);- this.pageCache[pageInfo.pageIndex] = page;- var promise = this.pagePromises[pageInfo.pageIndex];- promise.resolve(page);- }, this);-- messageHandler.on('GetAnnotations', function transportAnnotations(data) {- var annotations = data.annotations;- var promise = this.pageCache[data.pageIndex].annotationsPromise;- promise.resolve(annotations);- }, this);-- messageHandler.on('StartRenderPage', function transportRender(data) {- var page = this.pageCache[data.pageIndex];-- page.stats.timeEnd('Page Request');- page._startRenderPage(data.transparency, data.intent);- }, this);-- messageHandler.on('RenderPageChunk', function transportRender(data) {- var page = this.pageCache[data.pageIndex];-- page._renderPageChunk(data.operatorList, data.intent);- }, this);-- messageHandler.on('commonobj', function transportObj(data) {- var id = data[0];- var type = data[1];- if (this.commonObjs.hasData(id)) {- return;- }-- switch (type) {- case 'Font':- var exportedData = data[2];-- var font;- if ('error' in exportedData) {- var error = exportedData.error;- warn('Error during font loading: ' + error);- this.commonObjs.resolve(id, error);- break;- } else {- font = new FontFace(exportedData);- }-- FontLoader.bind(- [font],- function fontReady(fontObjs) {- this.commonObjs.resolve(id, font);- }.bind(this)- );- break;- case 'FontPath':- this.commonObjs.resolve(id, data[2]);- break;- default:- error('Got unknown common object type ' + type);- }- }, this);-- messageHandler.on('obj', function transportObj(data) {- var id = data[0];- var pageIndex = data[1];- var type = data[2];- var pageProxy = this.pageCache[pageIndex];- var imageData;- if (pageProxy.objs.hasData(id)) {- return;- }-- switch (type) {- case 'JpegStream':- imageData = data[3];- loadJpegStream(id, imageData, pageProxy.objs);- break;- case 'Image':- imageData = data[3];- pageProxy.objs.resolve(id, imageData);-- // heuristics that will allow not to store large data- var MAX_IMAGE_SIZE_TO_STORE = 8000000;- if (imageData && 'data' in imageData &&- imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {- pageProxy.cleanupAfterRender = true;- }- break;- default:- error('Got unknown object type ' + type);- }- }, this);-- messageHandler.on('DocProgress', function transportDocProgress(data) {- if (this.progressCallback) {- this.progressCallback({- loaded: data.loaded,- total: data.total- });- }- }, this);-- messageHandler.on('DocError', function transportDocError(data) {- this.workerReadyPromise.reject(data);- }, this);-- messageHandler.on('PageError', function transportError(data, intent) {- var page = this.pageCache[data.pageNum - 1];- var intentState = page.intentStates[intent];- if (intentState.displayReadyPromise) {- intentState.displayReadyPromise.reject(data.error);- } else {- error(data.error);- }- }, this);-- messageHandler.on('JpegDecode', function(data, deferred) {- var imageUrl = data[0];- var components = data[1];- if (components != 3 && components != 1) {- error('Only 3 component or 1 component can be returned');- }-- var img = new Image();- img.onload = (function messageHandler_onloadClosure() {- var width = img.width;- var height = img.height;- var size = width * height;- var rgbaLength = size * 4;- var buf = new Uint8Array(size * components);- var tmpCanvas = createScratchCanvas(width, height);- var tmpCtx = tmpCanvas.getContext('2d');- tmpCtx.drawImage(img, 0, 0);- var data = tmpCtx.getImageData(0, 0, width, height).data;- var i, j;-- if (components == 3) {- for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {- buf[j] = data[i];- buf[j + 1] = data[i + 1];- buf[j + 2] = data[i + 2];- }- } else if (components == 1) {- for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {- buf[j] = data[i];- }- }- deferred.resolve({ data: buf, width: width, height: height});- }).bind(this);- img.src = imageUrl;- });- },-- fetchDocument: function WorkerTransport_fetchDocument(source) {- source.disableAutoFetch = PDFJS.disableAutoFetch;- source.chunkedViewerLoading = !!this.pdfDataRangeTransport;- this.messageHandler.send('GetDocRequest', {- source: source,- disableRange: PDFJS.disableRange,- maxImageSize: PDFJS.maxImageSize,- cMapUrl: PDFJS.cMapUrl,- cMapPacked: PDFJS.cMapPacked,- disableFontFace: PDFJS.disableFontFace,- disableCreateObjectURL: PDFJS.disableCreateObjectURL,- verbosity: PDFJS.verbosity- });- },-- getData: function WorkerTransport_getData(promise) {- this.messageHandler.send('GetData', null, function(data) {- promise.resolve(data);- });- },-- getPage: function WorkerTransport_getPage(pageNumber, promise) {- if (pageNumber <= 0 || pageNumber > this.numPages ||- (pageNumber|0) !== pageNumber) {- var pagePromise = new PDFJS.LegacyPromise();- pagePromise.reject(new Error('Invalid page request'));- return pagePromise;- }-- var pageIndex = pageNumber - 1;- if (pageIndex in this.pagePromises) {- return this.pagePromises[pageIndex];- }- promise = new PDFJS.LegacyPromise();- this.pagePromises[pageIndex] = promise;- this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex });- return promise;- },-- getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {- var promise = new PDFJS.LegacyPromise();- this.messageHandler.send('GetPageIndex', { ref: ref },- function (pageIndex) {- promise.resolve(pageIndex);- }- );- return promise;- },-- getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {- this.messageHandler.send('GetAnnotationsRequest',- { pageIndex: pageIndex });- },-- getDestinations: function WorkerTransport_getDestinations() {- var promise = new PDFJS.LegacyPromise();- this.messageHandler.send('GetDestinations', null,- function transportDestinations(destinations) {- promise.resolve(destinations);- }- );- return promise;- },-- startCleanup: function WorkerTransport_startCleanup() {- this.messageHandler.send('Cleanup', null,- function endCleanup() {- for (var i = 0, ii = this.pageCache.length; i < ii; i++) {- var page = this.pageCache[i];- if (page) {- page.destroy();- }- }- this.commonObjs.clear();- FontLoader.clear();- }.bind(this)- );- }- };- return WorkerTransport;--})();--/**- * A PDF document and page is built of many objects. E.g. there are objects- * for fonts, images, rendering code and such. These objects might get processed- * inside of a worker. The `PDFObjects` implements some basic functions to- * manage these objects.- * @ignore- */-var PDFObjects = (function PDFObjectsClosure() {- function PDFObjects() {- this.objs = {};- }-- PDFObjects.prototype = {- /**- * Internal function.- * Ensures there is an object defined for `objId`.- */- ensureObj: function PDFObjects_ensureObj(objId) {- if (this.objs[objId]) {- return this.objs[objId];- }-- var obj = {- promise: new LegacyPromise(),- data: null,- resolved: false- };- this.objs[objId] = obj;-- return obj;- },-- /**- * If called *without* callback, this returns the data of `objId` but the- * object needs to be resolved. If it isn't, this function throws.- *- * If called *with* a callback, the callback is called with the data of the- * object once the object is resolved. That means, if you call this- * function and the object is already resolved, the callback gets called- * right away.- */- get: function PDFObjects_get(objId, callback) {- // If there is a callback, then the get can be async and the object is- // not required to be resolved right now- if (callback) {- this.ensureObj(objId).promise.then(callback);- return null;- }-- // If there isn't a callback, the user expects to get the resolved data- // directly.- var obj = this.objs[objId];-- // If there isn't an object yet or the object isn't resolved, then the- // data isn't ready yet!- if (!obj || !obj.resolved) {- error('Requesting object that isn\'t resolved yet ' + objId);- }-- return obj.data;- },-- /**- * Resolves the object `objId` with optional `data`.- */- resolve: function PDFObjects_resolve(objId, data) {- var obj = this.ensureObj(objId);-- obj.resolved = true;- obj.data = data;- obj.promise.resolve(data);- },-- isResolved: function PDFObjects_isResolved(objId) {- var objs = this.objs;-- if (!objs[objId]) {- return false;- } else {- return objs[objId].resolved;- }- },-- hasData: function PDFObjects_hasData(objId) {- return this.isResolved(objId);- },-- /**- * Returns the data of `objId` if object exists, null otherwise.- */- getData: function PDFObjects_getData(objId) {- var objs = this.objs;- if (!objs[objId] || !objs[objId].resolved) {- return null;- } else {- return objs[objId].data;- }- },-- clear: function PDFObjects_clear() {- this.objs = {};- }- };- return PDFObjects;-})();--/**- * Allows controlling of the rendering tasks.- * @class- */-var RenderTask = (function RenderTaskClosure() {- function RenderTask(internalRenderTask) {- this.internalRenderTask = internalRenderTask;- /**- * Promise for rendering task completion.- * @type {Promise}- */- this.promise = new PDFJS.LegacyPromise();- }-- RenderTask.prototype = /** @lends RenderTask.prototype */ {- /**- * Cancels the rendering task. If the task is currently rendering it will- * not be cancelled until graphics pauses with a timeout. The promise that- * this object extends will resolved when cancelled.- */- cancel: function RenderTask_cancel() {- this.internalRenderTask.cancel();- this.promise.reject(new Error('Rendering is cancelled'));- },-- /**- * Registers callback to indicate the rendering task completion.- *- * @param {function} onFulfilled The callback for the rendering completion.- * @param {function} onRejected The callback for the rendering failure.- * @return {Promise} A promise that is resolved after the onFulfilled or- * onRejected callback.- */- then: function RenderTask_then(onFulfilled, onRejected) {- return this.promise.then(onFulfilled, onRejected);- }- };-- return RenderTask;-})();--/**- * For internal use only.- * @ignore- */-var InternalRenderTask = (function InternalRenderTaskClosure() {-- function InternalRenderTask(callback, params, objs, commonObjs, operatorList,- pageNumber) {- this.callback = callback;- this.params = params;- this.objs = objs;- this.commonObjs = commonObjs;- this.operatorListIdx = null;- this.operatorList = operatorList;- this.pageNumber = pageNumber;- this.running = false;- this.graphicsReadyCallback = null;- this.graphicsReady = false;- this.cancelled = false;- }-- InternalRenderTask.prototype = {-- initalizeGraphics:- function InternalRenderTask_initalizeGraphics(transparency) {-- if (this.cancelled) {- return;- }- if (PDFJS.pdfBug && 'StepperManager' in globalScope &&- globalScope.StepperManager.enabled) {- this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);- this.stepper.init(this.operatorList);- this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();- }-- var params = this.params;- this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,- this.objs, params.imageLayer);-- this.gfx.beginDrawing(params.viewport, transparency);- this.operatorListIdx = 0;- this.graphicsReady = true;- if (this.graphicsReadyCallback) {- this.graphicsReadyCallback();- }- },-- cancel: function InternalRenderTask_cancel() {- this.running = false;- this.cancelled = true;- this.callback('cancelled');- },-- operatorListChanged: function InternalRenderTask_operatorListChanged() {- if (!this.graphicsReady) {- if (!this.graphicsReadyCallback) {- this.graphicsReadyCallback = this._continue.bind(this);- }- return;- }-- if (this.stepper) {- this.stepper.updateOperatorList(this.operatorList);- }-- if (this.running) {- return;- }- this._continue();- },-- _continue: function InternalRenderTask__continue() {- this.running = true;- if (this.cancelled) {- return;- }- if (this.params.continueCallback) {- this.params.continueCallback(this._next.bind(this));- } else {- this._next();- }- },-- _next: function InternalRenderTask__next() {- if (this.cancelled) {- return;- }- this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,- this.operatorListIdx,- this._continue.bind(this),- this.stepper);- if (this.operatorListIdx === this.operatorList.argsArray.length) {- this.running = false;- if (this.operatorList.lastChunk) {- this.gfx.endDrawing();- this.callback();- }- }- }-- };-- return InternalRenderTask;-})();---var Metadata = PDFJS.Metadata = (function MetadataClosure() {- function fixMetadata(meta) {- return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {- var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,- function(code, d1, d2, d3) {- return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);- });- var chars = '';- for (var i = 0; i < bytes.length; i += 2) {- var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);- chars += code >= 32 && code < 127 && code != 60 && code != 62 &&- code != 38 && false ? String.fromCharCode(code) :- '&#x' + (0x10000 + code).toString(16).substring(1) + ';';- }- return '>' + chars;- });- }-- function Metadata(meta) {- if (typeof meta === 'string') {- // Ghostscript produces invalid metadata- meta = fixMetadata(meta);-- var parser = new DOMParser();- meta = parser.parseFromString(meta, 'application/xml');- } else if (!(meta instanceof Document)) {- error('Metadata: Invalid metadata object');- }-- this.metaDocument = meta;- this.metadata = {};- this.parse();- }-- Metadata.prototype = {- parse: function Metadata_parse() {- var doc = this.metaDocument;- var rdf = doc.documentElement;-- if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>- rdf = rdf.firstChild;- while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {- rdf = rdf.nextSibling;- }- }-- var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;- if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {- return;- }-- var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;- for (i = 0, length = children.length; i < length; i++) {- desc = children[i];- if (desc.nodeName.toLowerCase() !== 'rdf:description') {- continue;- }-- for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {- if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {- entry = desc.childNodes[ii];- name = entry.nodeName.toLowerCase();- this.metadata[name] = entry.textContent.trim();- }- }- }- },-- get: function Metadata_get(name) {- return this.metadata[name] || null;- },-- has: function Metadata_has(name) {- return typeof this.metadata[name] !== 'undefined';- }- };-- return Metadata;-})();---// <canvas> contexts store most of the state we need natively.-// However, PDF needs a bit more state, which we store here.--// Minimal font size that would be used during canvas fillText operations.-var MIN_FONT_SIZE = 16;-var MAX_GROUP_SIZE = 4096;--var COMPILE_TYPE3_GLYPHS = true;--function createScratchCanvas(width, height) {- var canvas = document.createElement('canvas');- canvas.width = width;- canvas.height = height;- return canvas;-}--function addContextCurrentTransform(ctx) {- // If the context doesn't expose a `mozCurrentTransform`, add a JS based on.- if (!ctx.mozCurrentTransform) {- // Store the original context- ctx._scaleX = ctx._scaleX || 1.0;- ctx._scaleY = ctx._scaleY || 1.0;- ctx._originalSave = ctx.save;- ctx._originalRestore = ctx.restore;- ctx._originalRotate = ctx.rotate;- ctx._originalScale = ctx.scale;- ctx._originalTranslate = ctx.translate;- ctx._originalTransform = ctx.transform;- ctx._originalSetTransform = ctx.setTransform;-- ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0];- ctx._transformStack = [];-- Object.defineProperty(ctx, 'mozCurrentTransform', {- get: function getCurrentTransform() {- return this._transformMatrix;- }- });-- Object.defineProperty(ctx, 'mozCurrentTransformInverse', {- get: function getCurrentTransformInverse() {- // Calculation done using WolframAlpha:- // http://www.wolframalpha.com/input/?- // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}-- var m = this._transformMatrix;- var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];-- var ad_bc = a * d - b * c;- var bc_ad = b * c - a * d;-- return [- d / ad_bc,- b / bc_ad,- c / bc_ad,- a / ad_bc,- (d * e - c * f) / bc_ad,- (b * e - a * f) / ad_bc- ];- }- });-- ctx.save = function ctxSave() {- var old = this._transformMatrix;- this._transformStack.push(old);- this._transformMatrix = old.slice(0, 6);-- this._originalSave();- };-- ctx.restore = function ctxRestore() {- var prev = this._transformStack.pop();- if (prev) {- this._transformMatrix = prev;- this._originalRestore();- }- };-- ctx.translate = function ctxTranslate(x, y) {- var m = this._transformMatrix;- m[4] = m[0] * x + m[2] * y + m[4];- m[5] = m[1] * x + m[3] * y + m[5];-- this._originalTranslate(x, y);- };-- ctx.scale = function ctxScale(x, y) {- var m = this._transformMatrix;- m[0] = m[0] * x;- m[1] = m[1] * x;- m[2] = m[2] * y;- m[3] = m[3] * y;-- this._originalScale(x, y);- };-- ctx.transform = function ctxTransform(a, b, c, d, e, f) {- var m = this._transformMatrix;- this._transformMatrix = [- m[0] * a + m[2] * b,- m[1] * a + m[3] * b,- m[0] * c + m[2] * d,- m[1] * c + m[3] * d,- m[0] * e + m[2] * f + m[4],- m[1] * e + m[3] * f + m[5]- ];-- ctx._originalTransform(a, b, c, d, e, f);- };-- ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {- this._transformMatrix = [a, b, c, d, e, f];-- ctx._originalSetTransform(a, b, c, d, e, f);- };-- ctx.rotate = function ctxRotate(angle) {- var cosValue = Math.cos(angle);- var sinValue = Math.sin(angle);-- var m = this._transformMatrix;- this._transformMatrix = [- m[0] * cosValue + m[2] * sinValue,- m[1] * cosValue + m[3] * sinValue,- m[0] * (-sinValue) + m[2] * cosValue,- m[1] * (-sinValue) + m[3] * cosValue,- m[4],- m[5]- ];-- this._originalRotate(angle);- };- }-}--var CachedCanvases = (function CachedCanvasesClosure() {- var cache = {};- return {- getCanvas: function CachedCanvases_getCanvas(id, width, height,- trackTransform) {- var canvasEntry;- if (id in cache) {- canvasEntry = cache[id];- canvasEntry.canvas.width = width;- canvasEntry.canvas.height = height;- // reset canvas transform for emulated mozCurrentTransform, if needed- canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);- } else {- var canvas = createScratchCanvas(width, height);- var ctx = canvas.getContext('2d');- if (trackTransform) {- addContextCurrentTransform(ctx);- }- cache[id] = canvasEntry = {canvas: canvas, context: ctx};- }- return canvasEntry;- },- clear: function () {- cache = {};- }- };-})();--function compileType3Glyph(imgData) {- var POINT_TO_PROCESS_LIMIT = 1000;-- var width = imgData.width, height = imgData.height;- var i, j, j0, width1 = width + 1;- var points = new Uint8Array(width1 * (height + 1));- var POINT_TYPES =- new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);-- // decodes bit-packed mask data- var lineSize = (width + 7) & ~7, data0 = imgData.data;- var data = new Uint8Array(lineSize * height), pos = 0, ii;- for (i = 0, ii = data0.length; i < ii; i++) {- var mask = 128, elem = data0[i];- while (mask > 0) {- data[pos++] = (elem & mask) ? 0 : 255;- mask >>= 1;- }- }-- // finding iteresting points: every point is located between mask pixels,- // so there will be points of the (width + 1)x(height + 1) grid. Every point- // will have flags assigned based on neighboring mask pixels:- // 4 | 8- // --P--- // 2 | 1- // We are interested only in points with the flags:- // - outside corners: 1, 2, 4, 8;- // - inside corners: 7, 11, 13, 14;- // - and, intersections: 5, 10.- var count = 0;- pos = 0;- if (data[pos] !== 0) {- points[0] = 1;- ++count;- }- for (j = 1; j < width; j++) {- if (data[pos] !== data[pos + 1]) {- points[j] = data[pos] ? 2 : 1;- ++count;- }- pos++;- }- if (data[pos] !== 0) {- points[j] = 2;- ++count;- }- for (i = 1; i < height; i++) {- pos = i * lineSize;- j0 = i * width1;- if (data[pos - lineSize] !== data[pos]) {- points[j0] = data[pos] ? 1 : 8;- ++count;- }- // 'sum' is the position of the current pixel configuration in the 'TYPES'- // array (in order 8-1-2-4, so we can use '>>2' to shift the column).- var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);- for (j = 1; j < width; j++) {- sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +- (data[pos - lineSize + 1] ? 8 : 0);- if (POINT_TYPES[sum]) {- points[j0 + j] = POINT_TYPES[sum];- ++count;- }- pos++;- }- if (data[pos - lineSize] !== data[pos]) {- points[j0 + j] = data[pos] ? 2 : 4;- ++count;- }-- if (count > POINT_TO_PROCESS_LIMIT) {- return null;- }- }-- pos = lineSize * (height - 1);- j0 = i * width1;- if (data[pos] !== 0) {- points[j0] = 8;- ++count;- }- for (j = 1; j < width; j++) {- if (data[pos] !== data[pos + 1]) {- points[j0 + j] = data[pos] ? 4 : 8;- ++count;- }- pos++;- }- if (data[pos] !== 0) {- points[j0 + j] = 4;- ++count;- }- if (count > POINT_TO_PROCESS_LIMIT) {- return null;- }-- // building outlines- var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);- var outlines = [];- for (i = 0; count && i <= height; i++) {- var p = i * width1;- var end = p + width;- while (p < end && !points[p]) {- p++;- }- if (p === end) {- continue;- }- var coords = [p % width1, i];-- var type = points[p], p0 = p, pp;- do {- var step = steps[type];- do {- p += step;- } while (!points[p]);-- pp = points[p];- if (pp !== 5 && pp !== 10) {- // set new direction- type = pp;- // delete mark- points[p] = 0;- } else { // type is 5 or 10, ie, a crossing- // set new direction- type = pp & ((0x33 * type) >> 4);- // set new type for "future hit"- points[p] &= (type >> 2 | type << 2);- }-- coords.push(p % width1);- coords.push((p / width1) | 0);- --count;- } while (p0 !== p);- outlines.push(coords);- --i;- }-- var drawOutline = function(c) {- c.save();- // the path shall be painted in [0..1]x[0..1] space- c.scale(1 / width, -1 / height);- c.translate(0, -height);- c.beginPath();- for (var i = 0, ii = outlines.length; i < ii; i++) {- var o = outlines[i];- c.moveTo(o[0], o[1]);- for (var j = 2, jj = o.length; j < jj; j += 2) {- c.lineTo(o[j], o[j+1]);- }- }- c.fill();- c.beginPath();- c.restore();- };-- return drawOutline;-}--var CanvasExtraState = (function CanvasExtraStateClosure() {- function CanvasExtraState(old) {- // Are soft masks and alpha values shapes or opacities?- this.alphaIsShape = false;- this.fontSize = 0;- this.fontSizeScale = 1;- this.textMatrix = IDENTITY_MATRIX;- this.fontMatrix = FONT_IDENTITY_MATRIX;- this.leading = 0;- // Current point (in user coordinates)- this.x = 0;- this.y = 0;- // Start of text line (in text coordinates)- this.lineX = 0;- this.lineY = 0;- // Character and word spacing- this.charSpacing = 0;- this.wordSpacing = 0;- this.textHScale = 1;- this.textRenderingMode = TextRenderingMode.FILL;- this.textRise = 0;- // Color spaces- this.fillColorSpace = ColorSpace.singletons.gray;- this.fillColorSpaceObj = null;- this.strokeColorSpace = ColorSpace.singletons.gray;- this.strokeColorSpaceObj = null;- this.fillColorObj = null;- this.strokeColorObj = null;- // Default fore and background colors- this.fillColor = '#000000';- this.strokeColor = '#000000';- // Note: fill alpha applies to all non-stroking operations- this.fillAlpha = 1;- this.strokeAlpha = 1;- this.lineWidth = 1;- this.activeSMask = null; // nonclonable field (see the save method below)-- this.old = old;- }-- CanvasExtraState.prototype = {- clone: function CanvasExtraState_clone() {- return Object.create(this);- },- setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {- this.x = x;- this.y = y;- }- };- return CanvasExtraState;-})();--var CanvasGraphics = (function CanvasGraphicsClosure() {- // Defines the time the executeOperatorList is going to be executing- // before it stops and shedules a continue of execution.- var EXECUTION_TIME = 15;-- function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {- this.ctx = canvasCtx;- this.current = new CanvasExtraState();- this.stateStack = [];- this.pendingClip = null;- this.pendingEOFill = false;- this.res = null;- this.xobjs = null;- this.commonObjs = commonObjs;- this.objs = objs;- this.imageLayer = imageLayer;- this.groupStack = [];- this.processingType3 = null;- // Patterns are painted relative to the initial page/form transform, see pdf- // spec 8.7.2 NOTE 1.- this.baseTransform = null;- this.baseTransformStack = [];- this.groupLevel = 0;- this.smaskStack = [];- this.smaskCounter = 0;- this.tempSMask = null;- if (canvasCtx) {- addContextCurrentTransform(canvasCtx);- }- }-- function putBinaryImageData(ctx, imgData) {- if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {- ctx.putImageData(imgData, 0, 0);- return;- }-- // Put the image data to the canvas in chunks, rather than putting the- // whole image at once. This saves JS memory, because the ImageData object- // is smaller. It also possibly saves C++ memory within the implementation- // of putImageData(). (E.g. in Firefox we make two short-lived copies of- // the data passed to putImageData()). |n| shouldn't be too small, however,- // because too many putImageData() calls will slow things down.- //- // Note: as written, if the last chunk is partial, the putImageData() call- // will (conceptually) put pixels past the bounds of the canvas. But- // that's ok; any such pixels are ignored.-- var height = imgData.height, width = imgData.width;- var fullChunkHeight = 16;- var fracChunks = height / fullChunkHeight;- var fullChunks = Math.floor(fracChunks);- var totalChunks = Math.ceil(fracChunks);- var partialChunkHeight = height - fullChunks * fullChunkHeight;-- var chunkImgData = ctx.createImageData(width, fullChunkHeight);- var srcPos = 0, destPos;- var src = imgData.data;- var dest = chunkImgData.data;- var i, j, thisChunkHeight, elemsInThisChunk;-- // There are multiple forms in which the pixel data can be passed, and- // imgData.kind tells us which one this is.- if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {- // Grayscale, 1 bit per pixel (i.e. black-and-white).- var destDataLength = dest.length;- var srcLength = src.byteLength;- var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :- new Uint32ArrayView(dest);- var dest32DataLength = dest32.length;- var fullSrcDiff = (width + 7) >> 3;- var white = 0xFFFFFFFF;- var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?- 0xFF000000 : 0x000000FF;- for (i = 0; i < totalChunks; i++) {- thisChunkHeight =- (i < fullChunks) ? fullChunkHeight : partialChunkHeight;- destPos = 0;- for (j = 0; j < thisChunkHeight; j++) {- var srcDiff = srcLength - srcPos;- var k = 0;- var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;- var kEndUnrolled = kEnd & ~7;- var mask = 0;- var srcByte = 0;- for (; k < kEndUnrolled; k += 8) {- srcByte = src[srcPos++];- dest32[destPos++] = (srcByte & 128) ? white : black;- dest32[destPos++] = (srcByte & 64) ? white : black;- dest32[destPos++] = (srcByte & 32) ? white : black;- dest32[destPos++] = (srcByte & 16) ? white : black;- dest32[destPos++] = (srcByte & 8) ? white : black;- dest32[destPos++] = (srcByte & 4) ? white : black;- dest32[destPos++] = (srcByte & 2) ? white : black;- dest32[destPos++] = (srcByte & 1) ? white : black;- }- for (; k < kEnd; k++) {- if (mask === 0) {- srcByte = src[srcPos++];- mask = 128;- }-- dest32[destPos++] = (srcByte & mask) ? white : black;- mask >>= 1;- }- }- // We ran out of input. Make all remaining pixels transparent.- while (destPos < dest32DataLength) {- dest32[destPos++] = 0;- }-- ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);- }- } else if (imgData.kind === ImageKind.RGBA_32BPP) {- // RGBA, 32-bits per pixel.-- for (i = 0; i < totalChunks; i++) {- thisChunkHeight =- (i < fullChunks) ? fullChunkHeight : partialChunkHeight;- elemsInThisChunk = imgData.width * thisChunkHeight * 4;-- dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));- srcPos += elemsInThisChunk;-- ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);- }- } else if (imgData.kind === ImageKind.RGB_24BPP) {- // RGB, 24-bits per pixel.- for (i = 0; i < totalChunks; i++) {- thisChunkHeight =- (i < fullChunks) ? fullChunkHeight : partialChunkHeight;- elemsInThisChunk = imgData.width * thisChunkHeight * 3;- destPos = 0;- for (j = 0; j < elemsInThisChunk; j += 3) {- dest[destPos++] = src[srcPos++];- dest[destPos++] = src[srcPos++];- dest[destPos++] = src[srcPos++];- dest[destPos++] = 255;- }- ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);- }- } else {- error('bad image kind: ' + imgData.kind);- }- }-- function putBinaryImageMask(ctx, imgData) {- var height = imgData.height, width = imgData.width;- var fullChunkHeight = 16;- var fracChunks = height / fullChunkHeight;- var fullChunks = Math.floor(fracChunks);- var totalChunks = Math.ceil(fracChunks);- var partialChunkHeight = height - fullChunks * fullChunkHeight;-- var chunkImgData = ctx.createImageData(width, fullChunkHeight);- var srcPos = 0;- var src = imgData.data;- var dest = chunkImgData.data;-- for (var i = 0; i < totalChunks; i++) {- var thisChunkHeight =- (i < fullChunks) ? fullChunkHeight : partialChunkHeight;-- // Expand the mask so it can be used by the canvas. Any required- // inversion has already been handled.- var destPos = 3; // alpha component offset- for (var j = 0; j < thisChunkHeight; j++) {- var mask = 0;- for (var k = 0; k < width; k++) {- if (!mask) {- var elem = src[srcPos++];- mask = 128;- }- dest[destPos] = (elem & mask) ? 0 : 255;- destPos += 4;- mask >>= 1;- }- }- ctx.putImageData(chunkImgData, 0, i * fullChunkHeight);- }- }-- function copyCtxState(sourceCtx, destCtx) {- var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',- 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',- 'globalCompositeOperation', 'font'];- for (var i = 0, ii = properties.length; i < ii; i++) {- var property = properties[i];- if (property in sourceCtx) {- destCtx[property] = sourceCtx[property];- }- }- if ('setLineDash' in sourceCtx) {- destCtx.setLineDash(sourceCtx.getLineDash());- destCtx.lineDashOffset = sourceCtx.lineDashOffset;- } else if ('mozDash' in sourceCtx) {- destCtx.mozDash = sourceCtx.mozDash;- destCtx.mozDashOffset = sourceCtx.mozDashOffset;- }- }-- function genericComposeSMask(maskCtx, layerCtx, width, height,- subtype, backdrop) {- var addBackdropFn;- if (backdrop) {- addBackdropFn = function (r0, g0, b0, bytes) {- var length = bytes.length;- for (var i = 3; i < length; i += 4) {- var alpha = bytes[i] / 255;- if (alpha === 0) {- bytes[i - 3] = r0;- bytes[i - 2] = g0;- bytes[i - 1] = b0;- } else if (alpha < 1) {- var alpha_ = 1 - alpha;- bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) | 0;- bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) | 0;- bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) | 0;- }- }- }.bind(null, backdrop[0], backdrop[1], backdrop[2]);- } else {- addBackdropFn = function () {};- }-- var composeFn;- if (subtype === 'Luminosity') {- composeFn = function (maskDataBytes, layerDataBytes) {- var length = maskDataBytes.length;- for (var i = 3; i < length; i += 4) {- var y = ((maskDataBytes[i - 3] * 77) + // * 0.3 / 255 * 0x10000- (maskDataBytes[i - 2] * 152) + // * 0.59 ....- (maskDataBytes[i - 1] * 28)) | 0; // * 0.11 ....- layerDataBytes[i] = (layerDataBytes[i] * y) >> 16;- }- };- } else {- composeFn = function (maskDataBytes, layerDataBytes) {- var length = maskDataBytes.length;- for (var i = 3; i < length; i += 4) {- var alpha = maskDataBytes[i];- layerDataBytes[i] = (layerDataBytes[i] * alpha / 255) | 0;- }- };- }-- // processing image in chunks to save memory- var PIXELS_TO_PROCESS = 65536;- var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));- for (var row = 0; row < height; row += chunkSize) {- var chunkHeight = Math.min(chunkSize, height - row);- var maskData = maskCtx.getImageData(0, row, width, chunkHeight);- var layerData = layerCtx.getImageData(0, row, width, chunkHeight);-- addBackdropFn(maskData.data);- composeFn(maskData.data, layerData.data);-- maskCtx.putImageData(layerData, 0, row);- }- }-- function composeSMask(ctx, smask, layerCtx) {- var mask = smask.canvas;- var maskCtx = smask.context;-- ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,- smask.offsetX, smask.offsetY);-- var backdrop;- if (smask.backdrop) {- var cs = smask.colorSpace || ColorSpace.singletons.rgb;- backdrop = cs.getRgb(smask.backdrop, 0);- }- if (WebGLUtils.isEnabled) {- var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,- {subtype: smask.subtype, backdrop: backdrop});- ctx.setTransform(1, 0, 0, 1, 0, 0);- ctx.drawImage(composed, smask.offsetX, smask.offsetY);- return;- }- genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,- smask.subtype, backdrop);- ctx.drawImage(mask, 0, 0);- }-- var LINE_CAP_STYLES = ['butt', 'round', 'square'];- var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];- var NORMAL_CLIP = {};- var EO_CLIP = {};-- CanvasGraphics.prototype = {-- beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {- // For pdfs that use blend modes we have to clear the canvas else certain- // blend modes can look wrong since we'd be blending with a white- // backdrop. The problem with a transparent backdrop though is we then- // don't get sub pixel anti aliasing on text, so we fill with white if- // we can.- var width = this.ctx.canvas.width;- var height = this.ctx.canvas.height;- if (transparency) {- this.ctx.clearRect(0, 0, width, height);- } else {- this.ctx.mozOpaque = true;- this.ctx.save();- this.ctx.fillStyle = 'rgb(255, 255, 255)';- this.ctx.fillRect(0, 0, width, height);- this.ctx.restore();- }-- var transform = viewport.transform;-- this.ctx.save();- this.ctx.transform.apply(this.ctx, transform);-- this.baseTransform = this.ctx.mozCurrentTransform.slice();-- if (this.imageLayer) {- this.imageLayer.beginLayout();- }- },-- executeOperatorList: function CanvasGraphics_executeOperatorList(- operatorList,- executionStartIdx, continueCallback,- stepper) {- var argsArray = operatorList.argsArray;- var fnArray = operatorList.fnArray;- var i = executionStartIdx || 0;- var argsArrayLen = argsArray.length;-- // Sometimes the OperatorList to execute is empty.- if (argsArrayLen == i) {- return i;- }-- var executionEndIdx;- var endTime = Date.now() + EXECUTION_TIME;-- var commonObjs = this.commonObjs;- var objs = this.objs;- var fnId;- var deferred = Promise.resolve();-- while (true) {- if (stepper && i === stepper.nextBreakPoint) {- stepper.breakIt(i, continueCallback);- return i;- }-- fnId = fnArray[i];-- if (fnId !== OPS.dependency) {- this[fnId].apply(this, argsArray[i]);- } else {- var deps = argsArray[i];- for (var n = 0, nn = deps.length; n < nn; n++) {- var depObjId = deps[n];- var common = depObjId.substring(0, 2) == 'g_';-- // If the promise isn't resolved yet, add the continueCallback- // to the promise and bail out.- if (!common && !objs.isResolved(depObjId)) {- objs.get(depObjId, continueCallback);- return i;- }- if (common && !commonObjs.isResolved(depObjId)) {- commonObjs.get(depObjId, continueCallback);- return i;- }- }- }-- i++;-- // If the entire operatorList was executed, stop as were done.- if (i == argsArrayLen) {- return i;- }-- // If the execution took longer then a certain amount of time, schedule- // to continue exeution after a short delay.- // However, this is only possible if a 'continueCallback' is passed in.- if (continueCallback && Date.now() > endTime) {- deferred.then(continueCallback);- return i;- }-- // If the operatorList isn't executed completely yet OR the execution- // time was short enough, do another execution round.- }- },-- endDrawing: function CanvasGraphics_endDrawing() {- this.ctx.restore();- CachedCanvases.clear();- WebGLUtils.clear();-- if (this.imageLayer) {- this.imageLayer.endLayout();- }- },-- // Graphics state- setLineWidth: function CanvasGraphics_setLineWidth(width) {- this.current.lineWidth = width;- this.ctx.lineWidth = width;- },- setLineCap: function CanvasGraphics_setLineCap(style) {- this.ctx.lineCap = LINE_CAP_STYLES[style];- },- setLineJoin: function CanvasGraphics_setLineJoin(style) {- this.ctx.lineJoin = LINE_JOIN_STYLES[style];- },- setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {- this.ctx.miterLimit = limit;- },- setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {- var ctx = this.ctx;- if ('setLineDash' in ctx) {- ctx.setLineDash(dashArray);- ctx.lineDashOffset = dashPhase;- } else {- ctx.mozDash = dashArray;- ctx.mozDashOffset = dashPhase;- }- },- setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {- // Maybe if we one day fully support color spaces this will be important- // for now we can ignore.- // TODO set rendering intent?- },- setFlatness: function CanvasGraphics_setFlatness(flatness) {- // There's no way to control this with canvas, but we can safely ignore.- // TODO set flatness?- },- setGState: function CanvasGraphics_setGState(states) {- for (var i = 0, ii = states.length; i < ii; i++) {- var state = states[i];- var key = state[0];- var value = state[1];-- switch (key) {- case 'LW':- this.setLineWidth(value);- break;- case 'LC':- this.setLineCap(value);- break;- case 'LJ':- this.setLineJoin(value);- break;- case 'ML':- this.setMiterLimit(value);- break;- case 'D':- this.setDash(value[0], value[1]);- break;- case 'RI':- this.setRenderingIntent(value);- break;- case 'FL':- this.setFlatness(value);- break;- case 'Font':- this.setFont(value[0], value[1]);- break;- case 'CA':- this.current.strokeAlpha = state[1];- break;- case 'ca':- this.current.fillAlpha = state[1];- this.ctx.globalAlpha = state[1];- break;- case 'BM':- if (value && value.name && (value.name !== 'Normal')) {- var mode = value.name.replace(/([A-Z])/g,- function(c) {- return '-' + c.toLowerCase();- }- ).substring(1);- this.ctx.globalCompositeOperation = mode;- if (this.ctx.globalCompositeOperation !== mode) {- warn('globalCompositeOperation "' + mode +- '" is not supported');- }- } else {- this.ctx.globalCompositeOperation = 'source-over';- }- break;- case 'SMask':- if (this.current.activeSMask) {- this.endSMaskGroup();- }- this.current.activeSMask = value ? this.tempSMask : null;- if (this.current.activeSMask) {- this.beginSMaskGroup();- }- this.tempSMask = null;- break;- }- }- },- beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {-- var activeSMask = this.current.activeSMask;- var drawnWidth = activeSMask.canvas.width;- var drawnHeight = activeSMask.canvas.height;- var cacheId = 'smaskGroupAt' + this.groupLevel;- var scratchCanvas = CachedCanvases.getCanvas(- cacheId, drawnWidth, drawnHeight, true);-- var currentCtx = this.ctx;- var currentTransform = currentCtx.mozCurrentTransform;- this.ctx.save();-- var groupCtx = scratchCanvas.context;- groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);- groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);- groupCtx.transform.apply(groupCtx, currentTransform);-- copyCtxState(currentCtx, groupCtx);- this.ctx = groupCtx;- this.setGState([- ['BM', 'Normal'],- ['ca', 1],- ['CA', 1]- ]);- this.groupStack.push(currentCtx);- this.groupLevel++;- },- endSMaskGroup: function CanvasGraphics_endSMaskGroup() {- var groupCtx = this.ctx;- this.groupLevel--;- this.ctx = this.groupStack.pop();-- composeSMask(this.ctx, this.current.activeSMask, groupCtx);- this.ctx.restore();- },- save: function CanvasGraphics_save() {- this.ctx.save();- var old = this.current;- this.stateStack.push(old);- this.current = old.clone();- if (this.current.activeSMask) {- this.current.activeSMask = null;- }- },- restore: function CanvasGraphics_restore() {- var prev = this.stateStack.pop();- if (prev) {- if (this.current.activeSMask) {- this.endSMaskGroup();- }-- this.current = prev;- this.ctx.restore();- }- },- transform: function CanvasGraphics_transform(a, b, c, d, e, f) {- this.ctx.transform(a, b, c, d, e, f);- },-- // Path- moveTo: function CanvasGraphics_moveTo(x, y) {- this.ctx.moveTo(x, y);- this.current.setCurrentPoint(x, y);- },- lineTo: function CanvasGraphics_lineTo(x, y) {- this.ctx.lineTo(x, y);- this.current.setCurrentPoint(x, y);- },- curveTo: function CanvasGraphics_curveTo(x1, y1, x2, y2, x3, y3) {- this.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);- this.current.setCurrentPoint(x3, y3);- },- curveTo2: function CanvasGraphics_curveTo2(x2, y2, x3, y3) {- var current = this.current;- this.ctx.bezierCurveTo(current.x, current.y, x2, y2, x3, y3);- current.setCurrentPoint(x3, y3);- },- curveTo3: function CanvasGraphics_curveTo3(x1, y1, x3, y3) {- this.curveTo(x1, y1, x3, y3, x3, y3);- this.current.setCurrentPoint(x3, y3);- },- closePath: function CanvasGraphics_closePath() {- this.ctx.closePath();- },- rectangle: function CanvasGraphics_rectangle(x, y, width, height) {- if (width === 0) {- width = this.getSinglePixelWidth();- }- if (height === 0) {- height = this.getSinglePixelWidth();- }-- this.ctx.rect(x, y, width, height);- },- stroke: function CanvasGraphics_stroke(consumePath) {- consumePath = typeof consumePath !== 'undefined' ? consumePath : true;- var ctx = this.ctx;- var strokeColor = this.current.strokeColor;- if (this.current.lineWidth === 0) {- ctx.lineWidth = this.getSinglePixelWidth();- }- // For stroke we want to temporarily change the global alpha to the- // stroking alpha.- ctx.globalAlpha = this.current.strokeAlpha;- if (strokeColor && strokeColor.hasOwnProperty('type') &&- strokeColor.type === 'Pattern') {- // for patterns, we transform to pattern space, calculate- // the pattern, call stroke, and restore to user space- ctx.save();- ctx.strokeStyle = strokeColor.getPattern(ctx, this);- ctx.stroke();- ctx.restore();- } else {- ctx.stroke();- }- if (consumePath) {- this.consumePath();- }- // Restore the global alpha to the fill alpha- ctx.globalAlpha = this.current.fillAlpha;- },- closeStroke: function CanvasGraphics_closeStroke() {- this.closePath();- this.stroke();- },- fill: function CanvasGraphics_fill(consumePath) {- consumePath = typeof consumePath !== 'undefined' ? consumePath : true;- var ctx = this.ctx;- var fillColor = this.current.fillColor;- var needRestore = false;-- if (fillColor && fillColor.hasOwnProperty('type') &&- fillColor.type === 'Pattern') {- ctx.save();- ctx.fillStyle = fillColor.getPattern(ctx, this);- needRestore = true;- }-- if (this.pendingEOFill) {- if ('mozFillRule' in this.ctx) {- this.ctx.mozFillRule = 'evenodd';- this.ctx.fill();- this.ctx.mozFillRule = 'nonzero';- } else {- try {- this.ctx.fill('evenodd');- } catch (ex) {- // shouldn't really happen, but browsers might think differently- this.ctx.fill();- }- }- this.pendingEOFill = false;- } else {- this.ctx.fill();- }-- if (needRestore) {- ctx.restore();- }- if (consumePath) {- this.consumePath();- }- },- eoFill: function CanvasGraphics_eoFill() {- this.pendingEOFill = true;- this.fill();- },- fillStroke: function CanvasGraphics_fillStroke() {- this.fill(false);- this.stroke(false);-- this.consumePath();- },- eoFillStroke: function CanvasGraphics_eoFillStroke() {- this.pendingEOFill = true;- this.fillStroke();- },- closeFillStroke: function CanvasGraphics_closeFillStroke() {- this.closePath();- this.fillStroke();- },- closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {- this.pendingEOFill = true;- this.closePath();- this.fillStroke();- },- endPath: function CanvasGraphics_endPath() {- this.consumePath();- },-- // Clipping- clip: function CanvasGraphics_clip() {- this.pendingClip = NORMAL_CLIP;- },- eoClip: function CanvasGraphics_eoClip() {- this.pendingClip = EO_CLIP;- },-- // Text- beginText: function CanvasGraphics_beginText() {- this.current.textMatrix = IDENTITY_MATRIX;- this.current.x = this.current.lineX = 0;- this.current.y = this.current.lineY = 0;- },- endText: function CanvasGraphics_endText() {- if (!('pendingTextPaths' in this)) {- this.ctx.beginPath();- return;- }- var paths = this.pendingTextPaths;- var ctx = this.ctx;-- ctx.save();- ctx.beginPath();- for (var i = 0; i < paths.length; i++) {- var path = paths[i];- ctx.setTransform.apply(ctx, path.transform);- ctx.translate(path.x, path.y);- path.addToPath(ctx, path.fontSize);- }- ctx.restore();- ctx.clip();- ctx.beginPath();- delete this.pendingTextPaths;- },- setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {- this.current.charSpacing = spacing;- },- setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {- this.current.wordSpacing = spacing;- },- setHScale: function CanvasGraphics_setHScale(scale) {- this.current.textHScale = scale / 100;- },- setLeading: function CanvasGraphics_setLeading(leading) {- this.current.leading = -leading;- },- setFont: function CanvasGraphics_setFont(fontRefName, size) {- var fontObj = this.commonObjs.get(fontRefName);- var current = this.current;-- if (!fontObj) {- error('Can\'t find font for ' + fontRefName);- }-- current.fontMatrix = (fontObj.fontMatrix ?- fontObj.fontMatrix : FONT_IDENTITY_MATRIX);-- // A valid matrix needs all main diagonal elements to be non-zero- // This also ensures we bypass FF bugzilla bug #719844.- if (current.fontMatrix[0] === 0 ||- current.fontMatrix[3] === 0) {- warn('Invalid font matrix for font ' + fontRefName);- }-- // The spec for Tf (setFont) says that 'size' specifies the font 'scale',- // and in some docs this can be negative (inverted x-y axes).- if (size < 0) {- size = -size;- current.fontDirection = -1;- } else {- current.fontDirection = 1;- }-- this.current.font = fontObj;- this.current.fontSize = size;-- if (fontObj.coded) {- return; // we don't need ctx.font for Type3 fonts- }-- var name = fontObj.loadedName || 'sans-serif';- var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :- (fontObj.bold ? 'bold' : 'normal');-- var italic = fontObj.italic ? 'italic' : 'normal';- var typeface = '"' + name + '", ' + fontObj.fallbackName;-- // Some font backends cannot handle fonts below certain size.- // Keeping the font at minimal size and using the fontSizeScale to change- // the current transformation matrix before the fillText/strokeText.- // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227- var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE;- this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 :- size / MIN_FONT_SIZE;-- var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;- this.ctx.font = rule;- },- setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {- this.current.textRenderingMode = mode;- },- setTextRise: function CanvasGraphics_setTextRise(rise) {- this.current.textRise = rise;- },- moveText: function CanvasGraphics_moveText(x, y) {- this.current.x = this.current.lineX += x;- this.current.y = this.current.lineY += y;- },- setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {- this.setLeading(-y);- this.moveText(x, y);- },- setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {- this.current.textMatrix = [a, b, c, d, e, f];-- this.current.x = this.current.lineX = 0;- this.current.y = this.current.lineY = 0;- },- nextLine: function CanvasGraphics_nextLine() {- this.moveText(0, this.current.leading);- },- applyTextTransforms: function CanvasGraphics_applyTextTransforms() {- var ctx = this.ctx;- var current = this.current;- ctx.transform.apply(ctx, current.textMatrix);- ctx.translate(current.x, current.y + current.textRise);- if (current.fontDirection > 0) {- ctx.scale(current.textHScale, -1);- } else {- ctx.scale(-current.textHScale, 1);- }- },-- paintChar: function (character, x, y) {- var ctx = this.ctx;- var current = this.current;- var font = current.font;- var fontSize = current.fontSize / current.fontSizeScale;- var textRenderingMode = current.textRenderingMode;- var fillStrokeMode = textRenderingMode &- TextRenderingMode.FILL_STROKE_MASK;- var isAddToPathSet = !!(textRenderingMode &- TextRenderingMode.ADD_TO_PATH_FLAG);-- var addToPath;- if (font.disableFontFace || isAddToPathSet) {- addToPath = font.getPathGenerator(this.commonObjs, character);- }-- if (font.disableFontFace) {- ctx.save();- ctx.translate(x, y);- ctx.beginPath();- addToPath(ctx, fontSize);- if (fillStrokeMode === TextRenderingMode.FILL ||- fillStrokeMode === TextRenderingMode.FILL_STROKE) {- ctx.fill();- }- if (fillStrokeMode === TextRenderingMode.STROKE ||- fillStrokeMode === TextRenderingMode.FILL_STROKE) {- ctx.stroke();- }- ctx.restore();- } else {- if (fillStrokeMode === TextRenderingMode.FILL ||- fillStrokeMode === TextRenderingMode.FILL_STROKE) {- ctx.fillText(character, x, y);- }- if (fillStrokeMode === TextRenderingMode.STROKE ||- fillStrokeMode === TextRenderingMode.FILL_STROKE) {- ctx.strokeText(character, x, y);- }- }-- if (isAddToPathSet) {- var paths = this.pendingTextPaths || (this.pendingTextPaths = []);- paths.push({- transform: ctx.mozCurrentTransform,- x: x,- y: y,- fontSize: fontSize,- addToPath: addToPath- });- }- },-- get isFontSubpixelAAEnabled() {- // Checks if anti-aliasing is enabled when scaled text is painted.- // On Windows GDI scaled fonts looks bad.- var ctx = document.createElement('canvas').getContext('2d');- ctx.scale(1.5, 1);- ctx.fillText('I', 0, 10);- var data = ctx.getImageData(0, 0, 10, 10).data;- var enabled = false;- for (var i = 3; i < data.length; i += 4) {- if (data[i] > 0 && data[i] < 255) {- enabled = true;- break;- }- }- return shadow(this, 'isFontSubpixelAAEnabled', enabled);- },-- showText: function CanvasGraphics_showText(glyphs) {- var ctx = this.ctx;- var current = this.current;- var font = current.font;- var fontSize = current.fontSize;- var fontSizeScale = current.fontSizeScale;- var charSpacing = current.charSpacing;- var wordSpacing = current.wordSpacing;- var textHScale = current.textHScale * current.fontDirection;- var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;- var glyphsLength = glyphs.length;- var vertical = font.vertical;- var defaultVMetrics = font.defaultVMetrics;- var i, glyph, width;- var VERTICAL_TEXT_ROTATION = Math.PI / 2;-- if (fontSize === 0) {- return;- }-- // Type3 fonts - each glyph is a "mini-PDF"- if (font.coded) {- ctx.save();- ctx.transform.apply(ctx, current.textMatrix);- ctx.translate(current.x, current.y);-- ctx.scale(textHScale, 1);-- for (i = 0; i < glyphsLength; ++i) {- glyph = glyphs[i];- if (glyph === null) {- // word break- this.ctx.translate(wordSpacing, 0);- current.x += wordSpacing * textHScale;- continue;- }-- this.processingType3 = glyph;- this.save();- ctx.scale(fontSize, fontSize);- ctx.transform.apply(ctx, fontMatrix);- this.executeOperatorList(glyph.operatorList);- this.restore();-- var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);- width = ((transformed[0] * fontSize + charSpacing) *- current.fontDirection);-- ctx.translate(width, 0);- current.x += width * textHScale;- }- ctx.restore();- this.processingType3 = null;- } else {- ctx.save();- this.applyTextTransforms();-- var lineWidth = current.lineWidth;- var a1 = current.textMatrix[0], b1 = current.textMatrix[1];- var scale = Math.sqrt(a1 * a1 + b1 * b1);- if (scale === 0 || lineWidth === 0) {- lineWidth = this.getSinglePixelWidth();- } else {- lineWidth /= scale;- }-- if (fontSizeScale != 1.0) {- ctx.scale(fontSizeScale, fontSizeScale);- lineWidth /= fontSizeScale;- }-- ctx.lineWidth = lineWidth;-- var x = 0;- for (i = 0; i < glyphsLength; ++i) {- glyph = glyphs[i];- if (glyph === null) {- // word break- x += current.fontDirection * wordSpacing;- continue;- }-- var restoreNeeded = false;- var character = glyph.fontChar;- var vmetric = glyph.vmetric || defaultVMetrics;- if (vertical) {- var vx = glyph.vmetric ? vmetric[1] : glyph.width * 0.5;- vx = -vx * fontSize * current.fontMatrix[0];- var vy = vmetric[2] * fontSize * current.fontMatrix[0];- }- width = vmetric ? -vmetric[0] : glyph.width;- var charWidth = width * fontSize * current.fontMatrix[0] +- charSpacing * current.fontDirection;- var accent = glyph.accent;-- var scaledX, scaledY, scaledAccentX, scaledAccentY;-- if (vertical) {- scaledX = vx / fontSizeScale;- scaledY = (x + vy) / fontSizeScale;- } else {- scaledX = x / fontSizeScale;- scaledY = 0;- }-- if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {- // some standard fonts may not have the exact width, trying to- // rescale per character- var measuredWidth = ctx.measureText(character).width * 1000 /- current.fontSize * current.fontSizeScale;- var characterScaleX = width / measuredWidth;- restoreNeeded = true;- ctx.save();- ctx.scale(characterScaleX, 1);- scaledX /= characterScaleX;- if (accent) {- scaledAccentX /= characterScaleX;- }- }-- this.paintChar(character, scaledX, scaledY);- if (accent) {- scaledAccentX = scaledX + accent.offset.x / fontSizeScale;- scaledAccentY = scaledY - accent.offset.y / fontSizeScale;- this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);- }-- x += charWidth;-- if (restoreNeeded) {- ctx.restore();- }- }- if (vertical) {- current.y -= x * textHScale;- } else {- current.x += x * textHScale;- }- ctx.restore();- }- },- showSpacedText: function CanvasGraphics_showSpacedText(arr) {- var ctx = this.ctx;- var current = this.current;- var font = current.font;- var fontSize = current.fontSize;- // TJ array's number is independent from fontMatrix- var textHScale = current.textHScale * 0.001 * current.fontDirection;- var arrLength = arr.length;- var vertical = font.vertical;-- for (var i = 0; i < arrLength; ++i) {- var e = arr[i];- if (isNum(e)) {- var spacingLength = -e * fontSize * textHScale;- if (vertical) {- current.y += spacingLength;- } else {- current.x += spacingLength;- }-- } else {- this.showText(e);- }- }- },- nextLineShowText: function CanvasGraphics_nextLineShowText(text) {- this.nextLine();- this.showText(text);- },- nextLineSetSpacingShowText:- function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing,- charSpacing,- text) {- this.setWordSpacing(wordSpacing);- this.setCharSpacing(charSpacing);- this.nextLineShowText(text);- },-- // Type3 fonts- setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {- // We can safely ignore this since the width should be the same- // as the width in the Widths array.- },- setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,- yWidth,- llx,- lly,- urx,- ury) {- // TODO According to the spec we're also suppose to ignore any operators- // that set color or include images while processing this type3 font.- this.rectangle(llx, lly, urx - llx, ury - lly);- this.clip();- this.endPath();- },-- // Color- setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) {- this.current.strokeColorSpace = ColorSpace.fromIR(raw);- },- setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) {- this.current.fillColorSpace = ColorSpace.fromIR(raw);- },- setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) {- var cs = this.current.strokeColorSpace;- var rgbColor = cs.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.strokeStyle = color;- this.current.strokeColor = color;- },- getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) {- var pattern;- if (IR[0] == 'TilingPattern') {- var args = IR[1];- var base = cs.base;- var color;- if (base) {- var baseComps = base.numComps;-- color = base.getRgb(args, 0);- }- pattern = new TilingPattern(IR, color, this.ctx, this.objs,- this.commonObjs, this.baseTransform);- } else {- pattern = getShadingPatternFromIR(IR);- }- return pattern;- },- setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {- var cs = this.current.strokeColorSpace;-- if (cs.name == 'Pattern') {- this.current.strokeColor = this.getColorN_Pattern(arguments, cs);- } else {- this.setStrokeColor.apply(this, arguments);- }- },- setFillColor: function CanvasGraphics_setFillColor(/*...*/) {- var cs = this.current.fillColorSpace;- var rgbColor = cs.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.fillStyle = color;- this.current.fillColor = color;- },- setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {- var cs = this.current.fillColorSpace;-- if (cs.name == 'Pattern') {- this.current.fillColor = this.getColorN_Pattern(arguments, cs);- } else {- this.setFillColor.apply(this, arguments);- }- },- setStrokeGray: function CanvasGraphics_setStrokeGray(gray) {- this.current.strokeColorSpace = ColorSpace.singletons.gray;-- var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.strokeStyle = color;- this.current.strokeColor = color;- },- setFillGray: function CanvasGraphics_setFillGray(gray) {- this.current.fillColorSpace = ColorSpace.singletons.gray;-- var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.fillStyle = color;- this.current.fillColor = color;- },- setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {- this.current.strokeColorSpace = ColorSpace.singletons.rgb;-- var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.strokeStyle = color;- this.current.strokeColor = color;- },- setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {- this.current.fillColorSpace = ColorSpace.singletons.rgb;-- var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0);- var color = Util.makeCssRgb(rgbColor);- this.ctx.fillStyle = color;- this.current.fillColor = color;- },- setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) {- this.current.strokeColorSpace = ColorSpace.singletons.cmyk;-- var color = Util.makeCssCmyk(arguments);- this.ctx.strokeStyle = color;- this.current.strokeColor = color;- },- setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) {- this.current.fillColorSpace = ColorSpace.singletons.cmyk;-- var color = Util.makeCssCmyk(arguments);- this.ctx.fillStyle = color;- this.current.fillColor = color;- },-- shadingFill: function CanvasGraphics_shadingFill(patternIR) {- var ctx = this.ctx;-- this.save();- var pattern = getShadingPatternFromIR(patternIR);- ctx.fillStyle = pattern.getPattern(ctx, this, true);-- var inv = ctx.mozCurrentTransformInverse;- if (inv) {- var canvas = ctx.canvas;- var width = canvas.width;- var height = canvas.height;-- var bl = Util.applyTransform([0, 0], inv);- var br = Util.applyTransform([0, height], inv);- var ul = Util.applyTransform([width, 0], inv);- var ur = Util.applyTransform([width, height], inv);-- var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);- var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);- var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);- var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);-- this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);- } else {- // HACK to draw the gradient onto an infinite rectangle.- // PDF gradients are drawn across the entire image while- // Canvas only allows gradients to be drawn in a rectangle- // The following bug should allow us to remove this.- // https://bugzilla.mozilla.org/show_bug.cgi?id=664884-- this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);- }-- this.restore();- },-- // Images- beginInlineImage: function CanvasGraphics_beginInlineImage() {- error('Should not call beginInlineImage');- },- beginImageData: function CanvasGraphics_beginImageData() {- error('Should not call beginImageData');- },-- paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,- bbox) {- this.save();- this.baseTransformStack.push(this.baseTransform);-- if (matrix && isArray(matrix) && 6 == matrix.length) {- this.transform.apply(this, matrix);- }-- this.baseTransform = this.ctx.mozCurrentTransform;-- if (bbox && isArray(bbox) && 4 == bbox.length) {- var width = bbox[2] - bbox[0];- var height = bbox[3] - bbox[1];- this.rectangle(bbox[0], bbox[1], width, height);- this.clip();- this.endPath();- }- },-- paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {- this.restore();- this.baseTransform = this.baseTransformStack.pop();- },-- beginGroup: function CanvasGraphics_beginGroup(group) {- this.save();- var currentCtx = this.ctx;- // TODO non-isolated groups - according to Rik at adobe non-isolated- // group results aren't usually that different and they even have tools- // that ignore this setting. Notes from Rik on implmenting:- // - When you encounter an transparency group, create a new canvas with- // the dimensions of the bbox- // - copy the content from the previous canvas to the new canvas- // - draw as usual- // - remove the backdrop alpha:- // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha- // value of your transparency group and 'alphaBackdrop' the alpha of the- // backdrop- // - remove background color:- // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)- if (!group.isolated) {- info('TODO: Support non-isolated groups.');- }-- // TODO knockout - supposedly possible with the clever use of compositing- // modes.- if (group.knockout) {- warn('Knockout groups not supported.');- }-- var currentTransform = currentCtx.mozCurrentTransform;- if (group.matrix) {- currentCtx.transform.apply(currentCtx, group.matrix);- }- assert(group.bbox, 'Bounding box is required.');-- // Based on the current transform figure out how big the bounding box- // will actually be.- var bounds = Util.getAxialAlignedBoundingBox(- group.bbox,- currentCtx.mozCurrentTransform);- // Clip the bounding box to the current canvas.- var canvasBounds = [0,- 0,- currentCtx.canvas.width,- currentCtx.canvas.height];- bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];- // Use ceil in case we're between sizes so we don't create canvas that is- // too small and make the canvas at least 1x1 pixels.- var offsetX = Math.floor(bounds[0]);- var offsetY = Math.floor(bounds[1]);- var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);- var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);- var scaleX = 1, scaleY = 1;- if (drawnWidth > MAX_GROUP_SIZE) {- scaleX = drawnWidth / MAX_GROUP_SIZE;- drawnWidth = MAX_GROUP_SIZE;- }- if (drawnHeight > MAX_GROUP_SIZE) {- scaleY = drawnHeight / MAX_GROUP_SIZE;- drawnHeight = MAX_GROUP_SIZE;- }-- var cacheId = 'groupAt' + this.groupLevel;- if (group.smask) {- // Using two cache entries is case if masks are used one after another.- cacheId += '_smask_' + ((this.smaskCounter++) % 2);- }- var scratchCanvas = CachedCanvases.getCanvas(- cacheId, drawnWidth, drawnHeight, true);- var groupCtx = scratchCanvas.context;-- // Since we created a new canvas that is just the size of the bounding box- // we have to translate the group ctx.- groupCtx.scale(1 / scaleX, 1 / scaleY);- groupCtx.translate(-offsetX, -offsetY);- groupCtx.transform.apply(groupCtx, currentTransform);-- if (group.smask) {- // Saving state and cached mask to be used in setGState.- this.smaskStack.push({- canvas: scratchCanvas.canvas,- context: groupCtx,- offsetX: offsetX,- offsetY: offsetY,- scaleX: scaleX,- scaleY: scaleY,- subtype: group.smask.subtype,- backdrop: group.smask.backdrop,- colorSpace: group.colorSpace && ColorSpace.fromIR(group.colorSpace)- });- } else {- // Setup the current ctx so when the group is popped we draw it at the- // right location.- currentCtx.setTransform(1, 0, 0, 1, 0, 0);- currentCtx.translate(offsetX, offsetY);- currentCtx.scale(scaleX, scaleY);- }- // The transparency group inherits all off the current graphics state- // except the blend mode, soft mask, and alpha constants.- copyCtxState(currentCtx, groupCtx);- this.ctx = groupCtx;- this.setGState([- ['BM', 'Normal'],- ['ca', 1],- ['CA', 1]- ]);- this.groupStack.push(currentCtx);- this.groupLevel++;- },-- endGroup: function CanvasGraphics_endGroup(group) {- this.groupLevel--;- var groupCtx = this.ctx;- this.ctx = this.groupStack.pop();- // Turn off image smoothing to avoid sub pixel interpolation which can- // look kind of blurry for some pdfs.- if ('imageSmoothingEnabled' in this.ctx) {- this.ctx.imageSmoothingEnabled = false;- } else {- this.ctx.mozImageSmoothingEnabled = false;- }- if (group.smask) {- this.tempSMask = this.smaskStack.pop();- } else {- this.ctx.drawImage(groupCtx.canvas, 0, 0);- }- this.restore();- },-- beginAnnotations: function CanvasGraphics_beginAnnotations() {- this.save();- this.current = new CanvasExtraState();- },-- endAnnotations: function CanvasGraphics_endAnnotations() {- this.restore();- },-- beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,- matrix) {- this.save();-- if (rect && isArray(rect) && 4 == rect.length) {- var width = rect[2] - rect[0];- var height = rect[3] - rect[1];- this.rectangle(rect[0], rect[1], width, height);- this.clip();- this.endPath();- }-- this.transform.apply(this, transform);- this.transform.apply(this, matrix);- },-- endAnnotation: function CanvasGraphics_endAnnotation() {- this.restore();- },-- paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {- var domImage = this.objs.get(objId);- if (!domImage) {- warn('Dependent image isn\'t ready yet');- return;- }-- this.save();-- var ctx = this.ctx;- // scale the image to the unit square- ctx.scale(1 / w, -1 / h);-- ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,- 0, -h, w, h);- if (this.imageLayer) {- var currentTransform = ctx.mozCurrentTransformInverse;- var position = this.getCanvasPosition(0, 0);- this.imageLayer.appendImage({- objId: objId,- left: position[0],- top: position[1],- width: w / currentTransform[0],- height: h / currentTransform[3]- });- }- this.restore();- },-- paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {- var ctx = this.ctx;- var width = img.width, height = img.height;-- var glyph = this.processingType3;-- if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) {- var MAX_SIZE_TO_COMPILE = 1000;- if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {- glyph.compiled =- compileType3Glyph({data: img.data, width: width, height: height});- } else {- glyph.compiled = null;- }- }-- if (glyph && glyph.compiled) {- glyph.compiled(ctx);- return;- }-- var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);- var maskCtx = maskCanvas.context;- maskCtx.save();-- putBinaryImageMask(maskCtx, img);-- maskCtx.globalCompositeOperation = 'source-in';-- var fillColor = this.current.fillColor;- maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&- fillColor.type === 'Pattern') ?- fillColor.getPattern(maskCtx, this) : fillColor;- maskCtx.fillRect(0, 0, width, height);-- maskCtx.restore();-- this.paintInlineImageXObject(maskCanvas.canvas);- },-- paintImageMaskXObjectRepeat:- function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,- scaleY, positions) {- var width = imgData.width;- var height = imgData.height;- var ctx = this.ctx;-- var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);- var maskCtx = maskCanvas.context;- maskCtx.save();-- putBinaryImageMask(maskCtx, imgData);-- maskCtx.globalCompositeOperation = 'source-in';-- var fillColor = this.current.fillColor;- maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&- fillColor.type === 'Pattern') ?- fillColor.getPattern(maskCtx, this) : fillColor;- maskCtx.fillRect(0, 0, width, height);-- maskCtx.restore();-- for (var i = 0, ii = positions.length; i < ii; i += 2) {- ctx.save();- ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);- ctx.scale(1, -1);- ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,- 0, -1, 1, 1);- ctx.restore();- }- },-- paintImageMaskXObjectGroup:- function CanvasGraphics_paintImageMaskXObjectGroup(images) {- var ctx = this.ctx;-- for (var i = 0, ii = images.length; i < ii; i++) {- var image = images[i];- var width = image.width, height = image.height;-- var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);- var maskCtx = maskCanvas.context;- maskCtx.save();-- putBinaryImageMask(maskCtx, image);-- maskCtx.globalCompositeOperation = 'source-in';-- var fillColor = this.current.fillColor;- maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') &&- fillColor.type === 'Pattern') ?- fillColor.getPattern(maskCtx, this) : fillColor;- maskCtx.fillRect(0, 0, width, height);-- maskCtx.restore();-- ctx.save();- ctx.transform.apply(ctx, image.transform);- ctx.scale(1, -1);- ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,- 0, -1, 1, 1);- ctx.restore();- }- },-- paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {- var imgData = this.objs.get(objId);- if (!imgData) {- warn('Dependent image isn\'t ready yet');- return;- }-- this.paintInlineImageXObject(imgData);- },-- paintImageXObjectRepeat:- function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,- positions) {- var imgData = this.objs.get(objId);- if (!imgData) {- warn('Dependent image isn\'t ready yet');- return;- }-- var width = imgData.width;- var height = imgData.height;- var map = [];- for (var i = 0, ii = positions.length; i < ii; i += 2) {- map.push({transform: [scaleX, 0, 0, scaleY, positions[i],- positions[i + 1]], x: 0, y: 0, w: width, h: height});- }- this.paintInlineImageXObjectGroup(imgData, map);- },-- paintInlineImageXObject:- function CanvasGraphics_paintInlineImageXObject(imgData) {- var width = imgData.width;- var height = imgData.height;- var ctx = this.ctx;-- this.save();- // scale the image to the unit square- ctx.scale(1 / width, -1 / height);-- var currentTransform = ctx.mozCurrentTransformInverse;- var a = currentTransform[0], b = currentTransform[1];- var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);- var c = currentTransform[2], d = currentTransform[3];- var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);-- var imgToPaint, tmpCanvas;- // instanceof HTMLElement does not work in jsdom node.js module- if (imgData instanceof HTMLElement || !imgData.data) {- imgToPaint = imgData;- } else {- tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);- var tmpCtx = tmpCanvas.context;- putBinaryImageData(tmpCtx, imgData);- imgToPaint = tmpCanvas.canvas;- }-- var paintWidth = width, paintHeight = height;- var tmpCanvasId = 'prescale1';- // Vertial or horizontal scaling shall not be more than 2 to not loose the- // pixels during drawImage operation, painting on the temporary canvas(es)- // that are twice smaller in size- while ((widthScale > 2 && paintWidth > 1) ||- (heightScale > 2 && paintHeight > 1)) {- var newWidth = paintWidth, newHeight = paintHeight;- if (widthScale > 2 && paintWidth > 1) {- newWidth = Math.ceil(paintWidth / 2);- widthScale /= paintWidth / newWidth;- }- if (heightScale > 2 && paintHeight > 1) {- newHeight = Math.ceil(paintHeight / 2);- heightScale /= paintHeight / newHeight;- }- tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);- tmpCtx = tmpCanvas.context;- tmpCtx.clearRect(0, 0, newWidth, newHeight);- tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,- 0, 0, newWidth, newHeight);- imgToPaint = tmpCanvas.canvas;- paintWidth = newWidth;- paintHeight = newHeight;- tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';- }- ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,- 0, -height, width, height);-- if (this.imageLayer) {- var position = this.getCanvasPosition(0, -height);- this.imageLayer.appendImage({- imgData: imgData,- left: position[0],- top: position[1],- width: width / currentTransform[0],- height: height / currentTransform[3]- });- }- this.restore();- },-- paintInlineImageXObjectGroup:- function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {- var ctx = this.ctx;- var w = imgData.width;- var h = imgData.height;-- var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);- var tmpCtx = tmpCanvas.context;- putBinaryImageData(tmpCtx, imgData);-- for (var i = 0, ii = map.length; i < ii; i++) {- var entry = map[i];- ctx.save();- ctx.transform.apply(ctx, entry.transform);- ctx.scale(1, -1);- ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,- 0, -1, 1, 1);- if (this.imageLayer) {- var position = this.getCanvasPosition(entry.x, entry.y);- this.imageLayer.appendImage({- imgData: imgData,- left: position[0],- top: position[1],- width: w,- height: h- });- }- ctx.restore();- }- },-- paintSolidColorImageMask:- function CanvasGraphics_paintSolidColorImageMask() {- this.ctx.fillRect(0, 0, 1, 1);- },-- // Marked content-- markPoint: function CanvasGraphics_markPoint(tag) {- // TODO Marked content.- },- markPointProps: function CanvasGraphics_markPointProps(tag, properties) {- // TODO Marked content.- },- beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {- // TODO Marked content.- },- beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(- tag, properties) {- // TODO Marked content.- },- endMarkedContent: function CanvasGraphics_endMarkedContent() {- // TODO Marked content.- },-- // Compatibility-- beginCompat: function CanvasGraphics_beginCompat() {- // TODO ignore undefined operators (should we do that anyway?)- },- endCompat: function CanvasGraphics_endCompat() {- // TODO stop ignoring undefined operators- },-- // Helper functions-- consumePath: function CanvasGraphics_consumePath() {- if (this.pendingClip) {- if (this.pendingClip == EO_CLIP) {- if ('mozFillRule' in this.ctx) {- this.ctx.mozFillRule = 'evenodd';- this.ctx.clip();- this.ctx.mozFillRule = 'nonzero';- } else {- try {- this.ctx.clip('evenodd');- } catch (ex) {- // shouldn't really happen, but browsers might think differently- this.ctx.clip();- }- }- } else {- this.ctx.clip();- }- this.pendingClip = null;- }- this.ctx.beginPath();- },- getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {- var inverse = this.ctx.mozCurrentTransformInverse;- // max of the current horizontal and vertical scale- return Math.sqrt(Math.max(- (inverse[0] * inverse[0] + inverse[1] * inverse[1]),- (inverse[2] * inverse[2] + inverse[3] * inverse[3])));- },- getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {- var transform = this.ctx.mozCurrentTransform;- return [- transform[0] * x + transform[2] * y + transform[4],- transform[1] * x + transform[3] * y + transform[5]- ];- }- };-- for (var op in OPS) {- CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];- }-- return CanvasGraphics;-})();----var WebGLUtils = (function WebGLUtilsClosure() {- function loadShader(gl, code, shaderType) {- var shader = gl.createShader(shaderType);- gl.shaderSource(shader, code);- gl.compileShader(shader);- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);- if (!compiled) {- var errorMsg = gl.getShaderInfoLog(shader);- throw new Error('Error during shader compilation: ' + errorMsg);- }- return shader;- }- function createVertexShader(gl, code) {- return loadShader(gl, code, gl.VERTEX_SHADER);- }- function createFragmentShader(gl, code) {- return loadShader(gl, code, gl.FRAGMENT_SHADER);- }- function createProgram(gl, shaders) {- var program = gl.createProgram();- for (var i = 0, ii = shaders.length; i < ii; ++i) {- gl.attachShader(program, shaders[i]);- }- gl.linkProgram(program);- var linked = gl.getProgramParameter(program, gl.LINK_STATUS);- if (!linked) {- var errorMsg = gl.getProgramInfoLog(program);- throw new Error('Error during program linking: ' + errorMsg);- }- return program;- }- function createTexture(gl, image, textureId) {- gl.activeTexture(textureId);- var texture = gl.createTexture();- gl.bindTexture(gl.TEXTURE_2D, texture);-- // Set the parameters so we can render any size image.- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);-- // Upload the image into the texture.- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);- return texture;- }-- var currentGL, currentCanvas;- function generageGL() {- if (currentGL) {- return;- }- currentCanvas = document.createElement('canvas');- currentGL = currentCanvas.getContext('webgl',- { premultipliedalpha: false });- }-- var smaskVertexShaderCode = '\- attribute vec2 a_position; \- attribute vec2 a_texCoord; \- \- uniform vec2 u_resolution; \- \- varying vec2 v_texCoord; \- \- void main() { \- vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \- gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \- \- v_texCoord = a_texCoord; \- } ';-- var smaskFragmentShaderCode = '\- precision mediump float; \- \- uniform vec4 u_backdrop; \- uniform int u_subtype; \- uniform sampler2D u_image; \- uniform sampler2D u_mask; \- \- varying vec2 v_texCoord; \- \- void main() { \- vec4 imageColor = texture2D(u_image, v_texCoord); \- vec4 maskColor = texture2D(u_mask, v_texCoord); \- if (u_backdrop.a > 0.0) { \- maskColor.rgb = maskColor.rgb * maskColor.a + \- u_backdrop.rgb * (1.0 - maskColor.a); \- } \- float lum; \- if (u_subtype == 0) { \- lum = maskColor.a; \- } else { \- lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \- maskColor.b * 0.11; \- } \- imageColor.a *= lum; \- imageColor.rgb *= imageColor.a; \- gl_FragColor = imageColor; \- } ';-- var smaskCache = null;-- function initSmaskGL() {- var canvas, gl;-- generageGL();- canvas = currentCanvas;- currentCanvas = null;- gl = currentGL;- currentGL = null;-- // setup a GLSL program- var vertexShader = createVertexShader(gl, smaskVertexShaderCode);- var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);- var program = createProgram(gl, [vertexShader, fragmentShader]);- gl.useProgram(program);-- var cache = {};- cache.gl = gl;- cache.canvas = canvas;- cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');- cache.positionLocation = gl.getAttribLocation(program, 'a_position');- cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');- cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');-- var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');- var texLayerLocation = gl.getUniformLocation(program, 'u_image');- var texMaskLocation = gl.getUniformLocation(program, 'u_mask');-- // provide texture coordinates for the rectangle.- var texCoordBuffer = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([- 0.0, 0.0,- 1.0, 0.0,- 0.0, 1.0,- 0.0, 1.0,- 1.0, 0.0,- 1.0, 1.0]), gl.STATIC_DRAW);- gl.enableVertexAttribArray(texCoordLocation);- gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);-- gl.uniform1i(texLayerLocation, 0);- gl.uniform1i(texMaskLocation, 1);-- smaskCache = cache;- }-- function composeSMask(layer, mask, properties) {- var width = layer.width, height = layer.height;-- if (!smaskCache) {- initSmaskGL();- }- var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;- canvas.width = width;- canvas.height = height;- gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);- gl.uniform2f(cache.resolutionLocation, width, height);-- if (properties.backdrop) {- gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],- properties.backdrop[1], properties.backdrop[2], 1);- } else {- gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);- }- gl.uniform1i(cache.subtypeLocation,- properties.subtype === 'Luminosity' ? 1 : 0);-- // Create a textures- var texture = createTexture(gl, layer, gl.TEXTURE0);- var maskTexture = createTexture(gl, mask, gl.TEXTURE1);--- // Create a buffer and put a single clipspace rectangle in- // it (2 triangles)- var buffer = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, buffer);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([- 0, 0,- width, 0,- 0, height,- 0, height,- width, 0,- width, height]), gl.STATIC_DRAW);- gl.enableVertexAttribArray(cache.positionLocation);- gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);-- // draw- gl.clearColor(0, 0, 0, 0);- gl.enable(gl.BLEND);- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);- gl.clear(gl.COLOR_BUFFER_BIT);-- gl.drawArrays(gl.TRIANGLES, 0, 6);-- gl.flush();-- gl.deleteTexture(texture);- gl.deleteTexture(maskTexture);- gl.deleteBuffer(buffer);-- return canvas;- }-- var figuresVertexShaderCode = '\- attribute vec2 a_position; \- attribute vec3 a_color; \- \- uniform vec2 u_resolution; \- uniform vec2 u_scale; \- uniform vec2 u_offset; \- \- varying vec4 v_color; \- \- void main() { \- vec2 position = (a_position + u_offset) * u_scale; \- vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \- gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \- \- v_color = vec4(a_color / 255.0, 1.0); \- } ';-- var figuresFragmentShaderCode = '\- precision mediump float; \- \- varying vec4 v_color; \- \- void main() { \- gl_FragColor = v_color; \- } ';-- var figuresCache = null;-- function initFiguresGL() {- var canvas, gl;-- generageGL();- canvas = currentCanvas;- currentCanvas = null;- gl = currentGL;- currentGL = null;-- // setup a GLSL program- var vertexShader = createVertexShader(gl, figuresVertexShaderCode);- var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);- var program = createProgram(gl, [vertexShader, fragmentShader]);- gl.useProgram(program);-- var cache = {};- cache.gl = gl;- cache.canvas = canvas;- cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');- cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');- cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');- cache.positionLocation = gl.getAttribLocation(program, 'a_position');- cache.colorLocation = gl.getAttribLocation(program, 'a_color');-- figuresCache = cache;- }-- function drawFigures(width, height, backgroundColor, figures, context) {- if (!figuresCache) {- initFiguresGL();- }- var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;-- canvas.width = width;- canvas.height = height;- gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);- gl.uniform2f(cache.resolutionLocation, width, height);-- // count triangle points- var count = 0;- var i, ii, rows;- for (i = 0, ii = figures.length; i < ii; i++) {- switch (figures[i].type) {- case 'lattice':- rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;- count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;- break;- case 'triangles':- count += figures[i].coords.length;- break;- }- }- // transfer data- var coords = new Float32Array(count * 2);- var colors = new Uint8Array(count * 3);- var coordsMap = context.coords, colorsMap = context.colors;- var pIndex = 0, cIndex = 0;- for (i = 0, ii = figures.length; i < ii; i++) {- var figure = figures[i], ps = figure.coords, cs = figure.colors;- switch (figure.type) {- case 'lattice':- var cols = figure.verticesPerRow;- rows = (ps.length / cols) | 0;- for (var row = 1; row < rows; row++) {- var offset = row * cols + 1;- for (var col = 1; col < cols; col++, offset++) {- coords[pIndex] = coordsMap[ps[offset - cols - 1]];- coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];- coords[pIndex + 2] = coordsMap[ps[offset - cols]];- coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];- coords[pIndex + 4] = coordsMap[ps[offset - 1]];- coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];- colors[cIndex] = colorsMap[cs[offset - cols - 1]];- colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];- colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];- colors[cIndex + 3] = colorsMap[cs[offset - cols]];- colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];- colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];- colors[cIndex + 6] = colorsMap[cs[offset - 1]];- colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];- colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];-- coords[pIndex + 6] = coords[pIndex + 2];- coords[pIndex + 7] = coords[pIndex + 3];- coords[pIndex + 8] = coords[pIndex + 4];- coords[pIndex + 9] = coords[pIndex + 5];- coords[pIndex + 10] = coordsMap[ps[offset]];- coords[pIndex + 11] = coordsMap[ps[offset] + 1];- colors[cIndex + 9] = colors[cIndex + 3];- colors[cIndex + 10] = colors[cIndex + 4];- colors[cIndex + 11] = colors[cIndex + 5];- colors[cIndex + 12] = colors[cIndex + 6];- colors[cIndex + 13] = colors[cIndex + 7];- colors[cIndex + 14] = colors[cIndex + 8];- colors[cIndex + 15] = colorsMap[cs[offset]];- colors[cIndex + 16] = colorsMap[cs[offset] + 1];- colors[cIndex + 17] = colorsMap[cs[offset] + 2];- pIndex += 12;- cIndex += 18;- }- }- break;- case 'triangles':- for (var j = 0, jj = ps.length; j < jj; j++) {- coords[pIndex] = coordsMap[ps[j]];- coords[pIndex + 1] = coordsMap[ps[j] + 1];- colors[cIndex] = colorsMap[cs[i]];- colors[cIndex + 1] = colorsMap[cs[j] + 1];- colors[cIndex + 2] = colorsMap[cs[j] + 2];- pIndex += 2;- cIndex += 3;- }- break;- }- }-- // draw- if (backgroundColor) {- gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,- backgroundColor[2] / 255, 1.0);- } else {- gl.clearColor(0, 0, 0, 0);- }- gl.clear(gl.COLOR_BUFFER_BIT);-- var coordsBuffer = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);- gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);- gl.enableVertexAttribArray(cache.positionLocation);- gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);-- var colorsBuffer = gl.createBuffer();- gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);- gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);- gl.enableVertexAttribArray(cache.colorLocation);- gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,- 0, 0);-- gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);- gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);-- gl.drawArrays(gl.TRIANGLES, 0, count);-- gl.flush();-- gl.deleteBuffer(coordsBuffer);- gl.deleteBuffer(colorsBuffer);-- return canvas;- }-- function cleanup() {- smaskCache = null;- figuresCache = null;- }-- return {- get isEnabled() {- if (PDFJS.disableWebGL) {- return false;- }- var enabled = false;- try {- generageGL();- enabled = !!currentGL;- } catch (e) { }- return shadow(this, 'isEnabled', enabled);- },- composeSMask: composeSMask,- drawFigures: drawFigures,- clear: cleanup- };-})();---var ShadingIRs = {};--ShadingIRs.RadialAxial = {- fromIR: function RadialAxial_fromIR(raw) {- var type = raw[1];- var colorStops = raw[2];- var p0 = raw[3];- var p1 = raw[4];- var r0 = raw[5];- var r1 = raw[6];- return {- type: 'Pattern',- getPattern: function RadialAxial_getPattern(ctx) {- var grad;- if (type === 'axial') {- grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);- } else if (type === 'radial') {- grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);- }-- for (var i = 0, ii = colorStops.length; i < ii; ++i) {- var c = colorStops[i];- grad.addColorStop(c[0], c[1]);- }- return grad;- }- };- }-};--var createMeshCanvas = (function createMeshCanvasClosure() {- function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {- // Very basic Gouraud-shaded triangle rasterization algorithm.- var coords = context.coords, colors = context.colors;- var bytes = data.data, rowSize = data.width * 4;- var tmp;- if (coords[p1 + 1] > coords[p2 + 1]) {- tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;- }- if (coords[p2 + 1] > coords[p3 + 1]) {- tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;- }- if (coords[p1 + 1] > coords[p2 + 1]) {- tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;- }- var x1 = (coords[p1] + context.offsetX) * context.scaleX;- var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;- var x2 = (coords[p2] + context.offsetX) * context.scaleX;- var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;- var x3 = (coords[p3] + context.offsetX) * context.scaleX;- var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;- if (y1 >= y3) {- return;- }- var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];- var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];- var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];-- var minY = Math.round(y1), maxY = Math.round(y3);- var xa, car, cag, cab;- var xb, cbr, cbg, cbb;- var k;- for (var y = minY; y <= maxY; y++) {- if (y < y2) {- k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);- xa = x1 - (x1 - x2) * k;- car = c1r - (c1r - c2r) * k;- cag = c1g - (c1g - c2g) * k;- cab = c1b - (c1b - c2b) * k;- } else {- k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);- xa = x2 - (x2 - x3) * k;- car = c2r - (c2r - c3r) * k;- cag = c2g - (c2g - c3g) * k;- cab = c2b - (c2b - c3b) * k;- }- k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);- xb = x1 - (x1 - x3) * k;- cbr = c1r - (c1r - c3r) * k;- cbg = c1g - (c1g - c3g) * k;- cbb = c1b - (c1b - c3b) * k;- var x1_ = Math.round(Math.min(xa, xb));- var x2_ = Math.round(Math.max(xa, xb));- var j = rowSize * y + x1_ * 4;- for (var x = x1_; x <= x2_; x++) {- k = (xa - x) / (xa - xb);- k = k < 0 ? 0 : k > 1 ? 1 : k;- bytes[j++] = (car - (car - cbr) * k) | 0;- bytes[j++] = (cag - (cag - cbg) * k) | 0;- bytes[j++] = (cab - (cab - cbb) * k) | 0;- bytes[j++] = 255;- }- }- }-- function drawFigure(data, figure, context) {- var ps = figure.coords;- var cs = figure.colors;- var i, ii;- switch (figure.type) {- case 'lattice':- var verticesPerRow = figure.verticesPerRow;- var rows = Math.floor(ps.length / verticesPerRow) - 1;- var cols = verticesPerRow - 1;- for (i = 0; i < rows; i++) {- var q = i * verticesPerRow;- for (var j = 0; j < cols; j++, q++) {- drawTriangle(data, context,- ps[q], ps[q + 1], ps[q + verticesPerRow],- cs[q], cs[q + 1], cs[q + verticesPerRow]);- drawTriangle(data, context,- ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],- cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);- }- }- break;- case 'triangles':- for (i = 0, ii = ps.length; i < ii; i += 3) {- drawTriangle(data, context,- ps[i], ps[i + 1], ps[i + 2],- cs[i], cs[i + 1], cs[i + 2]);- }- break;- default:- error('illigal figure');- break;- }- }-- function createMeshCanvas(bounds, combinesScale, coords, colors, figures,- backgroundColor) {- // we will increase scale on some weird factor to let antialiasing take- // care of "rough" edges- var EXPECTED_SCALE = 1.1;- // MAX_PATTERN_SIZE is used to avoid OOM situation.- var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough-- var offsetX = Math.floor(bounds[0]);- var offsetY = Math.floor(bounds[1]);- var boundsWidth = Math.ceil(bounds[2]) - offsetX;- var boundsHeight = Math.ceil(bounds[3]) - offsetY;-- var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *- EXPECTED_SCALE)), MAX_PATTERN_SIZE);- var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *- EXPECTED_SCALE)), MAX_PATTERN_SIZE);- var scaleX = boundsWidth / width;- var scaleY = boundsHeight / height;-- var context = {- coords: coords,- colors: colors,- offsetX: -offsetX,- offsetY: -offsetY,- scaleX: 1 / scaleX,- scaleY: 1 / scaleY- };-- var canvas, tmpCanvas, i, ii;- if (WebGLUtils.isEnabled) {- canvas = WebGLUtils.drawFigures(width, height, backgroundColor,- figures, context);-- // https://bugzilla.mozilla.org/show_bug.cgi?id=972126- tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);- tmpCanvas.context.drawImage(canvas, 0, 0);- canvas = tmpCanvas.canvas;- } else {- tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);- var tmpCtx = tmpCanvas.context;-- var data = tmpCtx.createImageData(width, height);- if (backgroundColor) {- var bytes = data.data;- for (i = 0, ii = bytes.length; i < ii; i += 4) {- bytes[i] = backgroundColor[0];- bytes[i + 1] = backgroundColor[1];- bytes[i + 2] = backgroundColor[2];- bytes[i + 3] = 255;- }- }- for (i = 0; i < figures.length; i++) {- drawFigure(data, figures[i], context);- }- tmpCtx.putImageData(data, 0, 0);- canvas = tmpCanvas.canvas;- }-- return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,- scaleX: scaleX, scaleY: scaleY};- }- return createMeshCanvas;-})();--ShadingIRs.Mesh = {- fromIR: function Mesh_fromIR(raw) {- var type = raw[1];- var coords = raw[2];- var colors = raw[3];- var figures = raw[4];- var bounds = raw[5];- var matrix = raw[6];- var bbox = raw[7];- var background = raw[8];- return {- type: 'Pattern',- getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {- var combinedScale;- // Obtain scale from matrix and current transformation matrix.- if (shadingFill) {- combinedScale = Util.singularValueDecompose2dScale(- ctx.mozCurrentTransform);- } else {- var matrixScale = Util.singularValueDecompose2dScale(matrix);- var curMatrixScale = Util.singularValueDecompose2dScale(- owner.baseTransform);- combinedScale = [matrixScale[0] * curMatrixScale[0],- matrixScale[1] * curMatrixScale[1]];- }--- // Rasterizing on the main thread since sending/queue large canvases- // might cause OOM.- var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale,- coords, colors, figures, shadingFill ? null : background);-- if (!shadingFill) {- ctx.setTransform.apply(ctx, owner.baseTransform);- if (matrix) {- ctx.transform.apply(ctx, matrix);- }- }-- ctx.translate(temporaryPatternCanvas.offsetX,- temporaryPatternCanvas.offsetY);- ctx.scale(temporaryPatternCanvas.scaleX,- temporaryPatternCanvas.scaleY);-- return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');- }- };- }-};--ShadingIRs.Dummy = {- fromIR: function Dummy_fromIR() {- return {- type: 'Pattern',- getPattern: function Dummy_fromIR_getPattern() {- return 'hotpink';- }- };- }-};--function getShadingPatternFromIR(raw) {- var shadingIR = ShadingIRs[raw[0]];- if (!shadingIR) {- error('Unknown IR type: ' + raw[0]);- }- return shadingIR.fromIR(raw);-}--var TilingPattern = (function TilingPatternClosure() {- var PaintType = {- COLORED: 1,- UNCOLORED: 2- };-- var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough-- function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {- this.name = IR[1][0].name;- this.operatorList = IR[2];- this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];- this.bbox = IR[4];- this.xstep = IR[5];- this.ystep = IR[6];- this.paintType = IR[7];- this.tilingType = IR[8];- this.color = color;- this.objs = objs;- this.commonObjs = commonObjs;- this.baseTransform = baseTransform;- this.type = 'Pattern';- this.ctx = ctx;- }-- TilingPattern.prototype = {- createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {- var operatorList = this.operatorList;- var bbox = this.bbox;- var xstep = this.xstep;- var ystep = this.ystep;- var paintType = this.paintType;- var tilingType = this.tilingType;- var color = this.color;- var objs = this.objs;- var commonObjs = this.commonObjs;- var ctx = this.ctx;-- info('TilingType: ' + tilingType);-- var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];-- var topLeft = [x0, y0];- // we want the canvas to be as large as the step size- var botRight = [x0 + xstep, y0 + ystep];-- var width = botRight[0] - topLeft[0];- var height = botRight[1] - topLeft[1];-- // Obtain scale from matrix and current transformation matrix.- var matrixScale = Util.singularValueDecompose2dScale(this.matrix);- var curMatrixScale = Util.singularValueDecompose2dScale(- this.baseTransform);- var combinedScale = [matrixScale[0] * curMatrixScale[0],- matrixScale[1] * curMatrixScale[1]];-- // MAX_PATTERN_SIZE is used to avoid OOM situation.- // Use width and height values that are as close as possible to the end- // result when the pattern is used. Too low value makes the pattern look- // blurry. Too large value makes it look too crispy.- width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),- MAX_PATTERN_SIZE);-- height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),- MAX_PATTERN_SIZE);-- var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);- var tmpCtx = tmpCanvas.context;- var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);- graphics.groupLevel = owner.groupLevel;-- this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);-- this.setScale(width, height, xstep, ystep);- this.transformToScale(graphics);-- // transform coordinates to pattern space- var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];- graphics.transform.apply(graphics, tmpTranslate);-- this.clipBbox(graphics, bbox, x0, y0, x1, y1);-- graphics.executeOperatorList(operatorList);- return tmpCanvas.canvas;- },-- setScale: function TilingPattern_setScale(width, height, xstep, ystep) {- this.scale = [width / xstep, height / ystep];- },-- transformToScale: function TilingPattern_transformToScale(graphics) {- var scale = this.scale;- var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];- graphics.transform.apply(graphics, tmpScale);- },-- scaleToContext: function TilingPattern_scaleToContext() {- var scale = this.scale;- this.ctx.scale(1 / scale[0], 1 / scale[1]);- },-- clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {- if (bbox && isArray(bbox) && 4 == bbox.length) {- var bboxWidth = x1 - x0;- var bboxHeight = y1 - y0;- graphics.rectangle(x0, y0, bboxWidth, bboxHeight);- graphics.clip();- graphics.endPath();- }- },-- setFillAndStrokeStyleToContext:- function setFillAndStrokeStyleToContext(context, paintType, color) {- switch (paintType) {- case PaintType.COLORED:- var ctx = this.ctx;- context.fillStyle = ctx.fillStyle;- context.strokeStyle = ctx.strokeStyle;- break;- case PaintType.UNCOLORED:- var rgbColor = ColorSpace.singletons.rgb.getRgb(color, 0);- var cssColor = Util.makeCssRgb(rgbColor);- context.fillStyle = cssColor;- context.strokeStyle = cssColor;- break;- default:- error('Unsupported paint type: ' + paintType);- }- },-- getPattern: function TilingPattern_getPattern(ctx, owner) {- var temporaryPatternCanvas = this.createPatternCanvas(owner);-- ctx = this.ctx;- ctx.setTransform.apply(ctx, this.baseTransform);- ctx.transform.apply(ctx, this.matrix);- this.scaleToContext();-- return ctx.createPattern(temporaryPatternCanvas, 'repeat');- }- };-- return TilingPattern;-})();---PDFJS.disableFontFace = false;--var FontLoader = {- insertRule: function fontLoaderInsertRule(rule) {- var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');- if (!styleElement) {- styleElement = document.createElement('style');- styleElement.id = 'PDFJS_FONT_STYLE_TAG';- document.documentElement.getElementsByTagName('head')[0].appendChild(- styleElement);- }-- var styleSheet = styleElement.sheet;- styleSheet.insertRule(rule, styleSheet.cssRules.length);- },-- clear: function fontLoaderClear() {- var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');- if (styleElement) {- styleElement.parentNode.removeChild(styleElement);- }- },- get loadTestFont() {- // This is a CFF font with 1 glyph for '.' that fills its entire width and- // height.- return shadow(this, 'loadTestFont', atob(- 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +- 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +- 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +- 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +- 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +- 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +- 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +- 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +- 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +- 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +- 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +- 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +- 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +- 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +- 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +- 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +- 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +- 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +- 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +- 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +- 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +- 'ABAAAAAAAAAAAD6AAAAAAAAA=='- ));- },-- loadTestFontId: 0,-- loadingContext: {- requests: [],- nextRequestId: 0- },-- isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {- if (isWorker) {- return false;- }-- // User agent string sniffing is bad, but there is no reliable way to tell- // if font is fully loaded and ready to be used with canvas.- var userAgent = window.navigator.userAgent;- var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);- if (m && m[1] >= 14) {- return true;- }- // TODO other browsers- return false;- })(),-- bind: function fontLoaderBind(fonts, callback) {- assert(!isWorker, 'bind() shall be called from main thread');-- var rules = [], fontsToLoad = [];- for (var i = 0, ii = fonts.length; i < ii; i++) {- var font = fonts[i];-- // Add the font to the DOM only once or skip if the font- // is already loaded.- if (font.attached || font.loading === false) {- continue;- }- font.attached = true;-- var rule = font.bindDOM();- if (rule) {- rules.push(rule);- fontsToLoad.push(font);- }- }-- var request = FontLoader.queueLoadingCallback(callback);- if (rules.length > 0 && !this.isSyncFontLoadingSupported) {- FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);- } else {- request.complete();- }- },-- queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {- function LoadLoader_completeRequest() {- assert(!request.end, 'completeRequest() cannot be called twice');- request.end = Date.now();-- // sending all completed requests in order how they were queued- while (context.requests.length > 0 && context.requests[0].end) {- var otherRequest = context.requests.shift();- setTimeout(otherRequest.callback, 0);- }- }-- var context = FontLoader.loadingContext;- var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);- var request = {- id: requestId,- complete: LoadLoader_completeRequest,- callback: callback,- started: Date.now()- };- context.requests.push(request);- return request;- },-- prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,- fonts,- request) {- /** Hack begin */- // There's currently no event when a font has finished downloading so the- // following code is a dirty hack to 'guess' when a font is- // ready. It's assumed fonts are loaded in order, so add a known test- // font after the desired fonts and then test for the loading of that- // test font.-- function int32(data, offset) {- return (data.charCodeAt(offset) << 24) |- (data.charCodeAt(offset + 1) << 16) |- (data.charCodeAt(offset + 2) << 8) |- (data.charCodeAt(offset + 3) & 0xff);- }-- function spliceString(s, offset, remove, insert) {- var chunk1 = s.substr(0, offset);- var chunk2 = s.substr(offset + remove);- return chunk1 + insert + chunk2;- }-- var i, ii;-- var canvas = document.createElement('canvas');- canvas.width = 1;- canvas.height = 1;- var ctx = canvas.getContext('2d');-- var called = 0;- function isFontReady(name, callback) {- called++;- // With setTimeout clamping this gives the font ~100ms to load.- if(called > 30) {- warn('Load test font never loaded.');- callback();- return;- }- ctx.font = '30px ' + name;- ctx.fillText('.', 0, 20);- var imageData = ctx.getImageData(0, 0, 1, 1);- if (imageData.data[3] > 0) {- callback();- return;- }- setTimeout(isFontReady.bind(null, name, callback));- }-- var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;- // Chromium seems to cache fonts based on a hash of the actual font data,- // so the font must be modified for each load test else it will appear to- // be loaded already.- // TODO: This could maybe be made faster by avoiding the btoa of the full- // font by splitting it in chunks before hand and padding the font id.- var data = this.loadTestFont;- var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)- data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,- loadTestFontId);- // CFF checksum is important for IE, adjusting it- var CFF_CHECKSUM_OFFSET = 16;- var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'- var checksum = int32(data, CFF_CHECKSUM_OFFSET);- for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {- checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;- }- if (i < loadTestFontId.length) { // align to 4 bytes boundary- checksum = (checksum - XXXX_VALUE +- int32(loadTestFontId + 'XXX', i)) | 0;- }- data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));-- var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';- var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +- url + '}';- FontLoader.insertRule(rule);-- var names = [];- for (i = 0, ii = fonts.length; i < ii; i++) {- names.push(fonts[i].loadedName);- }- names.push(loadTestFontId);-- var div = document.createElement('div');- div.setAttribute('style',- 'visibility: hidden;' +- 'width: 10px; height: 10px;' +- 'position: absolute; top: 0px; left: 0px;');- for (i = 0, ii = names.length; i < ii; ++i) {- var span = document.createElement('span');- span.textContent = 'Hi';- span.style.fontFamily = names[i];- div.appendChild(span);- }- document.body.appendChild(div);-- isFontReady(loadTestFontId, function() {- document.body.removeChild(div);- request.complete();- });- /** Hack end */- }-};--var FontFace = (function FontFaceClosure() {- function FontFace(name, file, properties) {- this.compiledGlyphs = {};- if (arguments.length === 1) {- // importing translated data- var data = arguments[0];- for (var i in data) {- this[i] = data[i];- }- return;- }- }- FontFace.prototype = {- bindDOM: function FontFace_bindDOM() {- if (!this.data) {- return null;- }-- if (PDFJS.disableFontFace) {- this.disableFontFace = true;- return null;- }-- var data = bytesToString(new Uint8Array(this.data));- var fontName = this.loadedName;-- // Add the font-face rule to the document- var url = ('url(data:' + this.mimetype + ';base64,' +- window.btoa(data) + ');');- var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';- FontLoader.insertRule(rule);-- if (PDFJS.pdfBug && 'FontInspector' in globalScope &&- globalScope['FontInspector'].enabled) {- globalScope['FontInspector'].fontAdded(this, url);- }-- return rule;- },-- getPathGenerator: function (objs, character) {- if (!(character in this.compiledGlyphs)) {- var js = objs.get(this.loadedName + '_path_' + character);- /*jshint -W054 */- this.compiledGlyphs[character] = new Function('c', 'size', js);- }- return this.compiledGlyphs[character];- }- };- return FontFace;-})();---}).call((typeof window === 'undefined') ? this : window);--if (!PDFJS.workerSrc && typeof document !== 'undefined') {- // workerSrc is not set -- using last script url to define default location- PDFJS.workerSrc = (function () {- 'use strict';- var scriptTagContainer = document.body ||- document.getElementsByTagName('head')[0];- var pdfjsSrc = scriptTagContainer.lastChild.src;- return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');- })();-}--diff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.pngdeleted file mode 100644index bef02743f..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 1da6dc949..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.pngdeleted file mode 100644index de1d0fc90..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-next.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 0250307c0..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.pngdeleted file mode 100644index de1d0fc90..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 0250307c0..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.png b/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.pngdeleted file mode 100644index bef02743f..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/findbarButton-previous.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 1da6dc949..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/grab.cur b/data/ext/viewerPDF/pdfjs/web/images/grab.curdeleted file mode 100644index db7ad5aed..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/grab.cur and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/grabbing.cur b/data/ext/viewerPDF/pdfjs/web/images/grabbing.curdeleted file mode 100644index e0dfd04e4..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/grabbing.cur and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/loading-small.png b/data/ext/viewerPDF/pdfjs/web/images/loading-small.pngdeleted file mode 100644index 51848a70f..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/loading-small.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.pngdeleted file mode 100644index 40925e25a..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-documentProperties.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index adb240eaa..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.pngdeleted file mode 100644index e68846aa5..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-firstPage.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 3ad8af517..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.pngdeleted file mode 100644index cb85a841b..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-handTool.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 5c13f77ff..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.pngdeleted file mode 100644index be763e0c4..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-lastPage.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 8570984f2..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.pngdeleted file mode 100644index 675d6da2c..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCcw.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index b9e743122..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.png b/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.pngdeleted file mode 100644index e1c759888..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/secondaryToolbarButton-rotateCw.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index cb257b41c..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/shadow.png b/data/ext/viewerPDF/pdfjs/web/images/shadow.pngdeleted file mode 100644index 31d3bdb14..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/shadow.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/texture.png b/data/ext/viewerPDF/pdfjs/web/images/texture.pngdeleted file mode 100644index eb5ccb5ec..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/texture.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.pngdeleted file mode 100644index a187be6c9..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-bookmark.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 4efbaa675..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.pngdeleted file mode 100644index eaab35f09..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-download.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 896face45..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.pngdeleted file mode 100644index 306eb43b8..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-menuArrows.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index f7570bc0d..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.pngdeleted file mode 100644index b5cf1bd06..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-openFile.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 91ab76593..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.pngdeleted file mode 100644index 1957f79ab..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 16ebcb8ef..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.pngdeleted file mode 100644index 8219ecf83..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageDown.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 758c01d83..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.pngdeleted file mode 100644index 98e7ce481..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index a01b02380..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.pngdeleted file mode 100644index fb9daa337..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-pageUp.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index a5cfd755b..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.pngdeleted file mode 100644index 3ac21244d..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-presentationMode.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index cada9e791..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.pngdeleted file mode 100644index 51275e54b..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-print.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 53d18daf7..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.pngdeleted file mode 100644index f9b75579b..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-search.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 456b13324..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.pngdeleted file mode 100644index 843709527..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 9d9bfa4f6..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.pngdeleted file mode 100644index 1f90f83da..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-secondaryToolbarToggle.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index b066fe5cb..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.pngdeleted file mode 100644index 6f85ec061..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 291e00679..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.pngdeleted file mode 100644index 025dc9040..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-sidebarToggle.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 7f834df94..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.pngdeleted file mode 100644index aaa943021..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline-rtl.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 3410f70df..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.pngdeleted file mode 100644index 976365a50..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewOutline.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index b6a197fdf..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.pngdeleted file mode 100644index 584ba5588..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-viewThumbnail.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index fb7db9383..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.pngdeleted file mode 100644index 513d081bc..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomIn.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index d5d49d5ff..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.png b/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.pngdeleted file mode 100644index 156c26b94..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/toolbarButton-zoomOut.png and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/images/[email protected] b/data/ext/viewerPDF/pdfjs/web/images/[email protected]deleted file mode 100644index 959e1919d..000000000Binary files a/data/ext/viewerPDF/pdfjs/web/images/[email protected] and /dev/null differdiff --git a/data/ext/viewerPDF/pdfjs/web/locale/bn-BD/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/bn-BD/viewer.propertiesdeleted file mode 100644index 22466ab45..000000000--- a/data/ext/viewerPDF/pdfjs/web/locale/bn-BD/viewer.properties+++ /dev/null@@ -1,157 +0,0 @@-# 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.--# Main toolbar buttons (tooltips and alt text for images)-previous.title=পুর্ববর্তী পাতা-previous_label=পুর্ববর্তী-next.title=পরবর্তী পাতা-next_label=পরবর্তী--# LOCALIZATION NOTE (page_label, page_of):-# These strings are concatenated to form the "Page: X of Y" string.-# Do not translate "{{pageCount}}", it will be substituted with a number-# representing the total number of pages.-page_label=পাতা:--zoom_out.title=জুম-আউট করুন-zoom_out_label=জুম-আউট করুন-zoom_in.title=জুম-ইন করুন-zoom_in_label=জুম-ইন করুন-presentation_mode.title=প্রেজেন্টেশন মোড এ পরিবর্তন করুন-presentation_mode_label=প্রেজেন্টেশন ভিউ-open_file.title=ফাইল খুলুন-open_file_label=ফাইল খুলুন-print.title=প্রিন্ট-print_label=প্রিন্ট-download.title=ডাউনলোড-download_label=ডাউনলোড-bookmark.title=বর্তমান ভিউ (নতুন উইন্ডোতে খুলুন বা কপি করুন)-bookmark_label=বর্তমান ভিউ--# Secondary toolbar and context menu-tools.title=টুলস-tools_label=টুলস-first_page.title=প্রথম পাতায় যাও-first_page.label=প্রথম পাতায় যাও-first_page_label=প্রথম পাতায় যাও-last_page.title=শেষ পাতায় যাও-last_page.label=শেষ পাতায় যাও-last_page_label=শেষ পাতায় যাও-page_rotate_cw.title=ডানদিকে ঘোরাও-page_rotate_cw.label=ডানদিকে ঘোরাও-page_rotate_cw_label=ডানদিকে ঘোরাও-page_rotate_ccw.title=বামদিকে ঘোরাও-page_rotate_ccw.label=বামদিকে ঘোরাও-page_rotate_ccw_label=বামদিকে ঘোরাও--hand_tool_enable.title=হ্যাণ্ড টুল চালু কর-hand_tool_enable_label=হ্যাণ্ড টুল চালু কর-hand_tool_disable.title=হ্যাণ্ড টুল বন্ধ কর-hand_tool_disable_label=হ্যাণ্ড টুল বন্ধ কর--# Document properties dialog box-document_properties.title=ডকুমেন্ট বিবরন…-document_properties_label=ডকুমেন্ট বিবরন…-document_properties_file_name=ফাইলের নাম:-document_properties_file_size=ফাইলের সাইজ:-document_properties_kb={{size_kb}} কিলোবাইট ({{size_b}} bytes)-document_properties_mb={{size_mb}} মেগাবাইট ({{size_b}} bytes)-document_properties_title=নাম:-document_properties_author=লেখক:-document_properties_subject=বিষয়:-document_properties_keywords=কি-ওয়ার্ড:-document_properties_creation_date=তৈরির তারিখ:-document_properties_modification_date=পরিবর্তনের তারিখ:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=তৈরিকারক:-document_properties_producer=PDF উৎপাদনকারী:-document_properties_version=PDF ভার্শন:-document_properties_page_count=পেজ সংখ্যা:-document_properties_close=বন্ধ--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_sidebar.title=সাইডবার Toggle করুন-toggle_sidebar_label=সাইডবার Toggle করুন-outline.title=ডকুমেন্ট আউটলাইন দেখাও-outline_label=ডকুমেন্ট আউটলাইন-thumbs.title=থাম্বনেইল দেখাও-thumbs_label=থাম্বনেইল-findbar.title=ডকুমেন্ট এ খুজুন-findbar_label=খুজুন--# Thumbnails panel item (tooltip and alt text for images)-# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page-# number.-thumb_page_title=পেজ {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=পেজ এর থাম্বনেইল {{page}}--# Find panel button title and messages-find_label=খুজুন:-find_previous.title=এই শব্দের পুর্ববর্তী পাওয়া অংশগুলো দেখুন-find_previous_label=পুর্ববর্তী-find_next.title=এই শব্দের পরবর্তী পাওয়া অংশগুলো দেখুন-find_next_label=পরবর্তী-find_highlight=সবুগুলোকে হাইলাইট-find_reached_top=ডকুমেন্ট এর প্রথমে চলে এসেছি, শেষের দিক থেকে খোজ চালিয়ে যান-find_reached_bottom=ডকুমেন্ট এর শেষের দিকে চলে এসেছি, প্রথম দিক থেকে চালিয়ে যান-find_not_found=পাওয়া যায়নি--# Error panel labels-error_more_info=বেশি তথ্য-error_less_info=অল্প তথ্য-error_close=বন্ধ-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=PDF.js v{{version}} (build: {{build}})-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=বার্তা: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=স্ট্যাক: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=ফাইল: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=লাইন: {{line}}-rendering_error=পেজ রেন্ডারিং এর সময় কিছু সমস্যা হয়েছে।--# Predefined zoom values-page_scale_width=পেজ এর প্রস্থ-page_scale_fit=পেজ ফিট করুন-page_scale_auto=সয়ংক্রিয় জুম-page_scale_actual=আসল সাইজ--# Loading indicator messages-loading_error_indicator=সমস্যা-loading_error=পিডিএফ লোড হতে সমস্যা হচ্ছে।-invalid_file_error=অসমর্থিত বা করাপ্ট হওয়া পিডিএফ ফাইল।-missing_file_error=পিডিএফ ফাইল পাওয়া যাচ্ছে না।--# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.-# "{{type}}" will be replaced with an annotation type from a list defined in-# the PDF spec (32000-1:2008 Table 169 – Annotation types).-# Some common types are e.g.: "Check", "Text", "Comment", "Note"-password_label=পিডিএফ টি খুলতে পাসওয়ার্ড প্রবেশ করান।-password_invalid=ভুল পাসওয়ার্ড । অনুগ্রহ করে আবার চেষ্টা করুন।-password_ok=ঠিক আছে-password_cancel=বাতিল--printing_not_supported=সতর্কবার্তা: এই ব্রাউজারে প্রিন্ট করা সম্পুর্নভাবে সমর্থিত নয়-printing_not_ready=সতর্কবার্তা: পিডিএফ ফাইল সম্পুর্নভাবে প্রিন্ট করার জন্য লোড হয়নি।-web_fonts_disabled=ওয়েব ফন্ট Disable রয়েছে: এমবেডেড পিডিএফ ফন্ট ব্যাবহার করা যাচ্ছে না-document_colors_disabled=পিডিএফ ফাইলসমূহ তাদের নিজস্ব রঙ ব্যাবহার করতে পারবে না: \'Allow pages to choose their own colors\' অপশনটি ব্রাউজারে বন্ধ রয়েছে।diff --git a/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.propertiesdeleted file mode 100644index cd6f409b4..000000000--- a/data/ext/viewerPDF/pdfjs/web/locale/cs/viewer.properties+++ /dev/null@@ -1,161 +0,0 @@-# 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.--# Main toolbar buttons (tooltips and alt text for images)-previous.title=Předchozí stránka-previous_label=Předchozí-next.title=Další stránka-next_label=Další--# LOCALIZATION NOTE (page_label, page_of):-# These strings are concatenated to form the "Page: X of Y" string.-# Do not translate "{{pageCount}}", it will be substituted with a number-# representing the total number of pages.-page_label=Stránka:-page_of=z {{pageCount}}--zoom_out.title=Zmenšit-zoom_out_label=Zmenšit-zoom_in.title=Zvětšit-zoom_in_label=Přiblížit-zoom.title=Zvětšit-presentation_mode.title=Přepnout do prezentačního režimu-presentation_mode_label=Prezentační režim-open_file.title=Otevřít soubor-open_file_label=Otevřít-print.title=Tisk-print_label=Tisk-download.title=Stáhnout-download_label=Stáhnout-bookmark.title=Aktuální zobrazení (zkopírovat nebo otevřít v novém okně)-bookmark_label=Aktuální zobrazení--# Secondary toolbar and context menu-tools.title=Nástroje-tools_label=Nástroje-first_page.title=Přejít na první stránku-first_page.label=Přejít na první stránku-first_page_label=Přejít na první stránku-last_page.title=Přejít na poslední stránku-last_page.label=Přejít na poslední stránku-last_page_label=Přejít na poslední stránku-page_rotate_cw.title=Otočit ve směru hodinových ručiček-page_rotate_cw.label=Otočit ve směru hodinových ručiček-page_rotate_cw_label=Otočit ve směru hodinových ručiček-page_rotate_ccw.title=Otočit proti směru hodinových ručiček-page_rotate_ccw.label=Otočit proti směru hodinových ručiček-page_rotate_ccw_label=Otočit proti směru hodinových ručiček--hand_tool_enable.title=Zapnout ručičku-hand_tool_enable_label=Zapnout ručičku-hand_tool_disable.title=Vypnout ručičku-hand_tool_disable_label=Vypnout ručičku--# Document properties dialog box-document_properties.title=Vlastnosti dokumentu…-document_properties_label=Vlastnosti dokumentu…-document_properties_file_name=Název souboru:-document_properties_file_size=Velikost souboru:-document_properties_kb={{size_kb}} KB ({{size_b}} bajtů)-document_properties_mb={{size_mb}} MB ({{size_b}} bajtů)-document_properties_title=Název:-document_properties_author=Autor:-document_properties_subject=Předmět:-document_properties_keywords=Klíčové slova:-document_properties_creation_date=Datum vytvoření:-document_properties_modification_date=Datum úpravy:-document_properties_date_string={{date}}, {{time}}-document_properties_creator=Tvůrce:-document_properties_producer=Tvůrce PDF:-document_properties_version=Verze PDF:-document_properties_page_count=Počet stránek:-document_properties_close=Zavřít--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_sidebar.title=Přepnout posuvník-toggle_sidebar_label=Přepnout posuvník-outline.title=Zobrazit osnovu dokumentu-outline_label=Přehled dokumentu-thumbs.title=Zobrazit náhledy-thumbs_label=Náhledy-findbar.title=Najít v dokumentu-findbar_label=Najít--# Thumbnails panel item (tooltip and alt text for images)-# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page-# number.-thumb_page_title=Stránka {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=Náhled stránky {{page}}--# Find panel button title and messages-find_label=Najít:-find_previous.title=Najít předchozí výskyt výrazu-find_previous_label=Předchozí-find_next.title=Najít další výskyt výrazu-find_next_label=Další-find_highlight=Zvýraznit vše-find_match_case_label=Rozlišovat velikost-find_reached_top=Dosažen začátek dokumentu, pokračuje se od konce-find_reached_bottom=Dosažen konec dokumentu, pokračuje se od začátku-find_not_found=Výraz nenalezen--# Error panel labels-error_more_info=Více informací-error_less_info=Méně informací-error_close=Zavřít-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=PDF.js v{{version}} (sestavení: {{build}})-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=Zpráva: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=Stack: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=Soubor: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=Řádek: {{line}}-rendering_error=Došlo k chybě při vykreslování stránky.--# Predefined zoom values-page_scale_width=Šířka stránky-page_scale_fit=Stránka-page_scale_auto=Automatické přibližení-page_scale_actual=Skutečná velikost--# Loading indicator messages-loading_error_indicator=Chyba-loading_error=Došlo k chybě při načítání PDF.-invalid_file_error=Nesprávný nebo poškozený soubor PDF.-missing_file_error=Chybějící soubor PDF.--# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.-# "{{type}}" will be replaced with an annotation type from a list defined in-# the PDF spec (32000-1:2008 Table 169 – Annotation types).-# Some common types are e.g.: "Check", "Text", "Comment", "Note"-text_annotation_type.alt=[{{type}} anotace]-password_label=Zadejte heslo k otevření tohoto soubor PDF.-password_invalid=Nesprávné heslo. Prosím, zkuste to znovu.-password_ok=OK-password_cancel=Zrušit--printing_not_supported=Varování: Tisk není plně podporován tímto prohlížečem.-printing_not_ready=Varování: PDF není zcela nahrán pro tisk.-web_fonts_disabled=Webové písma jsou vypnuty: Není možnost použít vložené fonty PDF.-document_colors_disabled=Dokumentu PDF není povoleno používat jejich vlastní barvy: \'Povolit stránkám vybrat si jejich vlastní barvy\' je deaktivováno v prohlížeči.diff --git a/data/ext/viewerPDF/pdfjs/web/locale/cy/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/cy/viewer.propertiesdeleted file mode 100644index 2133dabfb..000000000--- a/data/ext/viewerPDF/pdfjs/web/locale/cy/viewer.properties+++ /dev/null@@ -1,134 +0,0 @@-# 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.--# Main toolbar buttons (tooltips and alt text for images)-previous.title=Tudalen Flaenorol-previous_label=Blaenorol-next.title=Nesaf Tudalen-next_label=Nesaf--# LOCALIZATION NOTE (page_label, page_of):-# These strings are concatenated to form the "Page: X of Y" string.-# Do not translate "{{pageCount}}", it will be substituted with a number-# representing the total number of pages.-page_label=Tudalen:-page_of=o {{pageCount}}--zoom_out.title=Chwyddo Allan-zoom_out_label=Chwyddo Allan-zoom_in.title=Chwyddo Mewn-zoom_in_label=Chwyddo Mewn-zoom.title=Chwyddo-presentation_mode.title=Newid i'r Modd Cyflwyn-presentation_mode_label=Modd Cyflwyniad-open_file.title=Agor Ffeil-open_file_label=Agor-print.title=Llwyth-print_label=Argraffu-download.title=Lawrlwytho-download_label=Llwytho i Lawr-bookmark.title=Golwg cyfredol (copïo neu agor ffenestr newydd)-bookmark_label=Golwg cyfredol--# Secondary toolbar and context menu-tools.title=Offer-tools_label=Offer-first_page.title=Mynd i'r Dudalen Gyntaf-first_page.label=Mynd i'r Dudalen Gyntaf-first_page_label=Mynd i'r Dudalen Gyntaf-last_page.title=Mynd i'r Dudalen Olaf-last_page.label=Mynd i'r Dudalen Olaf-last_page_label=Mynd i'r Dudalen Olaf-page_rotate_cw.title=Cylchdroi yn Glocwedd-page_rotate_cw.label=Cylchdroi yn Glocwedd-page_rotate_cw_label=Cylchdroi yn Glocwedd-page_rotate_ccw.title=Cylchdroi yn Wrthglocwedd-page_rotate_ccw.label=Cylchdroi yn Wrthglocwedd-page_rotate_ccw_label=Cylchdroi yn Wrthglocwedd--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_sidebar.title=Toglo'r Bar Ochr-toggle_sidebar_label=Toglo'r Bar Ochr-outline.title=Dangos Amlinell Dogfen-outline_label=Amlinelliad Dogfen-thumbs.title=Dangos Lluniau Bach-thumbs_label=Lluniau Bach-findbar.title=Canfod yn y Ddogfen-findbar_label=Canfod--# Thumbnails panel item (tooltip and alt text for images)-# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page-# number.-thumb_page_title=Tudalen {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=Llun Bach Tudalen {{page}}--# Find panel button title and messages-find_label=Canfod:-find_previous.title=Canfod enghraifft flaenorol o'r ymadrodd-find_previous_label=Blaenorol-find_next.title=Canfod enghraifft nesaf yr ymadrodd-find_next_label=Nesaf-find_highlight=Amlygu popeth-find_match_case_label=Cydweddu maint-find_reached_top=Wedi cyrraedd brig y dudalen, parhau o'r gwaelod-find_reached_bottom=Wedi cyrraedd diwedd y dudalen, parhau o'r brig-find_not_found=Heb ganfod ymadrodd--# Error panel labels-error_more_info=Rhagor o Wybodaeth-error_less_info=Llai o wybodaeth-error_close=Cau-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=PDF.js v {{version}} (build: {{build}})-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=Neges: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=Stac: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=Ffeil: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=Llinell: {{line}}-rendering_error=Digwyddodd gwall wrth adeiladu'r dudalen.--# Predefined zoom values-page_scale_width=Lled Tudalen-page_scale_fit=Ffit Tudalen-page_scale_auto=Chwyddo Awtomatig-page_scale_actual=Maint Gwirioneddol--# Loading indicator messages-loading_error_indicator=Gwall-loading_error=Digwyddodd gwall wrth lwytho'r PDF.-invalid_file_error=Annilys neu llygredig ffeil PDF.-missing_file_error=Ar goll ffeil PDF.--# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.-# "{{type}}" will be replaced with an annotation type from a list defined in-# the PDF spec (32000-1:2008 Table 169 – Annotation types).-# Some common types are e.g.: "Check", "Text", "Comment", "Note"-text_annotation_type.alt=[Anodiad {{type}} ]-request_password=PDF yn cael ei diogelu gan gyfrinair:-invalid_password=Cyfrinair annilys.--printing_not_supported=Rhybudd: Nid yw argraffu yn cael ei gynnal yn llawn gan y porwr.-printing_not_ready=Rhybudd: Nid yw'r PDF wedi ei lwytho'n llawn ar gyfer argraffu.-web_fonts_disabled=Ffontiau gwe wedi eu hanablu: methu defnyddio ffontiau PDF mewnblanedig.-document_colors_disabled=Nid oes caniatâd i ddogfennau PDF i ddefnyddio eu lliwiau eu hunain: Mae 'Caniatáu i dudalennau ddefnyddio eu lliwiau eu hunain' wedi ei atal yn y porwr.diff --git a/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.propertiesdeleted file mode 100644index 8586490bd..000000000--- a/data/ext/viewerPDF/pdfjs/web/locale/fa/viewer.properties+++ /dev/null@@ -1,134 +0,0 @@-# Copyright 2013 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.--# Main toolbar buttons (tooltips and alt text for images)-previous.title=صفحهٔ قبلی-previous_label=قبلی-next.title=صفحهٔ بعدی-next_label=بعدی--# LOCALIZATION NOTE (page_label, page_of):-# These strings are concatenated to form the "Page: X of Y" string.-# Do not translate "{{pageCount}}", it will be substituted with a number-# representing the total number of pages.-page_label=صفحه:-page_of=از {{pageCount}}--zoom_out.title=کوچکنمایی-zoom_out_label=کوچکنمایی-zoom_in.title=بزرگنمایی-zoom_in_label=بزرگنمایی-zoom.title=زوم-presentation_mode.title=تغییر وضع به حالت نمایش-presentation_mode_label=حالت نمایش-open_file.title=بازکردن پرونده-open_file_label=بازکردن پرونده-print.title=چاپ-print_label=چاپ-download.title=بارگیری-download_label=بارگیری-bookmark.title=دید فعلی (رونوشت یا بازکردن در پنجرهٔ جدید)-bookmark_label=دید فعلی--# Secondary toolbar and context menu-tools.title=ابزارها-tools_label=ابزارها-first_page.title=رفتن به صفحهٔ اول-first_page.label=رفتن به صفحهٔ اول-first_page_label=رفتن به صفحهٔ اول-last_page.title=رفتن به صفحهٔ آخر-last_page.label=رفتن به صفحهٔ آخر-last_page_label=رفتن به صفحهٔ آخر-page_rotate_cw.title=چرخش در جهت عقربههای ساعت-page_rotate_cw.label=چرخش در جهت عقربههای ساعت-page_rotate_cw_label=چرخش در جهت عقربههای ساعت-page_rotate_ccw.title=چرخش در خلاف جهت عقربههای ساعت-page_rotate_ccw.label=چرخش در خلاف جهت عقربههای ساعت-page_rotate_ccw_label=چرخش در خلاف جهت عقربههای ساعت--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_sidebar.title=تغییر وضع نوار کناری-toggle_sidebar_label=تغییر وضع نوار کناری-outline.title=نمایش رئوس مطالب سند-outline_label=رئوس مطالب سند-thumbs.title=نمایش بندانگشتیها-thumbs_label=بندانگشتیها-findbar.title=یافتن در سند-findbar_label=پیداکردن--# Thumbnails panel item (tooltip and alt text for images)-# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page-# number.-thumb_page_title=صفحهٔ {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=بندانگشتی صفحهٔ {{page}}--# Find panel button title and messages-find_label=پیداکردن:-find_previous.title=یافتن رویداد قبلی عبارت-find_previous_label=قبلی-find_next.title=یافتن رویداد بعدی عبارت-find_next_label=بعدی-find_highlight=پررنگکردن همه-find_match_case_label=تطبیق بزرگی/کوچکی حروف-find_reached_top=به بالای سند رسید، ادامهیافته از زیر-find_reached_bottom=به انتهای سند رسید، ادامهیافته از بالا-find_not_found=عبارت پیدا نشد--# Error panel labels-error_more_info=اطلاعات بیشتر-error_less_info=اطلاعات کمتر-error_close=بستن-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=پیدیاف.جیاس نسخهٔ {{version}} (ساخت: {{build}})-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=پیغام: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=پشته: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=پرونده: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=خط: {{line}}-rendering_error=خطایی هنگام رندرکردن صفحه روی داد.--# Predefined zoom values-page_scale_width=اندازهٔ صفحه-page_scale_fit=متناسب صفحه-page_scale_auto=زوم خودکار-page_scale_actual=اندازهٔ حقیقی--# Loading indicator messages-loading_error_indicator=خطا-loading_error=خطایی هنگامی بارگیری پیدیاف روی داد.-invalid_file_error=پروندهٔ پیدیاف نامعتیر یا خراب شده.-missing_file_error=پروندهٔ پیدیاف مفقودشده.--# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.-# "{{type}}" will be replaced with an annotation type from a list defined in-# the PDF spec (32000-1:2008 Table 169 – Annotation types).-# Some common types are e.g.: "Check", "Text", "Comment", "Note"-text_annotation_type.alt=[گزارمان {{type}}]-request_password=پیدیاف توسط یک گذرواژه محافظت شدهاست:-invalid_password=گذرواژهٔ نامعتبر.--printing_not_supported=اخطار: چاپ توسط این مرورگر بهصورت کامل پشتبانی نشدهاست.-printing_not_ready=اخطار: پیدیاف برای چاپ بهطور کامل بار نشدهاست.-web_fonts_disabled=قلمهای وبی غیر فعال هستند: از قلمهای توکار پیدیاف نتوانست استفاده شود.-document_colors_disabled=اسناد پیدیاف اجازه ندارند که رنگهای خودشان را استفاده کنند: «اجازهٔ انتخاب صفحهها برای انتخاب رنگهای خود» در مرورگر غیرفعال شدهاست.diff --git a/data/ext/viewerPDF/pdfjs/web/locale/no/viewer.properties b/data/ext/viewerPDF/pdfjs/web/locale/no/viewer.propertiesdeleted file mode 100644index 6c160fc77..000000000--- a/data/ext/viewerPDF/pdfjs/web/locale/no/viewer.properties+++ /dev/null@@ -1,134 +0,0 @@-# 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.--# Main toolbar buttons (tooltips and alt text for images)-previous.title=Førre Side-previous_label=Førre-next.title=Neste side-next_label=Neste--# LOCALIZATION NOTE (page_label, page_of):-# These strings are concatenated to form the "Page: X of Y" string.-# Do not translate "{{pageCount}}", it will be substituted with a number-# representing the total number of pages.-page_label=Side:-page_of=av {{pageCount}}--zoom_out.title=Zoom ut-zoom_out_label=Zoom ut-zoom_in.title=Zoom inn-zoom_in_label=Zoom inn-zoom.title=Zoom-presentation_mode.title=Bytt til presentasjonsmodus-presentation_mode_label=Presentasjonsmodus-open_file.title=Opne fil-open_file_label=Opne-print.title=Skriv ut-print_label=Skriv ut-download.title=Last ned-download_label=Last ned-bookmark.title=Gjeldande visning (kopier eller opne i nytt vindauge)-bookmark_label=Gjeldende visning--# Secondary toolbar and context menu-tools.title=Verktøy-tools_label=Verktøy-first_page.title=Gå til første side-first_page.label=Gå til første side-first_page_label=Gå til første side-last_page.title=Gå til siste side-last_page.label=Gå til siste side-last_page_label=Gå til siste side-page_rotate_cw.title=Roter med klokka-page_rotate_cw.label=Roter med klokka-page_rotate_cw_label=Roter med klokka-page_rotate_ccw.title=Roter mot klokka-page_rotate_ccw.label=Roter mot klokka-page_rotate_ccw_label=Roter mot klokka--# Tooltips and alt text for side panel toolbar buttons-# (the _label strings are alt text for the buttons, the .title strings are-# tooltips)-toggle_sidebar.title=Veksle Sidebar-toggle_sidebar_label=Veksle Sidebar-outline.title=Vis Document Outline-outline_label=Document Outline-thumbs.title=Vis miniatyrbilder-thumbs_label=Miniatyrbilder-findbar.title=Finne i Dokument-findbar_label=Finn--# Thumbnails panel item (tooltip and alt text for images)-# LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page-# number.-thumb_page_title=Side {{page}}-# LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page-# number.-thumb_page_canvas=Thumbnail av siden {{page}}--# Find panel button title and messages-find_label=Finn:-find_previous.title=Finn tidlegare førekomst av frasa-find_previous_label=Førre-find_next.title=Finn neste førekomst av frasa-find_next_label=Neste-find_highlight=Uthev alle-find_match_case_label=Skil store/små bokstavar-find_reached_top=Nådde toppen av dokumentet, held fram frå botnen-find_reached_bottom=Nådde botnen av dokumentet, held fram frå toppen-find_not_found=Fann ikkje teksten--# Error panel labels-error_more_info=Meir info-error_less_info=Mindre info-error_close=Lukk-# LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be-# replaced by the PDF.JS version and build ID.-error_version_info=PDF.js v {{version}} (build: {{build}})-# LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an-# english string describing the error.-error_message=Melding: {{message}}-# LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack-# trace.-error_stack=Stakk: {{stack}}-# LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename-error_file=Fil: {{file}}-# LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number-error_line=Linje: {{line}}-rendering_error=Ein feil oppstod ved oppteikning av sida.--# Predefined zoom values-page_scale_width=Sidebreidde-page_scale_fit=Tilpass til sida-page_scale_auto=Automatisk zoom-page_scale_actual=Verkeleg størrelse--# Loading indicator messages-loading_error_indicator=Feil-loading_error=Ein feil oppstod ved lasting av PDF.-invalid_file_error=Ugyldig eller korrupt PDF fil.-missing_file_error=Manglande PDF-fil.--# LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip.-# "{{type}}" will be replaced with an annotation type from a list defined in-# the PDF spec (32000-1:2008 Table 169 – Annotation types).-# Some common types are e.g.: "Check", "Text", "Comment", "Note"-text_annotation_type.alt=[{{type}} annotasjon]-request_password=PDF er beskytta av eit passord:-invalid_password=Ugyldig passord.--printing_not_supported=Åtvaring: Utskrift er ikkje fullstendig støtta av denne nettlesaren.-printing_not_ready=Åtvaring: PDF ikkje fullstendig innlasta for utskrift.-web_fonts_disabled=Web-fontar er avslått: Kan ikkje bruke innbundne PDF-fontar.-document_colors_disabled=PDF-dokument har ikkje løyve til å nytte eigne fargar: \'Tillat sider å velje eigne fargar\' er slått av i nettlesaren.diff --git a/data/ext/viewerPDF/pdfjs/web/viewer.html b/data/ext/viewerPDF/pdfjs/web/viewer.htmldeleted file mode 100644index a6efbc579..000000000--- a/data/ext/viewerPDF/pdfjs/web/viewer.html+++ /dev/null@@ -1,410 +0,0 @@-<!DOCTYPE html>-<!---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.--->-<html dir="ltr" mozdisallowselectionprint moznomarginboxes>- <head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">- <meta name="google" content="notranslate">- <title>PDF.js viewer</title>--- <link rel="stylesheet" href="viewer.css"/>-- <script type="text/javascript" src="compatibility.js"></script>-- <script type="text/javascript">- function getParameterByName(name) {- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");- var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),- results = regex.exec(location.search);- return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));- }- var DEFAULT_URL = getParameterByName("cp");- </script>---<!-- This snippet is used in production, see Makefile -->-<link rel="resource" type="application/l10n" href="locale/locale.properties"/>-<script type="text/javascript" src="l10n.js"></script>-<script type="text/javascript" src="../build/pdf.js"></script>---- <script type="text/javascript" src="debugger.js"></script>- <script type="text/javascript" src="viewer.js"></script>-- </head>-- <body tabindex="1">- <div id="outerContainer" class="loadingInProgress">-- <div id="sidebarContainer">- <div id="toolbarSidebar">- <div class="splitToolbarButton toggled">- <button id="viewThumbnail" class="toolbarButton group toggled" title="Show Thumbnails" tabindex="2" data-l10n-id="thumbs">- <span data-l10n-id="thumbs_label">Thumbnails</span>- </button>- <button id="viewOutline" class="toolbarButton group" title="Show Document Outline" tabindex="3" data-l10n-id="outline">- <span data-l10n-id="outline_label">Document Outline</span>- </button>- </div>- </div>- <div id="sidebarContent">- <div id="thumbnailView">- </div>- <div id="outlineView" class="hidden">- </div>- </div>- </div> <!-- sidebarContainer -->-- <div id="mainContainer">- <div class="findbar hidden doorHanger hiddenSmallView" id="findbar">- <label for="findInput" class="toolbarLabel" data-l10n-id="find_label">Find:</label>- <input id="findInput" class="toolbarField" tabindex="41">- <div class="splitToolbarButton">- <button class="toolbarButton findPrevious" title="" id="findPrevious" tabindex="42" data-l10n-id="find_previous">- <span data-l10n-id="find_previous_label">Previous</span>- </button>- <div class="splitToolbarButtonSeparator"></div>- <button class="toolbarButton findNext" title="" id="findNext" tabindex="43" data-l10n-id="find_next">- <span data-l10n-id="find_next_label">Next</span>- </button>- </div>- <input type="checkbox" id="findHighlightAll" class="toolbarField">- <label for="findHighlightAll" class="toolbarLabel" tabindex="44" data-l10n-id="find_highlight">Highlight all</label>- <input type="checkbox" id="findMatchCase" class="toolbarField">- <label for="findMatchCase" class="toolbarLabel" tabindex="45" data-l10n-id="find_match_case_label">Match case</label>- <span id="findMsg" class="toolbarLabel"></span>- </div> <!-- findbar -->-- <div id="secondaryToolbar" class="secondaryToolbar hidden doorHangerRight">- <div id="secondaryToolbarButtonContainer">- <button id="secondaryPresentationMode" class="secondaryToolbarButton presentationMode visibleLargeView" title="Switch to Presentation Mode" tabindex="18" data-l10n-id="presentation_mode">- <span data-l10n-id="presentation_mode_label">Presentation Mode</span>- </button>-- <button id="secondaryOpenFile" class="secondaryToolbarButton openFile visibleLargeView" title="Open File" tabindex="19" data-l10n-id="open_file">- <span data-l10n-id="open_file_label">Open</span>- </button>-- <button id="secondaryPrint" class="secondaryToolbarButton print visibleMediumView" title="Print" tabindex="20" data-l10n-id="print">- <span data-l10n-id="print_label">Print</span>- </button>-- <button id="secondaryDownload" class="secondaryToolbarButton download visibleMediumView" title="Download" tabindex="21" data-l10n-id="download">- <span data-l10n-id="download_label">Download</span>- </button>-- <a href="#" id="secondaryViewBookmark" class="secondaryToolbarButton bookmark visibleSmallView" title="Current view (copy or open in new window)" tabindex="22" data-l10n-id="bookmark">- <span data-l10n-id="bookmark_label">Current View</span>- </a>-- <div class="horizontalToolbarSeparator visibleLargeView"></div>-- <button id="firstPage" class="secondaryToolbarButton firstPage" title="Go to First Page" tabindex="23" data-l10n-id="first_page">- <span data-l10n-id="first_page_label">Go to First Page</span>- </button>- <button id="lastPage" class="secondaryToolbarButton lastPage" title="Go to Last Page" tabindex="24" data-l10n-id="last_page">- <span data-l10n-id="last_page_label">Go to Last Page</span>- </button>-- <div class="horizontalToolbarSeparator"></div>-- <button id="pageRotateCw" class="secondaryToolbarButton rotateCw" title="Rotate Clockwise" tabindex="25" data-l10n-id="page_rotate_cw">- <span data-l10n-id="page_rotate_cw_label">Rotate Clockwise</span>- </button>- <button id="pageRotateCcw" class="secondaryToolbarButton rotateCcw" title="Rotate Counterclockwise" tabindex="26" data-l10n-id="page_rotate_ccw">- <span data-l10n-id="page_rotate_ccw_label">Rotate Counterclockwise</span>- </button>-- <div class="horizontalToolbarSeparator"></div>-- <button id="toggleHandTool" class="secondaryToolbarButton handTool" title="Enable hand tool" tabindex="27" data-l10n-id="hand_tool_enable">- <span data-l10n-id="hand_tool_enable_label">Enable hand tool</span>- </button>-- <div class="horizontalToolbarSeparator"></div>-- <button id="documentProperties" class="secondaryToolbarButton documentProperties" title="Document Properties…" tabindex="28" data-l10n-id="document_properties">- <span data-l10n-id="document_properties_label">Document Properties…</span>- </button>- </div>- </div> <!-- secondaryToolbar -->-- <div class="toolbar">- <div id="toolbarContainer">- <div id="toolbarViewer">- <div id="toolbarViewerLeft">- <button id="sidebarToggle" class="toolbarButton" title="Toggle Sidebar" tabindex="4" data-l10n-id="toggle_sidebar">- <span data-l10n-id="toggle_sidebar_label">Toggle Sidebar</span>- </button>- <div class="toolbarButtonSpacer"></div>- <button id="viewFind" class="toolbarButton group hiddenSmallView" title="Find in Document" tabindex="5" data-l10n-id="findbar">- <span data-l10n-id="findbar_label">Find</span>- </button>- <div class="splitToolbarButton">- <button class="toolbarButton pageUp" title="Previous Page" id="previous" tabindex="6" data-l10n-id="previous">- <span data-l10n-id="previous_label">Previous</span>- </button>- <div class="splitToolbarButtonSeparator"></div>- <button class="toolbarButton pageDown" title="Next Page" id="next" tabindex="7" data-l10n-id="next">- <span data-l10n-id="next_label">Next</span>- </button>- </div>- <label id="pageNumberLabel" class="toolbarLabel" for="pageNumber" data-l10n-id="page_label">Page: </label>- <input type="number" id="pageNumber" class="toolbarField pageNumber" value="1" size="4" min="1" tabindex="8">- <span id="numPages" class="toolbarLabel"></span>- </div>- <div id="toolbarViewerRight">- <button id="presentationMode" class="toolbarButton presentationMode hiddenLargeView" title="Switch to Presentation Mode" tabindex="12" data-l10n-id="presentation_mode">- <span data-l10n-id="presentation_mode_label">Presentation Mode</span>- </button>-- <button id="openFile" class="toolbarButton openFile hiddenLargeView" title="Open File" tabindex="13" data-l10n-id="open_file">- <span data-l10n-id="open_file_label">Open</span>- </button>-- <button id="print" class="toolbarButton print hiddenMediumView" title="Print" tabindex="14" data-l10n-id="print">- <span data-l10n-id="print_label">Print</span>- </button>-- <button id="download" class="toolbarButton download hiddenMediumView" title="Download" tabindex="15" data-l10n-id="download">- <span data-l10n-id="download_label">Download</span>- </button>- <!-- <div class="toolbarButtonSpacer"></div> -->- <a href="#" id="viewBookmark" class="toolbarButton bookmark hiddenSmallView" title="Current view (copy or open in new window)" tabindex="16" data-l10n-id="bookmark">- <span data-l10n-id="bookmark_label">Current View</span>- </a>-- <div class="verticalToolbarSeparator hiddenSmallView"></div>-- <button id="secondaryToolbarToggle" class="toolbarButton" title="Tools" tabindex="17" data-l10n-id="tools">- <span data-l10n-id="tools_label">Tools</span>- </button>- </div>- <div class="outerCenter">- <div class="innerCenter" id="toolbarViewerMiddle">- <div class="splitToolbarButton">- <button id="zoomOut" class="toolbarButton zoomOut" title="Zoom Out" tabindex="9" data-l10n-id="zoom_out">- <span data-l10n-id="zoom_out_label">Zoom Out</span>- </button>- <div class="splitToolbarButtonSeparator"></div>- <button id="zoomIn" class="toolbarButton zoomIn" title="Zoom In" tabindex="10" data-l10n-id="zoom_in">- <span data-l10n-id="zoom_in_label">Zoom In</span>- </button>- </div>- <span id="scaleSelectContainer" class="dropdownToolbarButton">- <select id="scaleSelect" title="Zoom" tabindex="11" data-l10n-id="zoom">- <option id="pageAutoOption" value="auto" selected="selected" data-l10n-id="page_scale_auto">Automatic Zoom</option>- <option id="pageActualOption" value="page-actual" data-l10n-id="page_scale_actual">Actual Size</option>- <option id="pageFitOption" value="page-fit" data-l10n-id="page_scale_fit">Fit Page</option>- <option id="pageWidthOption" value="page-width" data-l10n-id="page_scale_width">Full Width</option>- <option id="customScaleOption" value="custom"></option>- <option value="0.5">50%</option>- <option value="0.75">75%</option>- <option value="1">100%</option>- <option value="1.25">125%</option>- <option value="1.5">150%</option>- <option value="2">200%</option>- </select>- </span>- </div>- </div>- </div>- <div id="loadingBar">- <div class="progress">- <div class="glimmer">- </div>- </div>- </div>- </div>- </div>-- <menu type="context" id="viewerContextMenu">- <menuitem id="contextFirstPage" label="First Page"- data-l10n-id="first_page"></menuitem>- <menuitem id="contextLastPage" label="Last Page"- data-l10n-id="last_page"></menuitem>- <menuitem id="contextPageRotateCw" label="Rotate Clockwise"- data-l10n-id="page_rotate_cw"></menuitem>- <menuitem id="contextPageRotateCcw" label="Rotate Counter-Clockwise"- data-l10n-id="page_rotate_ccw"></menuitem>- </menu>-- <div id="viewerContainer" tabindex="0">- <div id="viewer"></div>- </div>-- <div id="errorWrapper" hidden='true'>- <div id="errorMessageLeft">- <span id="errorMessage"></span>- <button id="errorShowMore" data-l10n-id="error_more_info">- More Information- </button>- <button id="errorShowLess" data-l10n-id="error_less_info" hidden='true'>- Less Information- </button>- </div>- <div id="errorMessageRight">- <button id="errorClose" data-l10n-id="error_close">- Close- </button>- </div>- <div class="clearBoth"></div>- <textarea id="errorMoreInfo" hidden='true' readonly="readonly"></textarea>- </div>- </div> <!-- mainContainer -->-- <div id="overlayContainer" class="hidden">- <div id="promptContainer" class="hidden">- <div id="passwordContainer" class="prompt doorHanger">- <div class="row">- <p id="passwordText" data-l10n-id="password_label">Enter the password to open this PDF file:</p>- </div>- <div class="row">- <input type="password" id="password" class="toolbarField" />- </div>- <div class="buttonRow">- <button id="passwordCancel" class="overlayButton"><span data-l10n-id="password_cancel">Cancel</span></button>- <button id="passwordSubmit" class="overlayButton"><span data-l10n-id="password_ok">OK</span></button>- </div>- </div>- </div>- <div id="documentPropertiesContainer" class="hidden">- <div class="doorHanger">- <div class="row">- <span data-l10n-id="document_properties_file_name">File name:</span> <p id="fileNameField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_file_size">File size:</span> <p id="fileSizeField">-</p>- </div>- <div class="separator"></div>- <div class="row">- <span data-l10n-id="document_properties_title">Title:</span> <p id="titleField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_author">Author:</span> <p id="authorField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_subject">Subject:</span> <p id="subjectField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_keywords">Keywords:</span> <p id="keywordsField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_creation_date">Creation Date:</span> <p id="creationDateField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_modification_date">Modification Date:</span> <p id="modificationDateField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_creator">Creator:</span> <p id="creatorField">-</p>- </div>- <div class="separator"></div>- <div class="row">- <span data-l10n-id="document_properties_producer">PDF Producer:</span> <p id="producerField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_version">PDF Version:</span> <p id="versionField">-</p>- </div>- <div class="row">- <span data-l10n-id="document_properties_page_count">Page Count:</span> <p id="pageCountField">-</p>- </div>- <div class="buttonRow">- <button id="documentPropertiesClose" class="overlayButton"><span data-l10n-id="document_properties_close">Close</span></button>- </div>- </div>- </div>- </div> <!-- overlayContainer -->-- </div> <!-- outerContainer -->- <div id="printContainer"></div>-<div id="mozPrintCallback-shim" hidden>- <style scoped>-#mozPrintCallback-shim {- position: fixed;- top: 0;- left: 0;- height: 100%;- width: 100%;- z-index: 9999999;-- display: block;- text-align: center;- background-color: rgba(0, 0, 0, 0.5);-}-#mozPrintCallback-shim[hidden] {- display: none;-}-@media print {- #mozPrintCallback-shim {- display: none;- }-}--#mozPrintCallback-shim .mozPrintCallback-dialog-box {- display: inline-block;- margin: -50px auto 0;- position: relative;- top: 45%;- left: 0;- min-width: 220px;- max-width: 400px;-- padding: 9px;-- border: 1px solid hsla(0, 0%, 0%, .5);- border-radius: 2px;- box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);-- background-color: #474747;-- color: hsl(0, 0%, 85%);- font-size: 16px;- line-height: 20px;-}-#mozPrintCallback-shim .progress-row {- clear: both;- padding: 1em 0;-}-#mozPrintCallback-shim progress {- width: 100%;-}-#mozPrintCallback-shim .relative-progress {- clear: both;- float: right;-}-#mozPrintCallback-shim .progress-actions {- clear: both;-}- </style>- <div class="mozPrintCallback-dialog-box">- <!-- TODO: Localise the following strings -->- Preparing document for printing...- <div class="progress-row">- <progress value="0" max="100"></progress>- <span class="relative-progress">0%</span>- </div>- <div class="progress-actions">- <input type="button" value="Cancel" class="mozPrintCallback-cancel">- </div>- </div>-</div>-- </body>-</html>-diff --git a/data/ext/viewerPDF/pdfjs/web/viewer.css b/data/ext/viewerPDF/viewer.csssimilarity index 62%rename from data/ext/viewerPDF/pdfjs/web/viewer.cssrename to data/ext/viewerPDF/viewer.cssindex d07521705..46a7c6f38 100644--- a/data/ext/viewerPDF/pdfjs/web/viewer.css+++ b/data/ext/viewerPDF/viewer.css@@ -20,8 +20,6 @@html {height: 100%;- /* Font size is needed to make the activity bar the correct size. */- font-size: 10px;}body {@@ -35,11 +33,10 @@ input,button,select {font: message-box;- outline: none;}.hidden {- display: none !important;+ display: none;}[hidden] {display: none !important;@@ -48,7 +45,8 @@ select {#viewerContainer:-webkit-full-screen {top: 0px;border-top: 2px solid transparent;- background-color: #000;+ background-color: #404040;+ background-image: url(images/texture.png);width: 100%;height: 100%;overflow: hidden;@@ -58,36 +56,26 @@ select {#viewerContainer:-moz-full-screen {top: 0px;border-top: 2px solid transparent;- background-color: #000;+ background-color: #404040;+ background-image: url(images/texture.png);width: 100%;height: 100%;overflow: hidden;cursor: none;}-#viewerContainer:-ms-fullscreen {- top: 0px !important;- border-top: 2px solid transparent;- width: 100%;- height: 100%;- overflow: hidden !important;- cursor: none;-}--#viewerContainer:-ms-fullscreen::-ms-backdrop {- background-color: #000;-}-#viewerContainer:fullscreen {top: 0px;border-top: 2px solid transparent;- background-color: #000;+ background-color: #404040;+ background-image: url(images/texture.png);width: 100%;height: 100%;overflow: hidden;cursor: none;}+:-webkit-full-screen .page {margin-bottom: 100%;}@@ -96,10 +84,6 @@ select {margin-bottom: 100%;}-:-ms-fullscreen .page {- margin-bottom: 100% !important;-}-:fullscreen .page {margin-bottom: 100%;}@@ -112,61 +96,39 @@ select {display: none;}-:-ms-fullscreen a:not(.internalLink) {- display: none !important;-}-:fullscreen a:not(.internalLink) {display: none;}-:-webkit-full-screen .textLayer > div {- cursor: none;-}--:-moz-full-screen .textLayer > div {- cursor: none;-}--:fullscreen .textLayer > div {- cursor: none;-}--#viewerContainer.presentationControls,-#viewerContainer.presentationControls .textLayer > div {+#viewerContainer.presentationControls {cursor: default;}/* outer/inner center provides horizontal center */-.outerCenter {- pointer-events: none;- position: relative;-}html[dir='ltr'] .outerCenter {float: right;+ position: relative;right: 50%;}html[dir='rtl'] .outerCenter {float: left;- left: 50%;-}-.innerCenter {- pointer-events: auto;position: relative;+ left: 50%;}html[dir='ltr'] .innerCenter {float: right;+ position: relative;right: -50%;}html[dir='rtl'] .innerCenter {float: left;+ position: relative;left: -50%;}#outerContainer {width: 100%;height: 100%;- position: relative;}#sidebarContainer {@@ -177,17 +139,28 @@ html[dir='rtl'] .innerCenter {visibility: hidden;-webkit-transition-duration: 200ms;-webkit-transition-timing-function: ease;+ -moz-transition-duration: 200ms;+ -moz-transition-timing-function: ease;+ -ms-transition-duration: 200ms;+ -ms-transition-timing-function: ease;+ -o-transition-duration: 200ms;+ -o-transition-timing-function: ease;transition-duration: 200ms;transition-timing-function: ease;}html[dir='ltr'] #sidebarContainer {-webkit-transition-property: left;+ -moz-transition-property: left;+ -ms-transition-property: left;+ -o-transition-property: left;transition-property: left;left: -200px;}html[dir='rtl'] #sidebarContainer {-webkit-transition-property: right;+ -ms-transition-property: right;+ -o-transition-property: right;transition-property: right;right: -200px;}@@ -212,16 +185,28 @@ html[dir='rtl'] #outerContainer.sidebarOpen > #sidebarContainer {min-width: 320px;-webkit-transition-duration: 200ms;-webkit-transition-timing-function: ease;+ -moz-transition-duration: 200ms;+ -moz-transition-timing-function: ease;+ -ms-transition-duration: 200ms;+ -ms-transition-timing-function: ease;+ -o-transition-duration: 200ms;+ -o-transition-timing-function: ease;transition-duration: 200ms;transition-timing-function: ease;}html[dir='ltr'] #outerContainer.sidebarOpen > #mainContainer {-webkit-transition-property: left;+ -moz-transition-property: left;+ -ms-transition-property: left;+ -o-transition-property: left;transition-property: left;left: 200px;}html[dir='rtl'] #outerContainer.sidebarOpen > #mainContainer {-webkit-transition-property: right;+ -moz-transition-property: right;+ -ms-transition-property: right;+ -o-transition-property: right;transition-property: right;right: 200px;}@@ -232,31 +217,28 @@ html[dir='rtl'] #outerContainer.sidebarOpen > #mainContainer {overflow: auto;position: absolute;width: 200px;+background-color: hsla(0,0%,0%,.1);+ box-shadow: inset -1px 0 0 hsla(0,0%,0%,.25);}html[dir='ltr'] #sidebarContent {left: 0;- box-shadow: inset -1px 0 0 hsla(0,0%,0%,.25);}html[dir='rtl'] #sidebarContent {right: 0;- box-shadow: inset 1px 0 0 hsla(0,0%,0%,.25);}#viewerContainer {overflow: auto;+ box-shadow: inset 1px 0 0 hsla(0,0%,100%,.05);position: absolute;top: 32px;right: 0;bottom: 0;left: 0;- outline: none;}-html[dir='ltr'] #viewerContainer {- box-shadow: inset 1px 0 0 hsla(0,0%,100%,.05);-}-html[dir='rtl'] #viewerContainer {- box-shadow: inset -1px 0 0 hsla(0,0%,100%,.05);+.loadingInProgress #viewerContainer {+ top: 39px;}.toolbar {@@ -277,41 +259,25 @@ html[dir='rtl'] #viewerContainer {background-color: #424242; /* fallback */background-image: url(images/texture.png),linear-gradient(hsla(0,0%,30%,.99), hsla(0,0%,25%,.95));-}-html[dir='ltr'] #toolbarSidebar {box-shadow: inset -1px 0 0 rgba(0, 0, 0, 0.25),+inset 0 -1px 0 hsla(0,0%,100%,.05),0 1px 0 hsla(0,0%,0%,.15),0 0 1px hsla(0,0%,0%,.1);}-html[dir='rtl'] #toolbarSidebar {- box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.25),- inset 0 1px 0 hsla(0,0%,100%,.05),- 0 1px 0 hsla(0,0%,0%,.15),- 0 0 1px hsla(0,0%,0%,.1);-}-#toolbarContainer, .findbar, .secondaryToolbar {+#toolbarContainer, .findbar {position: relative;height: 32px;background-color: #474747; /* fallback */background-image: url(images/texture.png),linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));-}-html[dir='ltr'] #toolbarContainer, .findbar, .secondaryToolbar {box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),inset 0 1px 1px hsla(0,0%,0%,.15),inset 0 -1px 0 hsla(0,0%,100%,.05),0 1px 0 hsla(0,0%,0%,.15),0 1px 1px hsla(0,0%,0%,.1);}-html[dir='rtl'] #toolbarContainer, .findbar, .secondaryToolbar {- box-shadow: inset -1px 0 0 hsla(0,0%,100%,.08),- inset 0 1px 1px hsla(0,0%,0%,.15),- inset 0 -1px 0 hsla(0,0%,100%,.05),- 0 1px 0 hsla(0,0%,0%,.15),- 0 1px 1px hsla(0,0%,0%,.1);-}#toolbarViewer {height: 32px;@@ -333,10 +299,24 @@ html[dir='rtl'] #toolbarContainer, .findbar, .secondaryToolbar {height: 100%;background-color: #ddd;overflow: hidden;+ -moz-transition: width 200ms;+ -ms-transition: width 200ms;-webkit-transition: width 200ms;transition: width 200ms;}+@-moz-keyframes progressIndeterminate {+ 0% { left: 0%; }+ 50% { left: 100%; }+ 100% { left: 100%; }+}++@-ms-keyframes progressIndeterminate {+ 0% { left: 0%; }+ 50% { left: 100%; }+ 100% { left: 100%; }+}+@-webkit-keyframes progressIndeterminate {0% { left: 0%; }50% { left: 100%; }@@ -351,6 +331,8 @@ html[dir='rtl'] #toolbarContainer, .findbar, .secondaryToolbar {#loadingBar .progress.indeterminate {background-color: #999;+ -moz-transition: none;+ -ms-transition: none;-webkit-transition: none;transition: none;}@@ -363,14 +345,15 @@ html[dir='rtl'] #toolbarContainer, .findbar, .secondaryToolbar {width: 50px;background-image: linear-gradient(to right, #999 0%, #fff 50%, #999 100%);- background-size: 100% 100%;- background-repeat: no-repeat;+ background-size: 100% 100% no-repeat;+ -moz-animation: progressIndeterminate 2s linear infinite;+ -ms-animation: progressIndeterminate 2s linear infinite;-webkit-animation: progressIndeterminate 2s linear infinite;animation: progressIndeterminate 2s linear infinite;}-.findbar, .secondaryToolbar {+.findbar {top: 32px;position: absolute;z-index: 10000;@@ -405,33 +388,12 @@ html[dir='rtl'] .findbar {background-position: right;}-.secondaryToolbar {- padding: 6px;- height: auto;- z-index: 30000;-}-html[dir='ltr'] .secondaryToolbar {- right: 4px;-}-html[dir='rtl'] .secondaryToolbar {- left: 4px;-}--#secondaryToolbarButtonContainer {- max-width: 200px;- max-height: 400px;- overflow-y: auto;- margin-bottom: -4px;-}--.doorHanger,-.doorHangerRight {+.doorHanger {border: 1px solid hsla(0,0%,0%,.5);border-radius: 2px;box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);}-.doorHanger:after, .doorHanger:before,-.doorHangerRight:after, .doorHangerRight:before {+.doorHanger:after, .doorHanger:before {bottom: 100%;border: solid transparent;content: " ";@@ -440,37 +402,31 @@ html[dir='rtl'] .secondaryToolbar {position: absolute;pointer-events: none;}-.doorHanger:after,-.doorHangerRight:after {+.doorHanger:after {border-bottom-color: hsla(0,0%,32%,.99);border-width: 8px;}-.doorHanger:before,-.doorHangerRight:before {+.doorHanger:before {border-bottom-color: hsla(0,0%,0%,.5);border-width: 9px;}-html[dir='ltr'] .doorHanger:after,-html[dir='rtl'] .doorHangerRight:after {+html[dir='ltr'] .doorHanger:after {left: 13px;margin-left: -8px;}-html[dir='ltr'] .doorHanger:before,-html[dir='rtl'] .doorHangerRight:before {+html[dir='ltr'] .doorHanger:before {left: 13px;margin-left: -9px;}-html[dir='rtl'] .doorHanger:after,-html[dir='ltr'] .doorHangerRight:after {+html[dir='rtl'] .doorHanger:after {right: 13px;margin-right: -8px;}-html[dir='rtl'] .doorHanger:before,-html[dir='ltr'] .doorHangerRight:before {+html[dir='rtl'] .doorHanger:before {right: 13px;margin-right: -9px;}@@ -488,9 +444,10 @@ html[dir='ltr'] #toolbarViewerLeft {margin-left: -1px;}html[dir='rtl'] #toolbarViewerRight {- margin-right: -1px;+ margin-left: -1px;}+html[dir='ltr'] #toolbarViewerLeft,html[dir='rtl'] #toolbarViewerRight {position: absolute;@@ -535,8 +492,7 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {float: right;}-.toolbarButton,-.secondaryToolbarButton {+.toolbarButton {border: 0 none;background-color: rgba(0, 0, 0, 0);width: 32px;@@ -550,8 +506,7 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {overflow: hidden;}-.toolbarButton[disabled],-.secondaryToolbarButton[disabled] {+.toolbarButton[disabled] {opacity: .5;}@@ -578,6 +533,15 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {-webkit-transition-property: background-color, border-color, box-shadow;-webkit-transition-duration: 150ms;-webkit-transition-timing-function: ease;+ -moz-transition-property: background-color, border-color, box-shadow;+ -moz-transition-duration: 150ms;+ -moz-transition-timing-function: ease;+ -ms-transition-property: background-color, border-color, box-shadow;+ -ms-transition-duration: 150ms;+ -ms-transition-timing-function: ease;+ -o-transition-property: background-color, border-color, box-shadow;+ -o-transition-duration: 150ms;+ -o-transition-timing-function: ease;transition-property: background-color, border-color, box-shadow;transition-duration: 150ms;transition-timing-function: ease;@@ -586,7 +550,6 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton {.splitToolbarButton > .toolbarButton:hover,.splitToolbarButton > .toolbarButton:focus,.dropdownToolbarButton:hover,-.overlayButton:hover,.toolbarButton.textButton:hover,.toolbarButton.textButton:focus {background-color: hsla(0,0%,0%,.2);@@ -616,7 +579,7 @@ html[dir='rtl'] .splitToolbarButton > .toolbarButton:first-child {.splitToolbarButtonSeparator {padding: 8px 0;width: 1px;- background-color: hsla(0,0%,0%,.5);+ background-color: hsla(0,0%,00%,.5);z-index: 99;box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);display: inline-block;@@ -636,20 +599,27 @@ html[dir='rtl'] .splitToolbarButtonSeparator {-webkit-transition-property: padding;-webkit-transition-duration: 10ms;-webkit-transition-timing-function: ease;+ -moz-transition-property: padding;+ -moz-transition-duration: 10ms;+ -moz-transition-timing-function: ease;+ -ms-transition-property: padding;+ -ms-transition-duration: 10ms;+ -ms-transition-timing-function: ease;+ -o-transition-property: padding;+ -o-transition-duration: 10ms;+ -o-transition-timing-function: ease;transition-property: padding;transition-duration: 10ms;transition-timing-function: ease;}.toolbarButton,-.dropdownToolbarButton,-.overlayButton,-.secondaryToolbarButton {+.dropdownToolbarButton {min-width: 16px;padding: 2px 6px 0;border: 1px solid transparent;border-radius: 2px;- color: hsla(0,0%,100%,.8);+ color: hsl(0,0%,95%);font-size: 12px;line-height: 14px;-webkit-user-select: none;@@ -660,28 +630,32 @@ html[dir='rtl'] .splitToolbarButtonSeparator {-webkit-transition-property: background-color, border-color, box-shadow;-webkit-transition-duration: 150ms;-webkit-transition-timing-function: ease;+ -moz-transition-property: background-color, border-color, box-shadow;+ -moz-transition-duration: 150ms;+ -moz-transition-timing-function: ease;+ -ms-transition-property: background-color, border-color, box-shadow;+ -ms-transition-duration: 150ms;+ -ms-transition-timing-function: ease;+ -o-transition-property: background-color, border-color, box-shadow;+ -o-transition-duration: 150ms;+ -o-transition-timing-function: ease;transition-property: background-color, border-color, box-shadow;transition-duration: 150ms;transition-timing-function: ease;}html[dir='ltr'] .toolbarButton,-html[dir='ltr'] .overlayButton,html[dir='ltr'] .dropdownToolbarButton {margin: 3px 2px 4px 0;}html[dir='rtl'] .toolbarButton,-html[dir='rtl'] .overlayButton,html[dir='rtl'] .dropdownToolbarButton {margin: 3px 0 4px 2px;}.toolbarButton:hover,.toolbarButton:focus,-.dropdownToolbarButton,-.overlayButton,-.secondaryToolbarButton:hover,-.secondaryToolbarButton:focus {+.dropdownToolbarButton {background-color: hsla(0,0%,0%,.12);background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));background-clip: padding-box;@@ -693,9 +667,7 @@ html[dir='rtl'] .dropdownToolbarButton {}.toolbarButton:hover:active,-.overlayButton:hover:active,-.dropdownToolbarButton:hover:active,-.secondaryToolbarButton:hover:active {+.dropdownToolbarButton:hover:active {background-color: hsla(0,0%,0%,.2);background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));border-color: hsla(0,0%,0%,.35) hsla(0,0%,0%,.4) hsla(0,0%,0%,.45);@@ -705,14 +677,22 @@ html[dir='rtl'] .dropdownToolbarButton {-webkit-transition-property: background-color, border-color, box-shadow;-webkit-transition-duration: 10ms;-webkit-transition-timing-function: linear;+ -moz-transition-property: background-color, border-color, box-shadow;+ -moz-transition-duration: 10ms;+ -moz-transition-timing-function: linear;+ -ms-transition-property: background-color, border-color, box-shadow;+ -ms-transition-duration: 10ms;+ -ms-transition-timing-function: linear;+ -o-transition-property: background-color, border-color, box-shadow;+ -o-transition-duration: 10ms;+ -o-transition-timing-function: linear;transition-property: background-color, border-color, box-shadow;transition-duration: 10ms;transition-timing-function: linear;}.toolbarButton.toggled,-.splitToolbarButton.toggled > .toolbarButton.toggled,-.secondaryToolbarButton.toggled {+.splitToolbarButton.toggled > .toolbarButton.toggled {background-color: hsla(0,0%,0%,.3);background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));border-color: hsla(0,0%,0%,.4) hsla(0,0%,0%,.45) hsla(0,0%,0%,.5);@@ -722,14 +702,22 @@ html[dir='rtl'] .dropdownToolbarButton {-webkit-transition-property: background-color, border-color, box-shadow;-webkit-transition-duration: 10ms;-webkit-transition-timing-function: linear;+ -moz-transition-property: background-color, border-color, box-shadow;+ -moz-transition-duration: 10ms;+ -moz-transition-timing-function: linear;+ -ms-transition-property: background-color, border-color, box-shadow;+ -ms-transition-duration: 10ms;+ -ms-transition-timing-function: linear;+ -o-transition-property: background-color, border-color, box-shadow;+ -o-transition-duration: 10ms;+ -o-transition-timing-function: linear;transition-property: background-color, border-color, box-shadow;transition-duration: 10ms;transition-timing-function: linear;}.toolbarButton.toggled:hover:active,-.splitToolbarButton.toggled > .toolbarButton.toggled:hover:active,-.secondaryToolbarButton.toggled:hover:active {+.splitToolbarButton.toggled > .toolbarButton.toggled:hover:active {background-color: hsla(0,0%,0%,.4);border-color: hsla(0,0%,0%,.4) hsla(0,0%,0%,.5) hsla(0,0%,0%,.55);box-shadow: 0 1px 1px hsla(0,0%,0%,.2) inset,@@ -767,12 +755,6 @@ html[dir='rtl'] .dropdownToolbarButton {background: hsl(0,0%,24%);}-.overlayButton {- margin: 3px 2px 4px 5px !important;- line-height: 16px;- padding: 2px 6px 3px 6px;-}-#customScaleOption {display: none;}@@ -806,6 +788,11 @@ html[dir='rtl'] .toolbarButton:first-child {min-width: 30px;}+.toolbarButton#sidebarToggle::before {+ display: inline-block;+ content: url(images/toolbarButton-sidebarToggle.png);+}+html[dir='ltr'] #findPrevious {margin-left: 3px;}@@ -819,211 +806,118 @@ html[dir='rtl'] #findPrevious {html[dir='rtl'] #findNext {margin-left: 3px;}--.toolbarButton::before,-.secondaryToolbarButton::before {+.toolbarButton::before {/* All matching images have a size of 16x16+ * (except for the print button: 18x16)* All relevant containers have a size of 32x25 */position: absolute;- display: inline-block;top: 4px;left: 7px;}-html[dir="ltr"] .secondaryToolbarButton::before {- left: 4px;-}-html[dir="rtl"] .secondaryToolbarButton::before {- right: 4px;-}--html[dir='ltr'] .toolbarButton#sidebarToggle::before {- content: url(images/toolbarButton-sidebarToggle.png);-}-html[dir='rtl'] .toolbarButton#sidebarToggle::before {- content: url(images/toolbarButton-sidebarToggle-rtl.png);-}--html[dir='ltr'] .toolbarButton#secondaryToolbarToggle::before {- content: url(images/toolbarButton-secondaryToolbarToggle.png);-}-html[dir='rtl'] .toolbarButton#secondaryToolbarToggle::before {- content: url(images/toolbarButton-secondaryToolbarToggle-rtl.png);-}-html[dir='ltr'] .toolbarButton.findPrevious::before {+ display: inline-block;content: url(images/findbarButton-previous.png);}+html[dir='rtl'] .toolbarButton.findPrevious::before {+ display: inline-block;content: url(images/findbarButton-previous-rtl.png);}html[dir='ltr'] .toolbarButton.findNext::before {+ display: inline-block;content: url(images/findbarButton-next.png);}+html[dir='rtl'] .toolbarButton.findNext::before {+ display: inline-block;content: url(images/findbarButton-next-rtl.png);}html[dir='ltr'] .toolbarButton.pageUp::before {+ display: inline-block;content: url(images/toolbarButton-pageUp.png);}+html[dir='rtl'] .toolbarButton.pageUp::before {+ display: inline-block;content: url(images/toolbarButton-pageUp-rtl.png);}html[dir='ltr'] .toolbarButton.pageDown::before {+ display: inline-block;content: url(images/toolbarButton-pageDown.png);}+html[dir='rtl'] .toolbarButton.pageDown::before {+ display: inline-block;content: url(images/toolbarButton-pageDown-rtl.png);}.toolbarButton.zoomOut::before {+ display: inline-block;content: url(images/toolbarButton-zoomOut.png);}.toolbarButton.zoomIn::before {+ display: inline-block;content: url(images/toolbarButton-zoomIn.png);}-.toolbarButton.presentationMode::before,-.secondaryToolbarButton.presentationMode::before {+.toolbarButton.presentationMode::before {+ display: inline-block;content: url(images/toolbarButton-presentationMode.png);}-.toolbarButton.print::before,-.secondaryToolbarButton.print::before {+.toolbarButton.print::before {+ display: inline-block;content: url(images/toolbarButton-print.png);+ left: 6px;}-.toolbarButton.openFile::before,-.secondaryToolbarButton.openFile::before {+.toolbarButton.openFile::before {+ display: inline-block;content: url(images/toolbarButton-openFile.png);}-.toolbarButton.download::before,-.secondaryToolbarButton.download::before {+.toolbarButton.download::before {+ display: inline-block;content: url(images/toolbarButton-download.png);}-.toolbarButton.bookmark,-.secondaryToolbarButton.bookmark {+.toolbarButton.bookmark {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;- outline: none;+ margin-top: 3px;padding-top: 4px;- text-decoration: none;-}-.secondaryToolbarButton.bookmark {- padding-top: 5px;}-.bookmark[href='#'] {+#viewBookmark[href='#'] {opacity: .5;pointer-events: none;}-.toolbarButton.bookmark::before,-.secondaryToolbarButton.bookmark::before {+.toolbarButton.bookmark::before {content: url(images/toolbarButton-bookmark.png);}#viewThumbnail.toolbarButton::before {+ display: inline-block;content: url(images/toolbarButton-viewThumbnail.png);}-html[dir="ltr"] #viewOutline.toolbarButton::before {+#viewOutline.toolbarButton::before {+ display: inline-block;content: url(images/toolbarButton-viewOutline.png);}-html[dir="rtl"] #viewOutline.toolbarButton::before {- content: url(images/toolbarButton-viewOutline-rtl.png);-}#viewFind.toolbarButton::before {+ display: inline-block;content: url(images/toolbarButton-search.png);}-.secondaryToolbarButton {- position: relative;- margin: 0 0 4px 0;- padding: 3px 0 1px 0;- height: auto;- min-height: 25px;- width: auto;- min-width: 100%;- white-space: normal;-}-html[dir="ltr"] .secondaryToolbarButton {- padding-left: 24px;- text-align: left;-}-html[dir="rtl"] .secondaryToolbarButton {- padding-right: 24px;- text-align: right;-}-html[dir="ltr"] .secondaryToolbarButton.bookmark {- padding-left: 27px;-}-html[dir="rtl"] .secondaryToolbarButton.bookmark {- padding-right: 27px;-}--html[dir="ltr"] .secondaryToolbarButton > span {- padding-right: 4px;-}-html[dir="rtl"] .secondaryToolbarButton > span {- padding-left: 4px;-}--.secondaryToolbarButton.firstPage::before {- content: url(images/secondaryToolbarButton-firstPage.png);-}--.secondaryToolbarButton.lastPage::before {- content: url(images/secondaryToolbarButton-lastPage.png);-}--.secondaryToolbarButton.rotateCcw::before {- content: url(images/secondaryToolbarButton-rotateCcw.png);-}--.secondaryToolbarButton.rotateCw::before {- content: url(images/secondaryToolbarButton-rotateCw.png);-}--.secondaryToolbarButton.handTool::before {- content: url(images/secondaryToolbarButton-handTool.png);-}--.secondaryToolbarButton.documentProperties::before {- content: url(images/secondaryToolbarButton-documentProperties.png);-}--.verticalToolbarSeparator {- display: block;- padding: 8px 0;- margin: 8px 4px;- width: 1px;- background-color: hsla(0,0%,0%,.5);- box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);-}-html[dir='ltr'] .verticalToolbarSeparator {- margin-left: 2px;-}-html[dir='rtl'] .verticalToolbarSeparator {- margin-right: 2px;-}--.horizontalToolbarSeparator {- display: block;- margin: 0 0 4px 0;- height: 1px;- width: 100%;- background-color: hsla(0,0%,0%,.5);- box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);-}.toolbarField {padding: 3px 6px;@@ -1041,9 +935,9 @@ html[dir='rtl'] .verticalToolbarSeparator {font-size: 12px;line-height: 14px;outline-style: none;- transition-property: background-color, border-color, box-shadow;- transition-duration: 150ms;- transition-timing-function: ease;+ -moz-transition-property: background-color, border-color, box-shadow;+ -moz-transition-duration: 150ms;+ -moz-transition-timing-function: ease;}.toolbarField[type=checkbox] {@@ -1052,7 +946,6 @@ html[dir='rtl'] .verticalToolbarSeparator {}.toolbarField.pageNumber {- -moz-appearance: textfield; /* hides the spinner in moz */min-width: 16px;text-align: right;width: 40px;@@ -1100,11 +993,6 @@ html[dir='rtl'] .verticalToolbarSeparator {.thumbnail {float: left;- margin-bottom: 5px;-}--#thumbnailView > a:last-of-type > .thumbnail {- margin-bottom: 10px;}.thumbnail:not([data-loaded]) {@@ -1113,7 +1001,7 @@ html[dir='rtl'] .verticalToolbarSeparator {}.thumbnailImage {- transition-duration: 150ms;+ -moz-transition-duration: 150ms;border: 1px solid transparent;box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5), 0 2px 8px rgba(0, 0, 0, 0.3);opacity: 0.8;@@ -1123,7 +1011,7 @@ html[dir='rtl'] .verticalToolbarSeparator {.thumbnailSelectionRing {border-radius: 2px;padding: 7px;- transition-duration: 150ms;+ -moz-transition-duration: 150ms;}a:focus > .thumbnail > .thumbnailSelectionRing > .thumbnailImage,@@ -1225,12 +1113,28 @@ html[dir='rtl'] .outlineItem > a {cursor: default;}+#findScrollView {+ position: absolute;+ top: 10px;+ bottom: 10px;+ left: 10px;+ width: 280px;+}++#sidebarControls {+ position:absolute;+ width: 180px;+ height: 32px;+ left: 15px;+ bottom: 35px;+}+.canvasWrapper {overflow: hidden;}canvas {- margin: 0;+ margin: auto;display: block;}@@ -1247,14 +1151,12 @@ canvas {background-color: white;}-.page > a,-.annotationLayer > a {+.page > a {display: block;position: absolute;}-.page > a:hover,-.annotationLayer > a:hover {+.page > a:hover {opacity: 0.2;background: #ff0;box-shadow: 0px 2px 10px #ff0;@@ -1335,6 +1237,7 @@ canvas {}.annotText > img:hover {+ cursor: pointer;opacity: 1;}@@ -1354,9 +1257,6 @@ canvas {padding: 3px;font-size: 0.8em;}-.loadingInProgress #errorWrapper {- top: 39px;-}#errorMessageLeft {float: left;@@ -1374,127 +1274,6 @@ canvas {width: 98%;}-#overlayContainer {- display: table;- position: absolute;- width: 100%;- height: 100%;- background-color: hsla(0,0%,0%,.2);- z-index: 10000;-}--#promptContainer {- display: table-cell;- vertical-align: middle;- text-align: center;-}--#promptContainer > * {- display: inline-block;-}--.prompt {- display: table;- padding: 15px;- border-spacing: 4px;- color: hsl(0,0%,85%);- line-height: 14px;- text-align: center;- background-color: #474747; /* fallback */- background-image: url(images/texture.png),- linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));- box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),- inset 0 1px 1px hsla(0,0%,0%,.15),- inset 0 -1px 0 hsla(0,0%,100%,.05),- 0 1px 0 hsla(0,0%,0%,.15),- 0 1px 1px hsla(0,0%,0%,.1);-}--.prompt > .row {- display: table-row;-}--.prompt > .row > * {- display: table-cell;-}--.prompt .toolbarField {- margin: 5px 0;- width: 200px;-}--.prompt .toolbarField:hover,-.prompt .toolbarField:focus {- border-color: hsla(0,0%,0%,.32) hsla(0,0%,0%,.38) hsla(0,0%,0%,.42);-}--#documentPropertiesContainer {- display: table-cell;- vertical-align: middle;- text-align: center;-}--#documentPropertiesContainer > * {- display: inline-block;- padding: 15px;- border-spacing: 4px;- max-width: 350px;- max-height: 350px;- color: hsl(0,0%,85%);- font-size: 12px;- line-height: 14px;- text-align: left;- cursor: default;- background-color: #474747; /* fallback */- background-image: url(images/texture.png),- linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));- box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),- inset 0 1px 1px hsla(0,0%,0%,.15),- inset 0 -1px 0 hsla(0,0%,100%,.05),- 0 1px 0 hsla(0,0%,0%,.15),- 0 1px 1px hsla(0,0%,0%,.1);-}--#documentPropertiesContainer .separator {- display: block;- margin: 4px 0 4px 0;- height: 1px;- width: 100%;- background-color: hsla(0,0%,0%,.5);- box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);-}--#documentPropertiesContainer .row {- display: table-row;-}--html[dir='ltr'] #documentPropertiesContainer .row > * {- display: table-cell;- min-width: 100px;-}--html[dir='rtl'] #documentPropertiesContainer .row > * {- display: table-cell;- min-width: 100px;- text-align: right;-}--#documentPropertiesContainer .row span {- width: 125px;- word-wrap: break-word;-}--#documentPropertiesContainer .row p {- max-width: 225px;- word-wrap: break-word;-}--#documentPropertiesContainer .buttonRow {- margin-top: 10px;- text-align: center;- vertical-align: middle;-}-.clearBoth {clear: both;}@@ -1503,10 +1282,6 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {background: white;color: black;margin-top: 5px;- visibility: hidden;- position: fixed;- right: 0;- top: 0;}#PDFBug {@@ -1568,33 +1343,6 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {color: black;}-.grab-to-pan-grab {- cursor: url("images/grab.cur"), move !important;- cursor: -webkit-grab !important;- cursor: -moz-grab !important;- cursor: grab !important;-}-.grab-to-pan-grab *:not(input):not(textarea):not(button):not(select):not(:link) {- cursor: inherit !important;-}-.grab-to-pan-grab:active,-.grab-to-pan-grabbing {- cursor: url("images/grabbing.cur"), move !important;- cursor: -webkit-grabbing !important;- cursor: -moz-grabbing !important;- cursor: grabbing !important;-- position: fixed;- background: transparent;- display: block;- top: 0;- left: 0;- right: 0;- bottom: 0;- overflow: hidden;- z-index: 50000; /* should be higher than anything else in PDF.js! */-}-@page {margin: 0;}@@ -1603,151 +1351,6 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {display: none;}-@media screen and (min-resolution: 2dppx) {- /* Rules for Retina screens */- .toolbarButton::before {- transform: scale(0.5);- -webkit-transform: scale(0.5);- top: -5px;- }-- .secondaryToolbarButton::before {- transform: scale(0.5);- top: -4px;- }-- html[dir='ltr'] .toolbarButton::before,- html[dir='rtl'] .toolbarButton::before {- left: -1px;- }-- html[dir='ltr'] .secondaryToolbarButton::before {- left: -2px;- }- html[dir='rtl'] .secondaryToolbarButton::before {- left: 186px;- }-- .dropdownToolbarButton {- background: url(images/[email protected]) no-repeat;- background-size: 7px 16px;- }-- html[dir='ltr'] .toolbarButton#sidebarToggle::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton#sidebarToggle::before {- content: url(images/[email protected]);- }-- html[dir='ltr'] .toolbarButton#secondaryToolbarToggle::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton#secondaryToolbarToggle::before {- content: url(images/[email protected]);- }-- html[dir='ltr'] .toolbarButton.findPrevious::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton.findPrevious::before {- content: url(images/[email protected]);- }-- html[dir='ltr'] .toolbarButton.findNext::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton.findNext::before {- content: url(images/[email protected]);- }-- html[dir='ltr'] .toolbarButton.pageUp::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton.pageUp::before {- content: url(images/[email protected]);- }-- html[dir='ltr'] .toolbarButton.pageDown::before {- content: url(images/[email protected]);- }- html[dir='rtl'] .toolbarButton.pageDown::before {- content: url(images/[email protected]);- }-- .toolbarButton.zoomIn::before {- content: url(images/[email protected]);- }-- .toolbarButton.zoomOut::before {- content: url(images/[email protected]);- }-- .toolbarButton.presentationMode::before,- .secondaryToolbarButton.presentationMode::before {- content: url(images/[email protected]);- }-- .toolbarButton.print::before,- .secondaryToolbarButton.print::before {- content: url(images/[email protected]);- }-- .toolbarButton.openFile::before,- .secondaryToolbarButton.openFile::before {- content: url(images/[email protected]);- }-- .toolbarButton.download::before,- .secondaryToolbarButton.download::before {- content: url(images/[email protected]);- }-- .toolbarButton.bookmark::before,- .secondaryToolbarButton.bookmark::before {- content: url(images/[email protected]);- }-- #viewThumbnail.toolbarButton::before {- content: url(images/[email protected]);- }-- html[dir="ltr"] #viewOutline.toolbarButton::before {- content: url(images/[email protected]);- }- html[dir="rtl"] #viewOutline.toolbarButton::before {- content: url(images/[email protected]);- }-- #viewFind.toolbarButton::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.firstPage::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.lastPage::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.rotateCcw::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.rotateCw::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.handTool::before {- content: url(images/[email protected]);- }-- .secondaryToolbarButton.documentProperties::before {- content: url(images/[email protected]);- }-}-@media print {/* General rules for printing. */body {@@ -1755,12 +1358,9 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {}/* Rules for browsers that don't support mozPrintCallback. */- #sidebarContainer, #secondaryToolbar, .toolbar, #loadingBox, #errorWrapper, .textLayer {+ #sidebarContainer, .toolbar, #loadingBox, #errorWrapper, .textLayer {display: none;}- #viewerContainer {- overflow: visible;- }#mainContainer, #viewerContainer, .page, .page canvas {position: static;@@ -1771,7 +1371,6 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {.page {float: left;display: none;- border: none;box-shadow: none;}@@ -1779,10 +1378,6 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {display: block;}- .fileInput {- display: none;- }-/* Rules for browsers that support mozPrintCallback */body[data-mozPrintCallback] #outerContainer {display: none;@@ -1797,40 +1392,16 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {}}-.visibleLargeView,-.visibleMediumView,-.visibleSmallView {- display: none;-}--@media all and (max-width: 960px) {+@media all and (max-width: 950px) {html[dir='ltr'] #outerContainer.sidebarMoving .outerCenter,html[dir='ltr'] #outerContainer.sidebarOpen .outerCenter {float: left;- left: 205px;+ left: 180px;}html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter {float: right;- right: 205px;- }-}--@media all and (max-width: 900px) {- .sidebarOpen .hiddenLargeView {- display: none;- }- .sidebarOpen .visibleLargeView {- display: inherit;- }-}--@media all and (max-width: 860px) {- .sidebarOpen .hiddenMediumView {- display: none;- }- .sidebarOpen .visibleMediumView {- display: inherit;+ right: 180px;}}@@ -1856,38 +1427,11 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {html[dir='ltr'] .outerCenter {float: left;- left: 205px;+ left: 180px;}html[dir='rtl'] .outerCenter {float: right;- right: 205px;- }-- #outerContainer .hiddenLargeView,- #outerContainer .hiddenMediumView {- display: inherit;- }- #outerContainer .visibleLargeView,- #outerContainer .visibleMediumView {- display: none;- }-}--@media all and (max-width: 700px) {- #outerContainer .hiddenLargeView {- display: none;- }- #outerContainer .visibleLargeView {- display: inherit;- }-}--@media all and (max-width: 660px) {- #outerContainer .hiddenMediumView {- display: none;- }- #outerContainer .visibleMediumView {- display: inherit;+ right: 180px;}}@@ -1895,17 +1439,10 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {.hiddenSmallView {display: none;}- .visibleSmallView {- display: inherit;- }- html[dir='ltr'] #outerContainer.sidebarMoving .outerCenter,- html[dir='ltr'] #outerContainer.sidebarOpen .outerCenter,html[dir='ltr'] .outerCenter {left: 156px;}- html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,- html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter,- html[dir='rtl'] .outerCenter {+ html[dir='rtr'] .outerCenter {right: 156px;}.toolbarButtonSpacer {@@ -1913,7 +1450,7 @@ html[dir='rtl'] #documentPropertiesContainer .row > * {}}-@media all and (max-width: 510px) {+@media all and (max-width: 500px) {#scaleSelectContainer, #pageNumberLabel {display: none;}diff --git a/data/ext/viewerPDF/pdfjs/web/viewer.js b/data/ext/viewerPDF/viewer.jssimilarity index 54%rename from data/ext/viewerPDF/pdfjs/web/viewer.jsrename to data/ext/viewerPDF/viewer.jsindex 93d970129..d9b56e40e 100644--- a/data/ext/viewerPDF/pdfjs/web/viewer.js+++ b/data/ext/viewerPDF/viewer.js@@ -14,16 +14,13 @@* See the License for the specific language governing permissions and* limitations under the License.*/-/* globals PDFJS, PDFBug, FirefoxCom, Stats, Cache, PDFFindBar, CustomStyle,- PDFFindController, ProgressBar, TextLayerBuilder, DownloadManager,- getFileName, scrollIntoView, getPDFFileNameFromURL, PDFHistory,- Preferences, ViewHistory, PageView, ThumbnailView, URL,- noContextMenuHandler, SecondaryToolbar, PasswordPrompt,- PresentationMode, HandTool, Promise, DocumentProperties */+/* globals PDFJS, PDFBug, FirefoxCom, Stats, Cache, PDFFindBar */+/* globals PDFFindController, ProgressBar, getFileName, CustomStyle */+/* globals getOutputScale, TextLayerBuilder */'use strict';-//var DEFAULT_URL = 'compressed.tracemonkey-pldi-09.pdf';+//var DEFAULT_URL = 'test.pdf';var DEFAULT_SCALE = 'auto';var DEFAULT_SCALE_DELTA = 1.1;var UNKNOWN_SCALE = 0;@@ -31,16 +28,11 @@ var CACHE_SIZE = 20;var CSS_UNITS = 96.0 / 72.0;var SCROLLBAR_PADDING = 40;var VERTICAL_PADDING = 5;-var MAX_AUTO_SCALE = 1.25;var MIN_SCALE = 0.25;var MAX_SCALE = 4.0;-var VIEW_HISTORY_MEMORY = 20;+var SETTINGS_MEMORY = 20;var SCALE_SELECT_CONTAINER_PADDING = 8;var SCALE_SELECT_PADDING = 22;-var THUMBNAIL_SCROLL_MARGIN = -19;-var USE_ONLY_CSS_ZOOM = false;-var CLEANUP_TIMEOUT = 30000;-var IGNORE_CURRENT_POSITION_ON_ZOOM = false;var RenderingStates = {INITIAL: 0,RUNNING: 1,@@ -54,8 +46,7 @@ var FindStates = {FIND_PENDING: 3};-PDFJS.imageResourcesPath = './images/';- PDFJS.workerSrc = '../build/pdf.worker.js';+ PDFJS.workerSrc = 'pdf.js';var mozL10n = document.mozL10n || document.webL10n;@@ -126,14 +117,8 @@ function getFileName(url) {scales. The scaled property is set to false if scaling isnot required, true otherwise.*/-function getOutputScale(ctx) {- var devicePixelRatio = window.devicePixelRatio || 1;- var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||- ctx.mozBackingStorePixelRatio ||- ctx.msBackingStorePixelRatio ||- ctx.oBackingStorePixelRatio ||- ctx.backingStorePixelRatio || 1;- var pixelRatio = devicePixelRatio / backingStoreRatio;+function getOutputScale() {+ var pixelRatio = 'devicePixelRatio' in window ? window.devicePixelRatio : 1;return {sx: pixelRatio,sy: pixelRatio,@@ -141,83 +126,6 @@ function getOutputScale(ctx) {};}-/**- * Scrolls specified element into view of its parent.- * element {Object} The element to be visible.- * spot {Object} An object with optional top and left properties,- * specifying the offset from the top left edge.- */-function scrollIntoView(element, spot) {- // Assuming offsetParent is available (it's not available when viewer is in- // hidden iframe or object). We have to scroll: if the offsetParent is not set- // producing the error. See also animationStartedClosure.- var parent = element.offsetParent;- var offsetY = element.offsetTop + element.clientTop;- var offsetX = element.offsetLeft + element.clientLeft;- if (!parent) {- console.error('offsetParent is not set -- cannot scroll');- return;- }- while (parent.clientHeight === parent.scrollHeight) {- if (parent.dataset._scaleY) {- offsetY /= parent.dataset._scaleY;- offsetX /= parent.dataset._scaleX;- }- offsetY += parent.offsetTop;- offsetX += parent.offsetLeft;- parent = parent.offsetParent;- if (!parent) {- return; // no need to scroll- }- }- if (spot) {- if (spot.top !== undefined) {- offsetY += spot.top;- }- if (spot.left !== undefined) {- offsetX += spot.left;- parent.scrollLeft = offsetX;- }- }- parent.scrollTop = offsetY;-}--/**- * Event handler to suppress context menu.- */-function noContextMenuHandler(e) {- e.preventDefault();-}--/**- * Returns the filename or guessed filename from the url (see issue 3455).- * url {String} The original PDF location.- * @return {String} Guessed PDF file name.- */-function getPDFFileNameFromURL(url) {- var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;- // SCHEME HOST 1.PATH 2.QUERY 3.REF- // Pattern to get last matching NAME.pdf- var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;- var splitURI = reURI.exec(url);- var suggestedFilename = reFilename.exec(splitURI[1]) ||- reFilename.exec(splitURI[2]) ||- reFilename.exec(splitURI[3]);- if (suggestedFilename) {- suggestedFilename = suggestedFilename[0];- if (suggestedFilename.indexOf('%') != -1) {- // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf- try {- suggestedFilename =- reFilename.exec(decodeURIComponent(suggestedFilename))[0];- } catch(e) { // Possible (extremely rare) errors:- // URIError "Malformed URI", e.g. for "%AA.pdf"- // TypeError "null has no properties", e.g. for "%2F.pdf"- }- }- }- return suggestedFilename || 'document.pdf';-}var ProgressBar = (function ProgressBarClosure() {@@ -227,18 +135,15 @@ var ProgressBar = (function ProgressBarClosure() {function ProgressBar(id, opts) {- // Fetch the sub-elements for later.+ // Fetch the sub-elements for laterthis.div = document.querySelector(id + ' .progress');- // Get the loading bar element, so it can be resized to fit the viewer.- this.bar = this.div.parentNode;-- // Get options, with sensible defaults.+ // Get options, with sensible defaultsthis.height = opts.height || 100;this.width = opts.width || 100;this.units = opts.units || '%';- // Initialize heights.+ // Initialize heightsthis.div.style.height = this.height + this.units;this.percent = 0;}@@ -265,22 +170,6 @@ var ProgressBar = (function ProgressBarClosure() {this._indeterminate = isNaN(val);this._percent = clamp(val, 0, 100);this.updateBar();- },-- setWidth: function ProgressBar_setWidth(viewer) {- if (viewer) {- var container = viewer.parentNode;- var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;- if (scrollbarWidth > 0) {- this.bar.setAttribute('style', 'width: calc(100% - ' +- scrollbarWidth + 'px);');- }- }- },-- hide: function ProgressBar_hide() {- this.bar.classList.add('hidden');- this.bar.removeAttribute('style');}};@@ -299,411 +188,114 @@ var Cache = function cacheCache(size) {};};-var isLocalStorageEnabled = (function isLocalStorageEnabledClosure() {- // Feature test as per http://diveintohtml5.info/storage.html- // The additional localStorage call is to get around a FF quirk, see- // bug #495747 in bugzilla- try {- return ('localStorage' in window && window['localStorage'] !== null &&- localStorage);- } catch (e) {- return false;- }-})();----var EXPORTED_SYMBOLS = ['DEFAULT_PREFERENCES'];--var DEFAULT_PREFERENCES = {- showPreviousViewOnLoad: true,- defaultZoomValue: '',- ifAvailableShowOutlineOnLoad: false-};---var Preferences = (function PreferencesClosure() {- function Preferences() {- this.prefs = {};- this.isInitializedPromiseResolved = false;- this.initializedPromise = this.readFromStorage().then(function(prefObj) {- this.isInitializedPromiseResolved = true;- if (prefObj) {- this.prefs = prefObj;- }- }.bind(this));- }-- Preferences.prototype = {- writeToStorage: function Preferences_writeToStorage(prefObj) {- return;- },-- readFromStorage: function Preferences_readFromStorage() {- var readFromStoragePromise = Promise.resolve();- return readFromStoragePromise;- },-- reset: function Preferences_reset() {- if (this.isInitializedPromiseResolved) {- this.prefs = {};- this.writeToStorage(this.prefs);- }- },-- set: function Preferences_set(name, value) {- if (!this.isInitializedPromiseResolved) {- return;- } else if (DEFAULT_PREFERENCES[name] === undefined) {- console.error('Preferences_set: \'' + name + '\' is undefined.');- return;- } else if (value === undefined) {- console.error('Preferences_set: no value is specified.');- return;- }- var valueType = typeof value;- var defaultType = typeof DEFAULT_PREFERENCES[name];-- if (valueType !== defaultType) {- if (valueType === 'number' && defaultType === 'string') {- value = value.toString();- } else {- console.error('Preferences_set: \'' + value + '\' is a \"' +- valueType + '\", expected a \"' + defaultType + '\".');- return;- }- }- this.prefs[name] = value;- this.writeToStorage(this.prefs);- },-- get: function Preferences_get(name) {- var defaultPref = DEFAULT_PREFERENCES[name];-- if (defaultPref === undefined) {- console.error('Preferences_get: \'' + name + '\' is undefined.');- return;- } else if (this.isInitializedPromiseResolved) {- var pref = this.prefs[name];-- if (pref !== undefined) {- return pref;- }- }- return defaultPref;- }- };-- return Preferences;-})();---Preferences.prototype.writeToStorage = function(prefObj) {- if (isLocalStorageEnabled) {- localStorage.setItem('preferences', JSON.stringify(prefObj));- }-};--Preferences.prototype.readFromStorage = function() {- var readFromStoragePromise = new Promise(function (resolve) {- if (isLocalStorageEnabled) {- var readPrefs = JSON.parse(localStorage.getItem('preferences'));- resolve(readPrefs);- }- });- return readFromStoragePromise;-};-(function mozPrintCallbackPolyfillClosure() {- if ('mozPrintCallback' in document.createElement('canvas')) {+function scrollIntoView(element, spot) {+ // Assuming offsetParent is available (it's not available when viewer is in+ // hidden iframe or object). We have to scroll: if the offsetParent is not set+ // producing the error. See also animationStartedClosure.+ var parent = element.offsetParent;+ var offsetY = element.offsetTop + element.clientTop;+ if (!parent) {+ console.error('offsetParent is not set -- cannot scroll');return;}- // Cause positive result on feature-detection:- HTMLCanvasElement.prototype.mozPrintCallback = undefined;-- var canvases; // During print task: non-live NodeList of <canvas> elements- var index; // Index of <canvas> element that is being processed-- var print = window.print;- window.print = function print() {- if (canvases) {- console.warn('Ignored window.print() because of a pending print job.');- return;- }- try {- dispatchEvent('beforeprint');- } finally {- canvases = document.querySelectorAll('canvas');- index = -1;- next();- }- };-- function dispatchEvent(eventType) {- var event = document.createEvent('CustomEvent');- event.initCustomEvent(eventType, false, false, 'custom');- window.dispatchEvent(event);- }-- function next() {- if (!canvases) {- return; // Print task cancelled by user (state reset in abort())- }-- renderProgress();- if (++index < canvases.length) {- var canvas = canvases[index];- if (typeof canvas.mozPrintCallback === 'function') {- canvas.mozPrintCallback({- context: canvas.getContext('2d'),- abort: abort,- done: next- });- } else {- next();- }- } else {- renderProgress();- print.call(window);- setTimeout(abort, 20); // Tidy-up- }- }-- function abort() {- if (canvases) {- canvases = null;- renderProgress();- dispatchEvent('afterprint');- }- }-- function renderProgress() {- var progressContainer = document.getElementById('mozPrintCallback-shim');- if (canvases) {- var progress = Math.round(100 * index / canvases.length);- var progressBar = progressContainer.querySelector('progress');- var progressPerc = progressContainer.querySelector('.relative-progress');- progressBar.value = progress;- progressPerc.textContent = progress + '%';- progressContainer.removeAttribute('hidden');- progressContainer.onclick = abort;- } else {- progressContainer.setAttribute('hidden', '');- }- }-- var hasAttachEvent = !!document.attachEvent;-- window.addEventListener('keydown', function(event) {- // Intercept Cmd/Ctrl + P in all browsers.- // Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera- if (event.keyCode === 80/*P*/ && (event.ctrlKey || event.metaKey) &&- !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {- window.print();- if (hasAttachEvent) {- // Only attachEvent can cancel Ctrl + P dialog in IE <=10- // attachEvent is gone in IE11, so the dialog will re-appear in IE11.- return;- }- event.preventDefault();- if (event.stopImmediatePropagation) {- event.stopImmediatePropagation();- } else {- event.stopPropagation();- }- return;- }- if (event.keyCode === 27 && canvases) { // Esc- abort();- }- }, true);- if (hasAttachEvent) {- document.attachEvent('onkeydown', function(event) {- event = event || window.event;- if (event.keyCode === 80/*P*/ && event.ctrlKey) {- event.keyCode = 0;- return false;- }- });- }-- if ('onbeforeprint' in window) {- // Do not propagate before/afterprint events when they are not triggered- // from within this polyfill. (FF/IE).- var stopPropagationIfNeeded = function(event) {- if (event.detail !== 'custom' && event.stopImmediatePropagation) {- event.stopImmediatePropagation();- }- };- window.addEventListener('beforeprint', stopPropagationIfNeeded, false);- window.addEventListener('afterprint', stopPropagationIfNeeded, false);- }-})();----var DownloadManager = (function DownloadManagerClosure() {-- function download(blobUrl, filename) {- var a = document.createElement('a');- if (a.click) {- // Use a.click() if available. Otherwise, Chrome might show- // "Unsafe JavaScript attempt to initiate a navigation change- // for frame with URL" and not open the PDF at all.- // Supported by (not mentioned = untested):- // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)- // - Chrome 19 - 26 (18- does not support a.click)- // - Opera 9 - 12.15- // - Internet Explorer 6 - 10- // - Safari 6 (5.1- does not support a.click)- a.href = blobUrl;- a.target = '_parent';- // Use a.download if available. This increases the likelihood that- // the file is downloaded instead of opened by another PDF plugin.- if ('download' in a) {- a.download = filename;- }- // <a> must be in the document for IE and recent Firefox versions.- // (otherwise .click() is ignored)- (document.body || document.documentElement).appendChild(a);- a.click();- a.parentNode.removeChild(a);- } else {- if (window.top === window &&- blobUrl.split('#')[0] === window.location.href.split('#')[0]) {- // If _parent == self, then opening an identical URL with different- // location hash will only cause a navigation, not a download.- var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';- blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');- }- window.open(blobUrl, '_parent');- }+ while (parent.clientHeight == parent.scrollHeight) {+ offsetY += parent.offsetTop;+ parent = parent.offsetParent;+ if (!parent)+ return; // no need to scroll}+ if (spot)+ offsetY += spot.top;+ parent.scrollTop = offsetY;+}- function DownloadManager() {}-- DownloadManager.prototype = {- downloadUrl: function DownloadManager_downloadUrl(url, filename) {- if (!PDFJS.isValidUrl(url, true)) {- return; // restricted/invalid URL- }-- download(url + '#pdfjs.action=download', filename);- },-- download: function DownloadManager_download(blob, url, filename) {- if (!URL) {- // URL.createObjectURL is not supported- this.downloadUrl(url, filename);- return;- }- if (navigator.msSaveBlob) {- // IE10 / IE11- if (!navigator.msSaveBlob(blob, filename)) {- this.downloadUrl(url, filename);- }- return;- }- var blobUrl = URL.createObjectURL(blob);- download(blobUrl, filename);+// Settings Manager - This is a utility for saving settings+// First we see if localStorage is available+// If not, we use FUEL in FF+// Use asyncStorage for B2G+var Settings = (function SettingsClosure() {+ var isLocalStorageEnabled = (function localStorageEnabledTest() {+ // Feature test as per http://diveintohtml5.info/storage.html+ // The additional localStorage call is to get around a FF quirk, see+ // bug #495747 in bugzilla+ try {+ return 'localStorage' in window && window['localStorage'] !== null &&+ localStorage;+ } catch (e) {+ return false;}- };+ })();- return DownloadManager;-})();-----var cache = new Cache(CACHE_SIZE);-var currentPageNumber = 1;---/**- * View History - This is a utility for saving various view parameters for- * recently opened files.- *- * The way that the view parameters are stored depends on how PDF.js is built,- * for 'node make <flag>' the following cases exist:- * - FIREFOX or MOZCENTRAL - uses about:config.- * - B2G - uses asyncStorage.- * - GENERIC or CHROME - uses localStorage, if it is available.- */-var ViewHistory = (function ViewHistoryClosure() {- function ViewHistory(fingerprint) {+ function Settings(fingerprint) {this.fingerprint = fingerprint;- var initializedPromiseResolve;- this.isInitializedPromiseResolved = false;- this.initializedPromise = new Promise(function (resolve) {- initializedPromiseResolve = resolve;- });+ this.initializedPromise = new PDFJS.Promise();- var resolvePromise = (function ViewHistoryResolvePromise(db) {- this.isInitializedPromiseResolved = true;+ var resolvePromise = (function settingsResolvePromise(db) {this.initialize(db || '{}');- initializedPromiseResolve();+ this.initializedPromise.resolve();}).bind(this);- if (isLocalStorageEnabled) {+ if (isLocalStorageEnabled)resolvePromise(localStorage.getItem('database'));- }}- ViewHistory.prototype = {- initialize: function ViewHistory_initialize(database) {+ Settings.prototype = {+ initialize: function settingsInitialize(database) {database = JSON.parse(database);- if (!('files' in database)) {+ if (!('files' in database))database.files = [];- }- if (database.files.length >= VIEW_HISTORY_MEMORY) {+ if (database.files.length >= SETTINGS_MEMORY)database.files.shift();- }var index;for (var i = 0, length = database.files.length; i < length; i++) {var branch = database.files[i];- if (branch.fingerprint === this.fingerprint) {+ if (branch.fingerprint == this.fingerprint) {index = i;break;}}- if (typeof index !== 'number') {+ if (typeof index != 'number')index = database.files.push({fingerprint: this.fingerprint}) - 1;- }this.file = database.files[index];this.database = database;},- set: function ViewHistory_set(name, val) {- if (!this.isInitializedPromiseResolved) {+ set: function settingsSet(name, val) {+ if (!this.initializedPromise.isResolved)return;- }+var file = this.file;file[name] = val;var database = JSON.stringify(this.database);- if (isLocalStorageEnabled) {+ if (isLocalStorageEnabled)localStorage.setItem('database', database);- }},- get: function ViewHistory_get(name, defaultValue) {- if (!this.isInitializedPromiseResolved) {+ get: function settingsGet(name, defaultValue) {+ if (!this.initializedPromise.isResolved)return defaultValue;- }+return this.file[name] || defaultValue;}};- return ViewHistory;+ return Settings;})();+var cache = new Cache(CACHE_SIZE);+var currentPageNumber = 1;++// TODO: Enable the FindBar *AFTER* the pagesPromise in the load function+// got resolved/* globals PDFFindController, FindStates, mozL10n */@@ -833,12 +425,11 @@ var PDFFindBar = {},open: function() {- if (!this.opened) {- this.opened = true;- this.toggleButton.classList.add('toggled');- this.bar.classList.remove('hidden');- }+ if (this.opened) return;+ this.opened = true;+ this.toggleButton.classList.add('toggled');+ this.bar.classList.remove('hidden');this.findField.select();this.findField.focus();},@@ -864,7 +455,7 @@ var PDFFindBar = {-/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom, Promise */+/* globals PDFFindBar, PDFJS, FindStates, FirefoxCom *//*** Provides a "search" or "find" functionality for the PDF.@@ -900,6 +491,8 @@ var PDFFindController = {resumePageIdx: null,+ resumeCallback: null,+state: null,dirtyMatch: false,@@ -912,7 +505,7 @@ var PDFFindController = {initialize: function(options) {if(typeof PDFFindBar === 'undefined' || PDFFindBar === null) {- throw 'PDFFindController cannot be initialized ' ++ throw 'PDFFindController cannot be initialized ' +'without a PDFFindController instance';}@@ -926,9 +519,6 @@ var PDFFindController = {'findcasesensitivitychange'];- this.firstPagePromise = new Promise(function (resolve) {- this.resolveFirstPage = resolve;- }.bind(this));this.handleEvent = this.handleEvent.bind(this);for (var i = 0; i < events.length; i++) {@@ -936,12 +526,6 @@ var PDFFindController = {}},- reset: function pdfFindControllerReset() {- this.startedTextExtraction = false;- this.extractTextPromises = [];- this.active = false;- },-calcFindMatch: function(pageIndex) {var pageContent = this.pageContents[pageIndex];var query = this.state.query;@@ -972,8 +556,10 @@ var PDFFindController = {this.pageMatches[pageIndex] = matches;this.updatePage(pageIndex);if (this.resumePageIdx === pageIndex) {+ var callback = this.resumeCallback;this.resumePageIdx = null;- this.nextPageMatch();+ this.resumeCallback = null;+ callback();}},@@ -984,17 +570,16 @@ var PDFFindController = {this.startedTextExtraction = true;this.pageContents = [];- var extractTextPromisesResolves = [];for (var i = 0, ii = this.pdfPageSource.pdfDocument.numPages; i < ii; i++) {- this.extractTextPromises.push(new Promise(function (resolve) {- extractTextPromisesResolves.push(resolve);- }));+ this.extractTextPromises.push(new PDFJS.Promise());}var self = this;function extractPageText(pageIndex) {self.pdfPageSource.pages[pageIndex].getTextContent().then(- function textContentResolved(bidiTexts) {+ function textContentResolved(data) {+ // Build the find string.+ var bidiTexts = data.bidiTexts;var str = '';for (var i = 0; i < bidiTexts.length; i++) {@@ -1004,7 +589,7 @@ var PDFFindController = {// Store the pageContent as a string.self.pageContents.push(str);- extractTextPromisesResolves[pageIndex](pageIndex);+ self.extractTextPromises[pageIndex].resolve(pageIndex);if ((pageIndex + 1) < self.pdfPageSource.pages.length)extractPageText(pageIndex + 1);}@@ -1020,17 +605,15 @@ var PDFFindController = {this.state = e.detail;this.updateUIState(FindStates.FIND_PENDING);- this.firstPagePromise.then(function() {- this.extractText();+ this.extractText();- clearTimeout(this.findTimeout);- if (e.type === 'find') {- // Only trigger the find action after 250ms of silence.- this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);- } else {- this.nextMatch();- }- }.bind(this));+ clearTimeout(this.findTimeout);+ if (e.type === 'find') {+ // Only trigger the find action after 250ms of silence.+ this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);+ } else {+ this.nextMatch();+ }},updatePage: function(idx) {@@ -1049,8 +632,8 @@ var PDFFindController = {},nextMatch: function() {+ var pages = this.pdfPageSource.pages;var previous = this.state.findPrevious;- var currentPageIndex = this.pdfPageSource.page - 1;var numPages = this.pdfPageSource.pages.length;this.active = true;@@ -1059,9 +642,10 @@ var PDFFindController = {// Need to recalculate the matches, reset everything.this.dirtyMatch = false;this.selected.pageIdx = this.selected.matchIdx = -1;- this.offset.pageIdx = currentPageIndex;+ this.offset.pageIdx = previous ? numPages - 1 : 0;this.offset.matchIdx = null;this.hadMatch = false;+ this.resumeCallback = null;this.resumePageIdx = null;this.pageMatches = [];var self = this;@@ -1088,7 +672,7 @@ var PDFFindController = {}// If we're waiting on a page, we return since we can't do anything else.- if (this.resumePageIdx) {+ if (this.resumeCallback) {return;}@@ -1114,49 +698,48 @@ var PDFFindController = {this.nextPageMatch();},- matchesReady: function(matches) {- var offset = this.offset;- var numMatches = matches.length;- var previous = this.state.findPrevious;- if (numMatches) {- // There were matches for the page, so initialize the matchIdx.- this.hadMatch = true;- offset.matchIdx = previous ? numMatches - 1 : 0;- this.updateMatch(true);- // matches were found- return true;- } else {- // No matches attempt to search the next page.- this.advanceOffsetPage(previous);- if (offset.wrapped) {- offset.matchIdx = null;- if (!this.hadMatch) {- // No point in wrapping there were no matches.- this.updateMatch(false);- // while matches were not found, searching for a page- // with matches should nevertheless halt.- return true;- }- }- // matches were not found (and searching is not done)- return false;- }- },-nextPageMatch: function() {- if (this.resumePageIdx !== null) {+ if (this.resumePageIdx !== null)console.error('There can only be one pending page.');++ var matchesReady = function(matches) {+ var offset = this.offset;+ var numMatches = matches.length;+ var previous = this.state.findPrevious;+ if (numMatches) {+ // There were matches for the page, so initialize the matchIdx.+ this.hadMatch = true;+ offset.matchIdx = previous ? numMatches - 1 : 0;+ this.updateMatch(true);+ } else {+ // No matches attempt to search the next page.+ this.advanceOffsetPage(previous);+ if (offset.wrapped) {+ offset.matchIdx = null;+ if (!this.hadMatch) {+ // No point in wrapping there were no matches.+ this.updateMatch(false);+ return;+ }+ }+ // Search the next page.+ this.nextPageMatch();+ }+ }.bind(this);++ var pageIdx = this.offset.pageIdx;+ var pageMatches = this.pageMatches;+ if (!pageMatches[pageIdx]) {+ // The matches aren't ready setup a callback so we can be notified,+ // when they are ready.+ this.resumeCallback = function() {+ matchesReady(pageMatches[pageIdx]);+ };+ this.resumePageIdx = pageIdx;+ return;}- do {- var pageIdx = this.offset.pageIdx;- var matches = this.pageMatches[pageIdx];- if (!matches) {- // The matches don't exist yet for processing by "matchesReady",- // so set a resume point for when they do exist.- this.resumePageIdx = pageIdx;- break;- }- } while (!this.matchesReady(matches));+ // The matches are finished already.+ matchesReady(pageMatches[pageIdx]);},advanceOffsetPage: function(previous) {@@ -1208,9 +791,9 @@ var PDFHistory = {initialDestination: null,initialize: function pdfHistoryInitialize(fingerprint) {- if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {+ if (PDFJS.disableHistory || window.parent !== window) {// The browsing history is only enabled when the viewer is standalone,- // i.e. not when it is embedded in a web page.+ // i.e. not when it is embedded in a page.return;}this.initialized = true;@@ -1232,7 +815,7 @@ var PDFHistory = {var state = window.history.state;if (this._isStateObjectDefined(state)) {- // This corresponds to navigating back to the document+ // This case corresponds to navigating back to the document// from another page in the browser history.if (state.target.dest) {this.initialDestination = state.target.dest;@@ -1243,14 +826,14 @@ var PDFHistory = {this.uid = state.uid + 1;this.current = state.target;} else {- // This corresponds to the loading of a new document.+ // This case corresponds to the loading of a new document.if (state && state.fingerprint &&this.fingerprint !== state.fingerprint) {// Reinitialize the browsing history when a new document// is opened in the web viewer.this.reInitialized = true;}- this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);+ window.history.replaceState({ fingerprint: this.fingerprint }, '', '');}var self = this;@@ -1267,14 +850,10 @@ var PDFHistory = {} else {// Handle the user modifying the hash of a loaded document.self.previousHash = window.location.hash.substring(1);-- // If the history is empty when the hash changes,- // update the previous entry in the browser history.if (self.uid === 0) {var previousParams = (self.previousHash && self.currentBookmark &&self.previousHash !== self.currentBookmark) ?- { hash: self.currentBookmark, page: self.currentPage } :- { page: 1 };+ { hash: self.currentBookmark } : { page: 1 };self.historyUnlocked = false;self.allowHashChange = false;window.history.back();@@ -1283,29 +862,23 @@ var PDFHistory = {self.historyUnlocked = true;}self._pushToHistory({ hash: self.previousHash }, false, true);- self._updatePreviousBookmark();+ if (self.currentBookmark) {+ self.previousBookmark = self.currentBookmark;+ }}}, false);- function pdfHistoryBeforeUnload() {+ window.addEventListener('beforeunload',+ function pdfHistoryBeforeunload(evt) {var previousParams = self._getPreviousParams(null, true);if (previousParams) {- var replacePrevious = (!self.current.dest &&- self.current.hash !== self.previousHash);- self._pushToHistory(previousParams, false, replacePrevious);- self._updatePreviousBookmark();+ self._pushToHistory(previousParams, false);+ }+ if (PDFView.isPresentationMode) {+ // Prevent the user from accidentally navigating away from+ // the document when presentation mode is active.+ evt.preventDefault();}- // Remove the event listener when navigating away from the document,- // since 'beforeunload' prevents Firefox from caching the document.- window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);- }- window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);-- window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {- // If the entire viewer (including the PDF file) is cached in the browser,- // we need to reattach the 'beforeunload' event listener since- // the 'DOMContentLoaded' event is not fired on 'pageshow'.- window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);}, false);},@@ -1315,15 +888,6 @@ var PDFHistory = {state.target && state.target.hash) ? true : false;},- _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,- replace) {- if (replace) {- window.history.replaceState(stateObj, '', document.URL);- } else {- window.history.pushState(stateObj, '', document.URL);- }- },-get isHashChangeUnlocked() {if (!this.initialized) {return true;@@ -1343,21 +907,16 @@ var PDFHistory = {return temp;},- _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {- if (this.updatePreviousBookmark &&- this.currentBookmark && this.currentPage) {- this.previousBookmark = this.currentBookmark;- this.previousPage = this.currentPage;- this.updatePreviousBookmark = false;- }- },-updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,pageNum) {if (this.initialized) {this.currentBookmark = bookmark.substring(1);this.currentPage = pageNum | 0;- this._updatePreviousBookmark();+ if (this.updatePreviousBookmark) {+ this.previousBookmark = this.currentBookmark;+ this.previousPage = this.currentPage;+ this.updatePreviousBookmark = false;+ }}},@@ -1380,41 +939,24 @@ var PDFHistory = {if (params.page) {params.page |= 0;}- if (isInitialBookmark) {- var target = window.history.state.target;- if (!target) {- // Invoked when the user specifies an initial bookmark,- // thus setting PDFView.initialBookmark, when the document is loaded.- this._pushToHistory(params, false);- this.previousHash = window.location.hash.substring(1);- }+ if (isInitialBookmark && this.uid === 0) {+ this._pushToHistory(params, false);+ this.previousHash = window.location.hash.substring(1);this.updatePreviousBookmark = this.nextHashParam ? false : true;- if (target) {- // If the current document is reloaded,- // avoid creating duplicate entries in the history.- this._updatePreviousBookmark();- }return;}- if (this.nextHashParam) {- if (this.nextHashParam === params.hash) {- this.nextHashParam = null;- this.updatePreviousBookmark = true;- return;- } else {- this.nextHashParam = null;- }+ if (this.nextHashParam && this.nextHashParam === params.hash) {+ this.nextHashParam = null;+ this.updatePreviousBookmark = true;+ return;}if (params.hash) {if (this.current.hash) {if (this.current.hash !== params.hash) {this._pushToHistory(params, true);- } else {- if (!this.current.page && params.page) {- this._pushToHistory(params, false, true);- }- this.updatePreviousBookmark = true;+ } else if (!this.current.page && params.page) {+ this._pushToHistory(params, false, true);}} else {this._pushToHistory(params, true);@@ -1429,22 +971,6 @@ var PDFHistory = {beforeUnload) {if (!(this.currentBookmark && this.currentPage)) {return null;- } else if (this.updatePreviousBookmark) {- this.updatePreviousBookmark = false;- }- if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {- // Prevent the history from getting stuck in the current state,- // effectively preventing the user from going back/forward in the history.- //- // This happens if the current position in the document didn't change when- // the history was previously updated. The reasons for this are either:- // 1. The current zoom value is such that the document does not need to,- // or cannot, be scrolled to display the destination.- // 2. The previous destination is broken, and doesn't actally point to a- // position within the document.- // (This is either due to a bad PDF generator, or the user making a- // mistake when entering a destination in the hash parameters.)- return null;}if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {if (this.previousBookmark === this.currentBookmark) {@@ -1458,7 +984,7 @@ var PDFHistory = {return null;}var params = { hash: this.currentBookmark, page: this.currentPage };- if (PresentationMode.active) {+ if (PDFView.isPresentationMode) {params.hash = null;}return params;@@ -1479,13 +1005,14 @@ var PDFHistory = {if (addPrevious && !overwrite) {var previousParams = this._getPreviousParams();if (previousParams) {- var replacePrevious = (!this.current.dest &&- this.current.hash !== this.previousHash);- this._pushToHistory(previousParams, false, replacePrevious);+ this._pushToHistory(previousParams, false);}}- this._pushOrReplaceState(this._stateObj(params),- (overwrite || this.uid === 0));+ if (overwrite || this.uid === 0) {+ window.history.replaceState(this._stateObj(params), '', '');+ } else {+ window.history.pushState(this._stateObj(params), '', '');+ }this.currentUid = this.uid++;this.current = params;this.updatePreviousBookmark = true;@@ -1549,908 +1076,14 @@ var PDFHistory = {}};--var SecondaryToolbar = {- opened: false,- previousContainerHeight: null,- newContainerHeight: null,-- initialize: function secondaryToolbarInitialize(options) {- this.toolbar = options.toolbar;- this.presentationMode = options.presentationMode;- this.documentProperties = options.documentProperties;- this.buttonContainer = this.toolbar.firstElementChild;-- // Define the toolbar buttons.- this.toggleButton = options.toggleButton;- this.presentationModeButton = options.presentationModeButton;- this.openFile = options.openFile;- this.print = options.print;- this.download = options.download;- this.viewBookmark = options.viewBookmark;- this.firstPage = options.firstPage;- this.lastPage = options.lastPage;- this.pageRotateCw = options.pageRotateCw;- this.pageRotateCcw = options.pageRotateCcw;- this.documentPropertiesButton = options.documentPropertiesButton;-- // Attach the event listeners.- var elements = [- // Button to toggle the visibility of the secondary toolbar:- { element: this.toggleButton, handler: this.toggle },- // All items within the secondary toolbar- // (except for toggleHandTool, hand_tool.js is responsible for it):- { element: this.presentationModeButton,- handler: this.presentationModeClick },- { element: this.openFile, handler: this.openFileClick },- { element: this.print, handler: this.printClick },- { element: this.download, handler: this.downloadClick },- { element: this.viewBookmark, handler: this.viewBookmarkClick },- { element: this.firstPage, handler: this.firstPageClick },- { element: this.lastPage, handler: this.lastPageClick },- { element: this.pageRotateCw, handler: this.pageRotateCwClick },- { element: this.pageRotateCcw, handler: this.pageRotateCcwClick },- { element: this.documentPropertiesButton,- handler: this.documentPropertiesClick }- ];-- for (var item in elements) {- var element = elements[item].element;- if (element) {- element.addEventListener('click', elements[item].handler.bind(this));- }- }- },-- // Event handling functions.- presentationModeClick: function secondaryToolbarPresentationModeClick(evt) {- this.presentationMode.request();- this.close();- },-- openFileClick: function secondaryToolbarOpenFileClick(evt) {- document.getElementById('fileInput').click();- this.close();- },-- printClick: function secondaryToolbarPrintClick(evt) {- window.print();- this.close();- },-- downloadClick: function secondaryToolbarDownloadClick(evt) {- PDFView.download();- this.close();- },-- viewBookmarkClick: function secondaryToolbarViewBookmarkClick(evt) {- this.close();- },-- firstPageClick: function secondaryToolbarFirstPageClick(evt) {- PDFView.page = 1;- this.close();- },-- lastPageClick: function secondaryToolbarLastPageClick(evt) {- PDFView.page = PDFView.pdfDocument.numPages;- this.close();- },-- pageRotateCwClick: function secondaryToolbarPageRotateCwClick(evt) {- PDFView.rotatePages(90);- },-- pageRotateCcwClick: function secondaryToolbarPageRotateCcwClick(evt) {- PDFView.rotatePages(-90);- },-- documentPropertiesClick: function secondaryToolbarDocumentPropsClick(evt) {- this.documentProperties.show();- this.close();- },-- // Misc. functions for interacting with the toolbar.- setMaxHeight: function secondaryToolbarSetMaxHeight(container) {- if (!container || !this.buttonContainer) {- return;- }- this.newContainerHeight = container.clientHeight;- if (this.previousContainerHeight === this.newContainerHeight) {- return;- }- this.buttonContainer.setAttribute('style',- 'max-height: ' + (this.newContainerHeight - SCROLLBAR_PADDING) + 'px;');- this.previousContainerHeight = this.newContainerHeight;- },-- open: function secondaryToolbarOpen() {- if (this.opened) {- return;- }- this.opened = true;- this.toggleButton.classList.add('toggled');- this.toolbar.classList.remove('hidden');- },-- close: function secondaryToolbarClose(target) {- if (!this.opened) {- return;- } else if (target && !this.toolbar.contains(target)) {- return;- }- this.opened = false;- this.toolbar.classList.add('hidden');- this.toggleButton.classList.remove('toggled');- },-- toggle: function secondaryToolbarToggle() {- if (this.opened) {- this.close();- } else {- this.open();- }- }-};---var PasswordPrompt = {- visible: false,- updatePassword: null,- reason: null,- overlayContainer: null,- passwordField: null,- passwordText: null,- passwordSubmit: null,- passwordCancel: null,-- initialize: function secondaryToolbarInitialize(options) {- this.overlayContainer = options.overlayContainer;- this.passwordField = options.passwordField;- this.passwordText = options.passwordText;- this.passwordSubmit = options.passwordSubmit;- this.passwordCancel = options.passwordCancel;-- // Attach the event listeners.- this.passwordSubmit.addEventListener('click',- this.verifyPassword.bind(this));-- this.passwordCancel.addEventListener('click', this.hide.bind(this));-- this.passwordField.addEventListener('keydown',- function (e) {- if (e.keyCode === 13) { // Enter key- this.verifyPassword();- }- }.bind(this));-- window.addEventListener('keydown',- function (e) {- if (e.keyCode === 27) { // Esc key- this.hide();- }- }.bind(this));- },-- show: function passwordPromptShow() {- if (this.visible) {- return;- }- this.visible = true;- this.overlayContainer.classList.remove('hidden');- this.overlayContainer.firstElementChild.classList.remove('hidden');- this.passwordField.focus();-- var promptString = mozL10n.get('password_label', null,- 'Enter the password to open this PDF file.');-- if (this.reason === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {- promptString = mozL10n.get('password_invalid', null,- 'Invalid password. Please try again.');- }-- this.passwordText.textContent = promptString;- },-- hide: function passwordPromptClose() {- if (!this.visible) {- return;- }- this.visible = false;- this.passwordField.value = '';- this.overlayContainer.classList.add('hidden');- this.overlayContainer.firstElementChild.classList.add('hidden');- },-- verifyPassword: function passwordPromptVerifyPassword() {- var password = this.passwordField.value;- if (password && password.length > 0) {- this.hide();- return this.updatePassword(password);- }- }-};---var DELAY_BEFORE_HIDING_CONTROLS = 3000; // in ms-var SELECTOR = 'presentationControls';-var DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS = 1000; // in ms--var PresentationMode = {- active: false,- args: null,- contextMenuOpen: false,- prevCoords: { x: null, y: null },-- initialize: function presentationModeInitialize(options) {- this.container = options.container;- this.secondaryToolbar = options.secondaryToolbar;-- this.viewer = this.container.firstElementChild;-- this.firstPage = options.firstPage;- this.lastPage = options.lastPage;- this.pageRotateCw = options.pageRotateCw;- this.pageRotateCcw = options.pageRotateCcw;-- this.firstPage.addEventListener('click', function() {- this.contextMenuOpen = false;- this.secondaryToolbar.firstPageClick();- }.bind(this));- this.lastPage.addEventListener('click', function() {- this.contextMenuOpen = false;- this.secondaryToolbar.lastPageClick();- }.bind(this));-- this.pageRotateCw.addEventListener('click', function() {- this.contextMenuOpen = false;- this.secondaryToolbar.pageRotateCwClick();- }.bind(this));- this.pageRotateCcw.addEventListener('click', function() {- this.contextMenuOpen = false;- this.secondaryToolbar.pageRotateCcwClick();- }.bind(this));- },-- get isFullscreen() {- return (document.fullscreenElement ||- document.mozFullScreen ||- document.webkitIsFullScreen ||- document.msFullscreenElement);- },-- /**- * Initialize a timeout that is used to reset PDFView.currentPosition when the- * browser transitions to fullscreen mode. Since resize events are triggered- * multiple times during the switch to fullscreen mode, this is necessary in- * order to prevent the page from being scrolled partially, or completely,- * out of view when Presentation Mode is enabled.- * Note: This is only an issue at certain zoom levels, e.g. 'page-width'.- */- _setSwitchInProgress: function presentationMode_setSwitchInProgress() {- if (this.switchInProgress) {- clearTimeout(this.switchInProgress);- }- this.switchInProgress = setTimeout(function switchInProgressTimeout() {- delete this.switchInProgress;- }.bind(this), DELAY_BEFORE_RESETTING_SWITCH_IN_PROGRESS);-- PDFView.currentPosition = null;- },-- _resetSwitchInProgress: function presentationMode_resetSwitchInProgress() {- if (this.switchInProgress) {- clearTimeout(this.switchInProgress);- delete this.switchInProgress;- }- },-- request: function presentationModeRequest() {- if (!PDFView.supportsFullscreen || this.isFullscreen ||- !this.viewer.hasChildNodes()) {- return false;- }- this._setSwitchInProgress();-- if (this.container.requestFullscreen) {- this.container.requestFullscreen();- } else if (this.container.mozRequestFullScreen) {- this.container.mozRequestFullScreen();- } else if (this.container.webkitRequestFullScreen) {- this.container.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);- } else if (this.container.msRequestFullscreen) {- this.container.msRequestFullscreen();- } else {- return false;- }-- this.args = {- page: PDFView.page,- previousScale: PDFView.currentScaleValue- };-- return true;- },-- enter: function presentationModeEnter() {- this.active = true;- this._resetSwitchInProgress();-- // Ensure that the correct page is scrolled into view when entering- // Presentation Mode, by waiting until fullscreen mode in enabled.- // Note: This is only necessary in non-Mozilla browsers.- setTimeout(function enterPresentationModeTimeout() {- PDFView.page = this.args.page;- PDFView.setScale('page-fit', true);- }.bind(this), 0);-- window.addEventListener('mousemove', this.mouseMove, false);- window.addEventListener('mousedown', this.mouseDown, false);- window.addEventListener('contextmenu', this.contextMenu, false);-- this.showControls();- HandTool.enterPresentationMode();- this.contextMenuOpen = false;- this.container.setAttribute('contextmenu', 'viewerContextMenu');- },-- exit: function presentationModeExit() {- var page = PDFView.page;-- // Ensure that the correct page is scrolled into view when exiting- // Presentation Mode, by waiting until fullscreen mode is disabled.- // Note: This is only necessary in non-Mozilla browsers.- setTimeout(function exitPresentationModeTimeout() {- PDFView.setScale(this.args.previousScale);- PDFView.page = page;- // Keep Presentation Mode active until the page is scrolled into view,- // to prevent issues in non-Mozilla browsers.- this.active = false;- this.args = null;- }.bind(this), 0);-- window.removeEventListener('mousemove', this.mouseMove, false);- window.removeEventListener('mousedown', this.mouseDown, false);- window.removeEventListener('contextmenu', this.contextMenu, false);-- this.hideControls();- PDFView.clearMouseScrollState();- HandTool.exitPresentationMode();- this.container.removeAttribute('contextmenu');- this.contextMenuOpen = false;-- // Ensure that the thumbnail of the current page is visible- // when exiting presentation mode.- scrollIntoView(document.getElementById('thumbnailContainer' + page));- },-- showControls: function presentationModeShowControls() {- if (this.controlsTimeout) {- clearTimeout(this.controlsTimeout);- } else {- this.container.classList.add(SELECTOR);- }- this.controlsTimeout = setTimeout(function hideControlsTimeout() {- this.container.classList.remove(SELECTOR);- delete this.controlsTimeout;- }.bind(this), DELAY_BEFORE_HIDING_CONTROLS);- },-- hideControls: function presentationModeHideControls() {- if (!this.controlsTimeout) {- return;- }- this.container.classList.remove(SELECTOR);- clearTimeout(this.controlsTimeout);- delete this.controlsTimeout;- },-- mouseMove: function presentationModeMouseMove(evt) {- // Workaround for a bug in WebKit browsers that causes the 'mousemove' event- // to be fired when the cursor is changed. For details, see:- // http://code.google.com/p/chromium/issues/detail?id=103041.-- var currCoords = { x: evt.clientX, y: evt.clientY };- var prevCoords = PresentationMode.prevCoords;- PresentationMode.prevCoords = currCoords;-- if (currCoords.x === prevCoords.x && currCoords.y === prevCoords.y) {- return;- }- PresentationMode.showControls();- },-- mouseDown: function presentationModeMouseDown(evt) {- var self = PresentationMode;- if (self.contextMenuOpen) {- self.contextMenuOpen = false;- evt.preventDefault();- return;- }-- if (evt.button === 0) {- // Enable clicking of links in presentation mode. Please note:- // Only links pointing to destinations in the current PDF document work.- var isInternalLink = (evt.target.href &&- evt.target.classList.contains('internalLink'));- if (!isInternalLink) {- // Unless an internal link was clicked, advance one page.- evt.preventDefault();- PDFView.page += (evt.shiftKey ? -1 : 1);- }- }- },-- contextMenu: function presentationModeContextMenu(evt) {- PresentationMode.contextMenuOpen = true;- }-};--(function presentationModeClosure() {- function presentationModeChange(e) {- if (PresentationMode.isFullscreen) {- PresentationMode.enter();- } else {- PresentationMode.exit();- }- }-- window.addEventListener('fullscreenchange', presentationModeChange, false);- window.addEventListener('mozfullscreenchange', presentationModeChange, false);- window.addEventListener('webkitfullscreenchange', presentationModeChange,- false);- window.addEventListener('MSFullscreenChange', presentationModeChange, false);-})();---/* Copyright 2013 Rob Wu <[email protected]>- * https://github.com/Rob--W/grab-to-pan.js- *- * 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.- */--'use strict';--var GrabToPan = (function GrabToPanClosure() {- /**- * Construct a GrabToPan instance for a given HTML element.- * @param options.element {Element}- * @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`- * @param options.onActiveChanged {function(boolean)} optional. Called- * when grab-to-pan is (de)activated. The first argument is a boolean that- * shows whether grab-to-pan is activated.- */- function GrabToPan(options) {- this.element = options.element;- this.document = options.element.ownerDocument;- if (typeof options.ignoreTarget === 'function') {- this.ignoreTarget = options.ignoreTarget;- }- this.onActiveChanged = options.onActiveChanged;-- // Bind the contexts to ensure that `this` always points to- // the GrabToPan instance.- this.activate = this.activate.bind(this);- this.deactivate = this.deactivate.bind(this);- this.toggle = this.toggle.bind(this);- this._onmousedown = this._onmousedown.bind(this);- this._onmousemove = this._onmousemove.bind(this);- this._endPan = this._endPan.bind(this);-- // This overlay will be inserted in the document when the mouse moves during- // a grab operation, to ensure that the cursor has the desired appearance.- var overlay = this.overlay = document.createElement('div');- overlay.className = 'grab-to-pan-grabbing';- }- GrabToPan.prototype = {- /**- * Class name of element which can be grabbed- */- CSS_CLASS_GRAB: 'grab-to-pan-grab',-- /**- * Bind a mousedown event to the element to enable grab-detection.- */- activate: function GrabToPan_activate() {- if (!this.active) {- this.active = true;- this.element.addEventListener('mousedown', this._onmousedown, true);- this.element.classList.add(this.CSS_CLASS_GRAB);- if (this.onActiveChanged) {- this.onActiveChanged(true);- }- }- },-- /**- * Removes all events. Any pending pan session is immediately stopped.- */- deactivate: function GrabToPan_deactivate() {- if (this.active) {- this.active = false;- this.element.removeEventListener('mousedown', this._onmousedown, true);- this._endPan();- this.element.classList.remove(this.CSS_CLASS_GRAB);- if (this.onActiveChanged) {- this.onActiveChanged(false);- }- }- },-- toggle: function GrabToPan_toggle() {- if (this.active) {- this.deactivate();- } else {- this.activate();- }- },-- /**- * Whether to not pan if the target element is clicked.- * Override this method to change the default behaviour.- *- * @param node {Element} The target of the event- * @return {boolean} Whether to not react to the click event.- */- ignoreTarget: function GrabToPan_ignoreTarget(node) {- // Use matchesSelector to check whether the clicked element- // is (a child of) an input element / link- return node[matchesSelector](- 'a[href], a[href] *, input, textarea, button, button *, select, option'- );- },-- /**- * @private- */- _onmousedown: function GrabToPan__onmousedown(event) {- if (event.button !== 0 || this.ignoreTarget(event.target)) {- return;- }- if (event.originalTarget) {- try {- /* jshint expr:true */- event.originalTarget.tagName;- } catch (e) {- // Mozilla-specific: element is a scrollbar (XUL element)- return;- }- }-- this.scrollLeftStart = this.element.scrollLeft;- this.scrollTopStart = this.element.scrollTop;- this.clientXStart = event.clientX;- this.clientYStart = event.clientY;- this.document.addEventListener('mousemove', this._onmousemove, true);- this.document.addEventListener('mouseup', this._endPan, true);- // When a scroll event occurs before a mousemove, assume that the user- // dragged a scrollbar (necessary for Opera Presto, Safari and IE)- // (not needed for Chrome/Firefox)- this.element.addEventListener('scroll', this._endPan, true);- event.preventDefault();- event.stopPropagation();- this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);- },-- /**- * @private- */- _onmousemove: function GrabToPan__onmousemove(event) {- this.element.removeEventListener('scroll', this._endPan, true);- if (isLeftMouseReleased(event)) {- this._endPan();- return;- }- var xDiff = event.clientX - this.clientXStart;- var yDiff = event.clientY - this.clientYStart;- this.element.scrollTop = this.scrollTopStart - yDiff;- this.element.scrollLeft = this.scrollLeftStart - xDiff;- if (!this.overlay.parentNode) {- document.body.appendChild(this.overlay);- }- },-- /**- * @private- */- _endPan: function GrabToPan__endPan() {- this.element.removeEventListener('scroll', this._endPan, true);- this.document.removeEventListener('mousemove', this._onmousemove, true);- this.document.removeEventListener('mouseup', this._endPan, true);- if (this.overlay.parentNode) {- this.overlay.parentNode.removeChild(this.overlay);- }- }- };-- // Get the correct (vendor-prefixed) name of the matches method.- var matchesSelector;- ['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {- var name = prefix + 'atches';- if (name in document.documentElement) {- matchesSelector = name;- }- name += 'Selector';- if (name in document.documentElement) {- matchesSelector = name;- }- return matchesSelector; // If found, then truthy, and [].some() ends.- });-- // Browser sniffing because it's impossible to feature-detect- // whether event.which for onmousemove is reliable- var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;- var chrome = window.chrome;- var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);- // ^ Chrome 15+ ^ Opera 15+- var isSafari6plus = /Apple/.test(navigator.vendor) &&- /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);-- /**- * Whether the left mouse is not pressed.- * @param event {MouseEvent}- * @return {boolean} True if the left mouse button is not pressed.- * False if unsure or if the left mouse button is pressed.- */- function isLeftMouseReleased(event) {- if ('buttons' in event && isNotIEorIsIE10plus) {- // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons- // Firefox 15+- // Internet Explorer 10+- return !(event.buttons | 1);- }- if (isChrome15OrOpera15plus || isSafari6plus) {- // Chrome 14+- // Opera 15+- // Safari 6.0+- return event.which === 0;- }- }-- return GrabToPan;-})();--var HandTool = {- initialize: function handToolInitialize(options) {- var toggleHandTool = options.toggleHandTool;- this.handTool = new GrabToPan({- element: options.container,- onActiveChanged: function(isActive) {- if (!toggleHandTool) {- return;- }- if (isActive) {- toggleHandTool.title =- mozL10n.get('hand_tool_disable.title', null, 'Disable hand tool');- toggleHandTool.firstElementChild.textContent =- mozL10n.get('hand_tool_disable_label', null, 'Disable hand tool');- } else {- toggleHandTool.title =- mozL10n.get('hand_tool_enable.title', null, 'Enable hand tool');- toggleHandTool.firstElementChild.textContent =- mozL10n.get('hand_tool_enable_label', null, 'Enable hand tool');- }- }- });- if (toggleHandTool) {- toggleHandTool.addEventListener('click', this.toggle.bind(this), false);- }- // TODO: Read global prefs and call this.handTool.activate() if needed.- },-- toggle: function handToolToggle() {- this.handTool.toggle();- SecondaryToolbar.close();- },-- enterPresentationMode: function handToolEnterPresentationMode() {- if (this.handTool.active) {- this.wasActive = true;- this.handTool.deactivate();- }- },-- exitPresentationMode: function handToolExitPresentationMode() {- if (this.wasActive) {- this.wasActive = null;- this.handTool.activate();- }- }-};---var DocumentProperties = {- overlayContainer: null,- fileName: '',- fileSize: '',- visible: false,-- // Document property fields (in the viewer).- fileNameField: null,- fileSizeField: null,- titleField: null,- authorField: null,- subjectField: null,- keywordsField: null,- creationDateField: null,- modificationDateField: null,- creatorField: null,- producerField: null,- versionField: null,- pageCountField: null,-- initialize: function documentPropertiesInitialize(options) {- this.overlayContainer = options.overlayContainer;-- // Set the document property fields.- this.fileNameField = options.fileNameField;- this.fileSizeField = options.fileSizeField;- this.titleField = options.titleField;- this.authorField = options.authorField;- this.subjectField = options.subjectField;- this.keywordsField = options.keywordsField;- this.creationDateField = options.creationDateField;- this.modificationDateField = options.modificationDateField;- this.creatorField = options.creatorField;- this.producerField = options.producerField;- this.versionField = options.versionField;- this.pageCountField = options.pageCountField;-- // Bind the event listener for the Close button.- if (options.closeButton) {- options.closeButton.addEventListener('click', this.hide.bind(this));- }-- // Bind the event listener for the Esc key (to close the dialog).- window.addEventListener('keydown',- function (e) {- if (e.keyCode === 27) { // Esc key- this.hide();- }- }.bind(this));- },-- getProperties: function documentPropertiesGetProperties() {- var self = this;-- // Get the file name.- this.fileName = getPDFFileNameFromURL(PDFView.url);-- // Get the file size.- PDFView.pdfDocument.getDownloadInfo().then(function(data) {- self.setFileSize(data.length);- });-- // Get the other document properties.- PDFView.pdfDocument.getMetadata().then(function(data) {- var fields = [- { field: self.fileNameField, content: self.fileName },- { field: self.fileSizeField, content: self.fileSize },- { field: self.titleField, content: data.info.Title },- { field: self.authorField, content: data.info.Author },- { field: self.subjectField, content: data.info.Subject },- { field: self.keywordsField, content: data.info.Keywords },- { field: self.creationDateField,- content: self.parseDate(data.info.CreationDate) },- { field: self.modificationDateField,- content: self.parseDate(data.info.ModDate) },- { field: self.creatorField, content: data.info.Creator },- { field: self.producerField, content: data.info.Producer },- { field: self.versionField, content: data.info.PDFFormatVersion },- { field: self.pageCountField, content: PDFView.pdfDocument.numPages }- ];-- // Show the properties in the dialog.- for (var item in fields) {- var element = fields[item];- if (element.field && element.content !== undefined &&- element.content !== '') {- element.field.textContent = element.content;- }- }- });- },-- setFileSize: function documentPropertiesSetFileSize(fileSize) {- var kb = fileSize / 1024;- if (kb < 1024) {- this.fileSize = mozL10n.get('document_properties_kb', {- size_kb: (+kb.toPrecision(3)).toLocaleString(),- size_b: fileSize.toLocaleString()- }, '{{size_kb}} KB ({{size_b}} bytes)');- } else {- this.fileSize = mozL10n.get('document_properties_mb', {- size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),- size_b: fileSize.toLocaleString()- }, '{{size_mb}} MB ({{size_b}} bytes)');- }- },-- show: function documentPropertiesShow() {- if (this.visible) {- return;- }- this.visible = true;- this.overlayContainer.classList.remove('hidden');- this.overlayContainer.lastElementChild.classList.remove('hidden');- this.getProperties();- },-- hide: function documentPropertiesClose() {- if (!this.visible) {- return;- }- this.visible = false;- this.overlayContainer.classList.add('hidden');- this.overlayContainer.lastElementChild.classList.add('hidden');- },-- parseDate: function documentPropertiesParseDate(inputDate) {- // This is implemented according to the PDF specification (see- // http://www.gnupdf.org/Date for an overview), but note that- // Adobe Reader doesn't handle changing the date to universal time- // and doesn't use the user's time zone (they're effectively ignoring- // the HH' and mm' parts of the date string).- var dateToParse = inputDate;- if (dateToParse === undefined) {- return '';- }-- // Remove the D: prefix if it is available.- if (dateToParse.substring(0,2) === 'D:') {- dateToParse = dateToParse.substring(2);- }-- // Get all elements from the PDF date string.- // JavaScript's Date object expects the month to be between- // 0 and 11 instead of 1 and 12, so we're correcting for this.- var year = parseInt(dateToParse.substring(0,4), 10);- var month = parseInt(dateToParse.substring(4,6), 10) - 1;- var day = parseInt(dateToParse.substring(6,8), 10);- var hours = parseInt(dateToParse.substring(8,10), 10);- var minutes = parseInt(dateToParse.substring(10,12), 10);- var seconds = parseInt(dateToParse.substring(12,14), 10);- var utRel = dateToParse.substring(14,15);- var offsetHours = parseInt(dateToParse.substring(15,17), 10);- var offsetMinutes = parseInt(dateToParse.substring(18,20), 10);-- // As per spec, utRel = 'Z' means equal to universal time.- // The other cases ('-' and '+') have to be handled here.- if (utRel == '-') {- hours += offsetHours;- minutes += offsetMinutes;- } else if (utRel == '+') {- hours -= offsetHours;- minutes += offsetMinutes;- }-- // Return the new date format from the user's locale.- var date = new Date(Date.UTC(year, month, day, hours, minutes, seconds));- var dateString = date.toLocaleDateString();- var timeString = date.toLocaleTimeString();- return mozL10n.get('document_properties_date_string',- {date: dateString, time: timeString},- '{{date}}, {{time}}');- }-};--var PDFView = {pages: [],thumbnails: [],currentScale: UNKNOWN_SCALE,currentScaleValue: null,initialBookmark: document.location.hash.substring(1),+ startedTextExtraction: false,+ pageText: [],container: null,thumbnailContainer: null,initialized: false,@@ -2459,14 +1092,13 @@ var PDFView = {sidebarOpen: false,pageViewScroll: null,thumbnailViewScroll: null,+ isPresentationMode: false,+ presentationModeArgs: null,pageRotation: 0,mouseScrollTimeStamp: 0,mouseScrollDelta: 0,lastScroll: 0,previousPageNumber: 1,- isViewerEmbedded: (window.parent !== window),- idleTimeout: null,- currentPosition: null,// called once when the document is loadedinitialize: function pdfViewInitialize() {@@ -2482,77 +1114,20 @@ var PDFView = {this.renderHighestPriority.bind(this));PDFFindBar.initialize({- bar: document.getElementById('findbar'),- toggleButton: document.getElementById('viewFind'),- findField: document.getElementById('findInput'),- highlightAllCheckbox: document.getElementById('findHighlightAll'),- caseSensitiveCheckbox: document.getElementById('findMatchCase'),- findMsg: document.getElementById('findMsg'),- findStatusIcon: document.getElementById('findStatusIcon'),- findPreviousButton: document.getElementById('findPrevious'),- findNextButton: document.getElementById('findNext')+ bar: document.getElementById('findbar'),+ toggleButton: document.getElementById('viewFind'),+ findField: document.getElementById('findInput'),+ highlightAllCheckbox: document.getElementById('findHighlightAll'),+ caseSensitiveCheckbox: document.getElementById('findMatchCase'),+ findMsg: document.getElementById('findMsg'),+ findStatusIcon: document.getElementById('findStatusIcon'),+ findPreviousButton: document.getElementById('findPrevious'),+ findNextButton: document.getElementById('findNext')});PDFFindController.initialize({- pdfPageSource: this,- integratedFind: this.supportsIntegratedFind- });-- HandTool.initialize({- container: container,- toggleHandTool: document.getElementById('toggleHandTool')- });-- SecondaryToolbar.initialize({- toolbar: document.getElementById('secondaryToolbar'),- presentationMode: PresentationMode,- toggleButton: document.getElementById('secondaryToolbarToggle'),- presentationModeButton:- document.getElementById('secondaryPresentationMode'),- openFile: document.getElementById('secondaryOpenFile'),- print: document.getElementById('secondaryPrint'),- download: document.getElementById('secondaryDownload'),- viewBookmark: document.getElementById('secondaryViewBookmark'),- firstPage: document.getElementById('firstPage'),- lastPage: document.getElementById('lastPage'),- pageRotateCw: document.getElementById('pageRotateCw'),- pageRotateCcw: document.getElementById('pageRotateCcw'),- documentProperties: DocumentProperties,- documentPropertiesButton: document.getElementById('documentProperties')- });-- PasswordPrompt.initialize({- overlayContainer: document.getElementById('overlayContainer'),- passwordField: document.getElementById('password'),- passwordText: document.getElementById('passwordText'),- passwordSubmit: document.getElementById('passwordSubmit'),- passwordCancel: document.getElementById('passwordCancel')- });-- PresentationMode.initialize({- container: container,- secondaryToolbar: SecondaryToolbar,- firstPage: document.getElementById('contextFirstPage'),- lastPage: document.getElementById('contextLastPage'),- pageRotateCw: document.getElementById('contextPageRotateCw'),- pageRotateCcw: document.getElementById('contextPageRotateCcw')- });-- DocumentProperties.initialize({- overlayContainer: document.getElementById('overlayContainer'),- closeButton: document.getElementById('documentPropertiesClose'),- fileNameField: document.getElementById('fileNameField'),- fileSizeField: document.getElementById('fileSizeField'),- titleField: document.getElementById('titleField'),- authorField: document.getElementById('authorField'),- subjectField: document.getElementById('subjectField'),- keywordsField: document.getElementById('keywordsField'),- creationDateField: document.getElementById('creationDateField'),- modificationDateField: document.getElementById('modificationDateField'),- creatorField: document.getElementById('creatorField'),- producerField: document.getElementById('producerField'),- versionField: document.getElementById('versionField'),- pageCountField: document.getElementById('pageCountField')+ pdfPageSource: this,+ integratedFind: this.supportsIntegratedFind});this.initialized = true;@@ -2583,99 +1158,85 @@ var PDFView = {}, true);},- _setScaleUpdatePages: function pdfView_setScaleUpdatePages(- newScale, newValue, resetAutoSettings, noScroll) {- this.currentScaleValue = newValue;- if (newScale === this.currentScale) {+ setScale: function pdfViewSetScale(val, resetAutoSettings, noScroll) {+ if (val == this.currentScale)return;- }- for (var i = 0, ii = this.pages.length; i < ii; i++) {- this.pages[i].update(newScale);- }- this.currentScale = newScale;- if (!noScroll) {- var page = this.page, dest;- if (this.currentPosition && !IGNORE_CURRENT_POSITION_ON_ZOOM) {- page = this.currentPosition.page;- dest = [null, { name: 'XYZ' }, this.currentPosition.left,- this.currentPosition.top, null];- }- this.pages[page - 1].scrollIntoView(dest);- }+ var pages = this.pages;+ for (var i = 0; i < pages.length; i++)+ pages[i].update(val * CSS_UNITS);++ if (!noScroll && this.currentScale != val)+ this.pages[this.page - 1].scrollIntoView();+ this.currentScale = val;+var event = document.createEvent('UIEvents');event.initUIEvent('scalechange', false, false, window, 0);- event.scale = newScale;+ event.scale = val;event.resetAutoSettings = resetAutoSettings;window.dispatchEvent(event);},- setScale: function pdfViewSetScale(value, resetAutoSettings, noScroll) {- if (value === 'custom') {+ parseScale: function pdfViewParseScale(value, resetAutoSettings, noScroll) {+ if ('custom' == value)return;- }+var scale = parseFloat(value);+ this.currentScaleValue = value;+ if (scale) {+ this.setScale(scale, true, noScroll);+ return;+ }- if (scale > 0) {- this._setScaleUpdatePages(scale, value, true, noScroll);- } else {- var currentPage = this.pages[this.page - 1];- if (!currentPage) {- return;- }- var pageWidthScale = (this.container.clientWidth - SCROLLBAR_PADDING) /- currentPage.width * currentPage.scale;- var pageHeightScale = (this.container.clientHeight - VERTICAL_PADDING) /- currentPage.height * currentPage.scale;- switch (value) {- case 'page-actual':- scale = 1;- break;- case 'page-width':- scale = pageWidthScale;- break;- case 'page-height':- scale = pageHeightScale;- break;- case 'page-fit':- scale = Math.min(pageWidthScale, pageHeightScale);- break;- case 'auto':- scale = Math.min(MAX_AUTO_SCALE, pageWidthScale);- break;- default:- console.error('pdfViewSetScale: \'' + value +- '\' is an unknown zoom value.');- return;- }- this._setScaleUpdatePages(scale, value, resetAutoSettings, noScroll);+ var container = this.container;+ var currentPage = this.pages[this.page - 1];+ if (!currentPage) {+ return;+ }- selectScaleOption(value);+ var pageWidthScale = (container.clientWidth - SCROLLBAR_PADDING) /+ currentPage.width * currentPage.scale / CSS_UNITS;+ var pageHeightScale = (container.clientHeight - VERTICAL_PADDING) /+ currentPage.height * currentPage.scale / CSS_UNITS;+ switch (value) {+ case 'page-actual':+ scale = 1;+ break;+ case 'page-width':+ scale = pageWidthScale;+ break;+ case 'page-height':+ scale = pageHeightScale;+ break;+ case 'page-fit':+ scale = Math.min(pageWidthScale, pageHeightScale);+ break;+ case 'auto':+ scale = Math.min(1.0, pageWidthScale);+ break;}+ this.setScale(scale, resetAutoSettings, noScroll);++ selectScaleOption(value);},- zoomIn: function pdfViewZoomIn(ticks) {- var newScale = this.currentScale;- do {- newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);- newScale = Math.ceil(newScale * 10) / 10;- newScale = Math.min(MAX_SCALE, newScale);- } while (--ticks && newScale < MAX_SCALE);- this.setScale(newScale, true);+ zoomIn: function pdfViewZoomIn() {+ var newScale = (this.currentScale * DEFAULT_SCALE_DELTA).toFixed(2);+ newScale = Math.ceil(newScale * 10) / 10;+ newScale = Math.min(MAX_SCALE, newScale);+ this.parseScale(newScale, true);},- zoomOut: function pdfViewZoomOut(ticks) {- var newScale = this.currentScale;- do {- newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);- newScale = Math.floor(newScale * 10) / 10;- newScale = Math.max(MIN_SCALE, newScale);- } while (--ticks && newScale > MIN_SCALE);- this.setScale(newScale, true);+ zoomOut: function pdfViewZoomOut() {+ var newScale = (this.currentScale / DEFAULT_SCALE_DELTA).toFixed(2);+ newScale = Math.floor(newScale * 10) / 10;+ newScale = Math.max(MIN_SCALE, newScale);+ this.parseScale(newScale, true);},set page(val) {var pages = this.pages;+ var input = document.getElementById('pageNumber');var event = document.createEvent('UIEvents');event.initUIEvent('pagechange', false, false, window, 0);@@ -2694,13 +1255,13 @@ var PDFView = {// checking if the this.page was called from the updateViewarea function:// avoiding the creation of two "set page" method (internal and public)- if (updateViewarea.inProgress) {+ if (updateViewarea.inProgress)return;- }+// Avoid scrolling the first page during loading- if (this.loading && val === 1) {+ if (this.loading && val == 1)return;- }+pages[val - 1].scrollIntoView();},@@ -2722,16 +1283,11 @@ var PDFView = {get supportsFullscreen() {var doc = document.documentElement;var support = doc.requestFullscreen || doc.mozRequestFullScreen ||- doc.webkitRequestFullScreen || doc.msRequestFullscreen;+ doc.webkitRequestFullScreen;if (document.fullscreenEnabled === false ||document.mozFullScreenEnabled === false ||- document.webkitFullscreenEnabled === false ||- document.msFullscreenEnabled === false) {- support = false;- } else if (this.isViewerEmbedded) {- // Need to check if the viewer is embedded as well, to prevent issues with- // presentation mode when the viewer is embedded in '<object>' tags.+ document.webkitFullscreenEnabled === false ) {support = false;}@@ -2769,20 +1325,82 @@ var PDFView = {return support;},- get loadingBar() {- var bar = new ProgressBar('#loadingBar', {});- Object.defineProperty(this, 'loadingBar', { value: bar,- enumerable: true,- configurable: true,- writable: false });- return bar;- },-get isHorizontalScrollbarEnabled() {- return (PresentationMode.active ? false :- (this.container.scrollWidth > this.container.clientWidth));+ var div = document.getElementById('viewerContainer');+ return div.scrollWidth > div.clientWidth;},+ initPassiveLoading: function pdfViewInitPassiveLoading() {+ if (!PDFView.loadingBar) {+ PDFView.loadingBar = new ProgressBar('#loadingBar', {});+ }++ var pdfDataRangeTransport = {+ rangeListeners: [],+ progressListeners: [],++ addRangeListener: function PdfDataRangeTransport_addRangeListener(+ listener) {+ this.rangeListeners.push(listener);+ },++ addProgressListener: function PdfDataRangeTransport_addProgressListener(+ listener) {+ this.progressListeners.push(listener);+ },++ onDataRange: function PdfDataRangeTransport_onDataRange(begin, chunk) {+ var listeners = this.rangeListeners;+ for (var i = 0, n = listeners.length; i < n; ++i) {+ listeners[i](begin, chunk);+ }+ },++ onDataProgress: function PdfDataRangeTransport_onDataProgress(loaded) {+ var listeners = this.progressListeners;+ for (var i = 0, n = listeners.length; i < n; ++i) {+ listeners[i](loaded);+ }+ },++ requestDataRange: function PdfDataRangeTransport_requestDataRange(+ begin, end) {+ FirefoxCom.request('requestDataRange', { begin: begin, end: end });+ }+ };++ window.addEventListener('message', function windowMessage(e) {+ var args = e.data;++ if (typeof args !== 'object' || !('pdfjsLoadAction' in args))+ return;+ switch (args.pdfjsLoadAction) {+ case 'supportsRangedLoading':+ PDFView.open(args.pdfUrl, 0, undefined, pdfDataRangeTransport, {+ length: args.length+ });+ break;+ case 'range':+ pdfDataRangeTransport.onDataRange(args.begin, args.chunk);+ break;+ case 'rangeProgress':+ pdfDataRangeTransport.onDataProgress(args.loaded);+ break;+ case 'progress':+ PDFView.progress(args.loaded / args.total);+ break;+ case 'complete':+ if (!args.data) {+ PDFView.error(mozL10n.get('loading_error', null,+ 'An error occurred while loading the PDF.'), e);+ break;+ }+ PDFView.open(args.data, 0);+ break;+ }+ });+ FirefoxCom.requestSync('initPassiveLoading', null);+ },setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {this.url = url;@@ -2815,17 +1433,26 @@ var PDFView = {}}- // Terminate worker of the previous document if any.- if (this.pdfDocument) {- this.pdfDocument.destroy();+ if (!PDFView.loadingBar) {+ PDFView.loadingBar = new ProgressBar('#loadingBar', {});}+this.pdfDocument = null;var self = this;self.loading = true;var passwordNeeded = function passwordNeeded(updatePassword, reason) {- PasswordPrompt.updatePassword = updatePassword;- PasswordPrompt.reason = reason;- PasswordPrompt.show();+ var promptString = mozL10n.get('request_password', null,+ 'PDF is protected by a password:');++ if (reason === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {+ promptString += '\n' + mozL10n.get('invalid_password', null,+ 'Invalid Password.');+ }++ password = prompt(promptString);+ if (password && password.length > 0) {+ return updatePassword(password);+ }};function getDocumentProgress(progressData) {@@ -2866,43 +1493,66 @@ var PDFView = {download: function pdfViewDownload() {function noData() {- downloadManager.downloadUrl(url, filename);+ FirefoxCom.request('download', { originalUrl: url });}-var url = this.url.split('#')[0];- var filename = getPDFFileNameFromURL(url);- var downloadManager = new DownloadManager();- downloadManager.onerror = function (err) {- // This error won't really be helpful because it's likely the- // fallback won't work either (or is already open).- PDFView.error('PDF failed to download.');- };- if (!this.pdfDocument) { // the PDF is not ready yet- noData();- return;+ var a = document.createElement('a');++ // If _parent == self, then opening an identical URL with different+ // location hash will only cause a navigation, not a download.+ if (window.top === window && !('download' in a) &&+ url === window.location.href.split('#')[0]) {+ url += url.indexOf('?') === -1 ? '?' : '&';}- this.pdfDocument.getData().then(- function getDataSuccess(data) {- var blob = PDFJS.createBlob(data, 'application/pdf');- downloadManager.download(blob, url, filename);- },- noData // Error occurred try downloading with just the url.- ).then(null, noData);+ url += '#pdfjs.action=download';+ if (a.click) {+ // Use a.click() if available. Otherwise, Chrome might show+ // "Unsafe JavaScript attempt to initiate a navigation change+ // for frame with URL" and not open the PDF at all.+ // Supported by (not mentioned = untested):+ // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)+ // - Chrome 19 - 26 (18- does not support a.click)+ // - Opera 9 - 12.15+ // - Internet Explorer 6 - 10+ // - Safari 6 (5.1- does not support a.click)+ a.href = url;+ a.target = '_parent';+ // Use a.download if available. This increases the likelihood that+ // the file is downloaded instead of opened by another PDF plugin.+ if ('download' in a) {+ var filename = url.match(/([^\/?#=]+\.pdf)/i);+ a.download = filename ? filename[1] : 'file.pdf';+ }+ // <a> must be in the document for IE and recent Firefox versions.+ // (otherwise .click() is ignored)+ (document.body || document.documentElement).appendChild(a);+ a.click();+ a.parentNode.removeChild(a);+ } else {+ window.open(url, '_parent');+ }},- fallback: function pdfViewFallback(featureId) {+ fallback: function pdfViewFallback() {return;},navigateTo: function pdfViewNavigateTo(dest) {- var destString = '';var self = this;-- var goToDestination = function(destRef) {- self.pendingRefStr = null;+ PDFJS.Promise.all([this.pagesPromise,+ this.destinationsPromise]).then(function() {+ var destString = '';+ if (typeof dest === 'string') {+ destString = dest;+ dest = self.destinations[dest];+ }+ if (!(dest instanceof Array)) {+ return; // invalid destination+ }// dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>+ var destRef = dest[0];var pageNumber = destRef instanceof Object ?self.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] :(destRef + 1);@@ -2915,24 +1565,7 @@ var PDFView = {// Update the browsing history.PDFHistory.push({ dest: dest, hash: destString, page: pageNumber });- } else {- self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {- var pageNum = pageIndex + 1;- self.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] = pageNum;- goToDestination(destRef);- });- }- };-- this.destinationsPromise.then(function() {- if (typeof dest === 'string') {- destString = dest;- dest = self.destinations[dest];- }- if (!(dest instanceof Array)) {- return; // invalid destination}- goToDestination(dest[0]);});},@@ -2966,14 +1599,15 @@ var PDFView = {},/**- * Prefix the full url on anchor links to make sure that links are resolved- * relative to the current URL instead of the one defined in <base href>.- * @param {String} anchor The anchor hash, including the #.+ * For the firefox extension we prefix the full url on anchor links so they+ * don't come up as resource:// urls and so open in new tab/window works.+ * @param {String} anchor The anchor hash include the #.*/getAnchorUrl: function getAnchorUrl(anchor) {return anchor;},+/*** Show the error box.* @param {String} message A message that is human readable.@@ -3025,19 +1659,17 @@ var PDFView = {errorMoreInfo.removeAttribute('hidden');moreInfoButton.setAttribute('hidden', 'true');lessInfoButton.removeAttribute('hidden');- errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';};lessInfoButton.onclick = function() {errorMoreInfo.setAttribute('hidden', 'true');moreInfoButton.removeAttribute('hidden');lessInfoButton.setAttribute('hidden', 'true');};- moreInfoButton.oncontextmenu = noContextMenuHandler;- lessInfoButton.oncontextmenu = noContextMenuHandler;- closeButton.oncontextmenu = noContextMenuHandler;moreInfoButton.removeAttribute('hidden');lessInfoButton.setAttribute('hidden', 'true');errorMoreInfo.value = moreInfoText;++ errorMoreInfo.rows = moreInfoText.split('\n').length - 1;},progress: function pdfViewProgress(level) {@@ -3052,32 +1684,21 @@ var PDFView = {},load: function pdfViewLoad(pdfDocument, scale) {- var self = this;- var isOnePageRenderedResolved = false;- var resolveOnePageRendered = null;- var onePageRendered = new Promise(function (resolve) {- resolveOnePageRendered = resolve;- });function bindOnAfterDraw(pageView, thumbnailView) {// when page is painted, using the image as thumbnail basepageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {- if (!isOnePageRenderedResolved) {- isOnePageRenderedResolved = true;- resolveOnePageRendered();- }thumbnailView.setImage(pageView.canvas);};}- PDFFindController.reset();-this.pdfDocument = pdfDocument;var errorWrapper = document.getElementById('errorWrapper');errorWrapper.setAttribute('hidden', 'true');- pdfDocument.getDownloadInfo().then(function() {- PDFView.loadingBar.hide();+ pdfDocument.dataLoaded().then(function() {+ var loadingBar = document.getElementById('loadingBar');+ loadingBar.classList.add('hidden');var outerContainer = document.getElementById('outerContainer');outerContainer.classList.remove('loadingInProgress');});@@ -3102,28 +1723,27 @@ var PDFView = {mozL10n.get('page_of', {pageCount: pagesCount}, 'of {{pageCount}}');document.getElementById('pageNumber').max = pagesCount;- var prefs = PDFView.prefs = new Preferences();PDFView.documentFingerprint = id;- var store = PDFView.store = new ViewHistory(id);+ var store = PDFView.store = new Settings(id);this.pageRotation = 0;var pages = this.pages = [];+ this.pageText = [];+ this.startedTextExtraction = false;var pagesRefMap = this.pagesRefMap = {};var thumbnails = this.thumbnails = [];- var resolvePagesPromise;- var pagesPromise = new Promise(function (resolve) {- resolvePagesPromise = resolve;- });- this.pagesPromise = pagesPromise;+ var pagesPromise = this.pagesPromise = new PDFJS.Promise();+ var self = this;var firstPagePromise = pdfDocument.getPage(1);// Fetch a single page so we can get a viewport that will be the default// viewport for all pagesfirstPagePromise.then(function(pdfPage) {- var viewport = pdfPage.getViewport((scale || 1.0) * CSS_UNITS);+ var viewport = pdfPage.getViewport(scale || 1.0);+ var pagePromises = [];for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {var viewportClone = viewport.clone();var pageView = new PageView(container, pageNum, scale,@@ -3136,59 +1756,48 @@ var PDFView = {thumbnails.push(thumbnailView);}- // Fetch all the pages since the viewport is needed before printing- // starts to create the correct size canvas. Wait until one page is- // rendered so we don't tie up too many resources early on.- onePageRendered.then(function () {- if (!PDFJS.disableAutoFetch) {- var getPagesLeft = pagesCount;- for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {- pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {- var pageView = pages[pageNum - 1];- if (!pageView.pdfPage) {- pageView.setPdfPage(pdfPage);- }- var refStr = pdfPage.ref.num + ' ' + pdfPage.ref.gen + ' R';- pagesRefMap[refStr] = pageNum;- getPagesLeft--;- if (!getPagesLeft) {- resolvePagesPromise();- }- }.bind(null, pageNum));- }- } else {- // XXX: Printing is semi-broken with auto fetch disabled.- resolvePagesPromise();- }- });-var event = document.createEvent('CustomEvent');event.initCustomEvent('documentload', true, true, {});window.dispatchEvent(event);- PDFView.loadingBar.setWidth(container);+ for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {+ var pagePromise = pdfDocument.getPage(pageNum);+ pagePromise.then(function(pdfPage) {+ var pageNum = pdfPage.pageNumber;+ var pageView = pages[pageNum - 1];+ if (!pageView.pdfPage) {+ // The pdfPage might already be set if we've already entered+ // pageView.draw()+ pageView.setPdfPage(pdfPage);+ }+ var thumbnailView = thumbnails[pageNum - 1];+ if (!thumbnailView.pdfPage) {+ thumbnailView.setPdfPage(pdfPage);+ }++ var pageRef = pdfPage.ref;+ var refStr = pageRef.num + ' ' + pageRef.gen + ' R';+ pagesRefMap[refStr] = pdfPage.pageNumber;+ });+ pagePromises.push(pagePromise);+ }- PDFFindController.resolveFirstPage();+ PDFJS.Promise.all(pagePromises).then(function(pages) {+ pagesPromise.resolve(pages);+ });});- var prefsPromise = prefs.initializedPromise;var storePromise = store.initializedPromise;- Promise.all([firstPagePromise, prefsPromise, storePromise]).- then(function() {- var showPreviousViewOnLoad = prefs.get('showPreviousViewOnLoad');- var defaultZoomValue = prefs.get('defaultZoomValue');-+ PDFJS.Promise.all([firstPagePromise, storePromise]).then(function() {var storedHash = null;- if (showPreviousViewOnLoad && store.get('exists', false)) {+ if (store.get('exists', false)) {var pageNum = store.get('page', '1');- var zoom = defaultZoomValue || store.get('zoom', PDFView.currentScale);+ var zoom = store.get('zoom', PDFView.currentScale);var left = store.get('scrollLeft', '0');var top = store.get('scrollTop', '0');storedHash = 'page=' + pageNum + '&zoom=' + zoom + ',' +left + ',' + top;- } else if (defaultZoomValue) {- storedHash = 'page=1&zoom=' + defaultZoomValue;}// Initialize the browsing history.PDFHistory.initialize(self.documentFingerprint);@@ -3196,9 +1805,10 @@ var PDFView = {self.setInitialView(storedHash, scale);// Make all navigation keys work on document load,- // unless the viewer is embedded in a web page.- if (!self.isViewerEmbedded) {- self.container.focus();+ // unless the viewer is embedded in another page.+ if (window.parent === window) {+ PDFView.container.focus();+ PDFView.container.blur();}});@@ -3207,7 +1817,7 @@ var PDFView = {pdfDocument.getJavaScript().then(function(javaScript) {if (javaScript.length) {console.warn('Warning: JavaScript is not supported');- PDFView.fallback(PDFJS.UNSUPPORTED_FEATURES.javaScript);+ PDFView.fallback();}// Hack to support auto printing.var regex = /\bprint\s*\(/g;@@ -3233,17 +1843,10 @@ var PDFView = {// outline depends on destinations and pagesRefMapvar promises = [pagesPromise, destinationsPromise,PDFView.animationStartedPromise];- Promise.all(promises).then(function() {+ PDFJS.Promise.all(promises).then(function() {pdfDocument.getOutline().then(function(outline) {self.outline = new DocumentOutlineView(outline);document.getElementById('viewOutline').disabled = !outline;-- if (outline && prefs.get('ifAvailableShowOutlineOnLoad')) {- if (!self.sidebarOpen) {- document.getElementById('sidebarToggle').click();- }- self.switchSidebarView('outline');- }});});@@ -3272,9 +1875,8 @@ var PDFView = {if (info.IsAcroFormPresent) {console.warn('Warning: AcroForm/XFA is not supported');- PDFView.fallback(PDFJS.UNSUPPORTED_FEATURES.forms);+ PDFView.fallback();}-});},@@ -3283,14 +1885,6 @@ var PDFView = {// updated if the zoom level stayed the same.this.currentScale = 0;this.currentScaleValue = null;- // When opening a new file (when one is already loaded in the viewer):- // Reset 'currentPageNumber', since otherwise the page's scale will be wrong- // if 'currentPageNumber' is larger than the number of pages in the file.- document.getElementById('pageNumber').value = currentPageNumber = 1;- // Reset the current position when loading a new file,- // to prevent displaying the wrong position in the document.- this.currentPosition = null;-if (PDFHistory.initialDestination) {this.navigateTo(PDFHistory.initialDestination);PDFHistory.initialDestination = null;@@ -3301,23 +1895,18 @@ var PDFView = {} else if (storedHash) {this.setHash(storedHash);} else if (scale) {- this.setScale(scale, true);+ this.parseScale(scale, true);this.page = 1;}if (PDFView.currentScale === UNKNOWN_SCALE) {// Scale was not initialized: invalid bookmark or scale was not specified.// Setting the default one.- this.setScale(DEFAULT_SCALE, true);+ this.parseScale(DEFAULT_SCALE, true);}},renderHighestPriority: function pdfViewRenderHighestPriority() {- if (PDFView.idleTimeout) {- clearTimeout(PDFView.idleTimeout);- PDFView.idleTimeout = null;- }-// Pages have a higher priority than thumbnails, so check them first.var visiblePages = this.getVisiblePages();var pageView = this.getHighestPriority(visiblePages, this.pages,@@ -3332,25 +1921,9 @@ var PDFView = {var thumbView = this.getHighestPriority(visibleThumbs,this.thumbnails,this.thumbnailViewScroll.down);- if (thumbView) {+ if (thumbView)this.renderView(thumbView, 'thumbnail');- return;- }- }-- PDFView.idleTimeout = setTimeout(function () {- PDFView.cleanup();- }, CLEANUP_TIMEOUT);- },-- cleanup: function pdfViewCleanup() {- for (var i = 0, ii = this.pages.length; i < ii; i++) {- if (this.pages[i] &&- this.pages[i].renderingState !== RenderingStates.FINISHED) {- this.pages[i].reset();- }}- this.pdfDocument.cleanup();},getHighestPriority: function pdfViewGetHighestPriority(visible, views,@@ -3389,7 +1962,7 @@ var PDFView = {return false;},- isViewFinished: function pdfViewIsViewFinished(view) {+ isViewFinished: function pdfViewNeedsRendering(view) {return view.renderingState === RenderingStates.FINISHED;},@@ -3427,31 +2000,28 @@ var PDFView = {PDFView.navigateTo(params.nameddest);return;}- var pageNumber, dest;if ('page' in params) {- pageNumber = (params.page | 0) || 1;- }- if ('zoom' in params) {- var zoomArgs = params.zoom.split(','); // scale,left,top- // building destination array-- // If the zoom value, it has to get divided by 100. If it is a string,- // it should stay as it is.- var zoomArg = zoomArgs[0];- var zoomArgNumber = parseFloat(zoomArg);- if (zoomArgNumber) {- zoomArg = zoomArgNumber / 100;+ var pageNumber = (params.page | 0) || 1;+ if ('zoom' in params) {+ var zoomArgs = params.zoom.split(','); // scale,left,top+ // building destination array++ // If the zoom value, it has to get divided by 100. If it is a string,+ // it should stay as it is.+ var zoomArg = zoomArgs[0];+ var zoomArgNumber = parseFloat(zoomArg);+ if (zoomArgNumber)+ zoomArg = zoomArgNumber / 100;++ var dest = [null, {name: 'XYZ'},+ zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,+ zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,+ zoomArg];+ var currentPage = this.pages[pageNumber - 1];+ currentPage.scrollIntoView(dest);+ } else {+ this.page = pageNumber; // simple page}- dest = [null, {name: 'XYZ'},- zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,- zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,- zoomArg];- }- if (dest) {- var currentPage = this.pages[(pageNumber || this.page) - 1];- currentPage.scrollIntoView(dest);- } else if (pageNumber) {- this.page = pageNumber; // simple page}if ('pagemode' in params) {var toggle = document.getElementById('sidebarToggle');@@ -3512,15 +2082,15 @@ var PDFView = {},getVisiblePages: function pdfViewGetVisiblePages() {- if (!PresentationMode.active) {+ if (!this.isPresentationMode) {return this.getVisibleElements(this.container, this.pages, true);} else {- // The algorithm in getVisibleElements doesn't work in all browsers and- // configurations when presentation mode is active.- var visible = [];- var currentPage = this.pages[this.page - 1];+ // The algorithm in getVisibleElements is broken in presentation mode.+ var visible = [], page = this.page;+ var currentPage = this.pages[page - 1];visible.push({ id: currentPage.id, view: currentPage });- return { first: currentPage, last: currentPage, views: visible };++ return { first: currentPage, last: currentPage, views: visible};}},@@ -3556,7 +2126,7 @@ var PDFView = {Math.max(0, currentHeight + viewHeight - bottom);percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;- visible.push({ id: view.id, x: currentWidth, y: currentHeight,+ visible.push({ id: view.id, y: currentHeight,view: view, percent: percentHeight });}@@ -3627,8 +2197,81 @@ var PDFView = {div.removeChild(div.lastChild);},- rotatePages: function pdfViewRotatePages(delta) {- var currentPage = this.pages[this.page - 1];+ presentationMode: function pdfViewPresentationMode() {+ var isPresentationMode = document.fullscreenElement ||+ document.mozFullScreen ||+ document.webkitIsFullScreen;++ if (isPresentationMode) {+ return false;+ }++ var wrapper = document.getElementById('viewerContainer');+ if (document.documentElement.requestFullscreen) {+ wrapper.requestFullscreen();+ } else if (document.documentElement.mozRequestFullScreen) {+ wrapper.mozRequestFullScreen();+ } else if (document.documentElement.webkitRequestFullScreen) {+ wrapper.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);+ } else {+ return false;+ }++ this.presentationModeArgs = {+ page: this.page,+ previousScale: this.currentScaleValue+ };++ return true;+ },++ enterPresentationMode: function pdfViewEnterPresentationMode() {+ this.isPresentationMode = true;+ this.page = this.presentationModeArgs.page;+ this.parseScale('page-fit', true);+ this.showPresentationControls();+ },++ exitPresentationMode: function pdfViewExitPresentationMode() {+ this.isPresentationMode = false;+ this.parseScale(this.presentationModeArgs.previousScale);+ this.page = this.page;+ this.clearMouseScrollState();+ this.hidePresentationControls();+ this.presentationModeArgs = null;++ // Ensure that the thumbnail of the current page is visible+ // when exiting presentation mode.+ scrollIntoView(document.getElementById('thumbnailContainer' + this.page));+ },++ showPresentationControls: function pdfViewShowPresentationControls() {+ var DELAY_BEFORE_HIDING_CONTROLS = 3000;+ var wrapper = document.getElementById('viewerContainer');+ if (this.presentationControlsTimeout) {+ clearTimeout(this.presentationControlsTimeout);+ } else {+ wrapper.classList.add('presentationControls');+ }+ this.presentationControlsTimeout = setTimeout(function hideControls() {+ wrapper.classList.remove('presentationControls');+ delete PDFView.presentationControlsTimeout;+ }, DELAY_BEFORE_HIDING_CONTROLS);+ },++ hidePresentationControls: function pdfViewShowPresentationControls() {+ if (!this.presentationControlsTimeout) {+ return;+ }+ clearTimeout(this.presentationControlsTimeout);+ delete this.presentationControlsTimeout;++ var wrapper = document.getElementById('viewerContainer');+ wrapper.classList.remove('presentationControls');+ },++ rotatePages: function pdfViewPageRotation(delta) {+this.pageRotation = (this.pageRotation + 360 + delta) % 360;for (var i = 0, l = this.pages.length; i < l; i++) {@@ -3641,13 +2284,19 @@ var PDFView = {thumb.update(this.pageRotation);}- this.setScale(this.currentScaleValue, true, true);+ this.parseScale(this.currentScaleValue, true);this.renderHighestPriority();- if (currentPage) {- currentPage.scrollIntoView();+ var currentPage = this.pages[this.page - 1];+ if (!currentPage) {+ return;}++ // Wait for presentation mode to take effect+ setTimeout(function() {+ currentPage.scrollIntoView();+ }, 0);},/**@@ -3716,7 +2365,6 @@ var PDFView = {}};-var PageView = function pageView(container, id, scale,navigateTo, defaultViewport) {this.id = id;@@ -3724,17 +2372,14 @@ var PageView = function pageView(container, id, scale,this.rotation = 0;this.scale = scale || 1.0;this.viewport = defaultViewport;- this.pdfPageRotate = defaultViewport.rotation;+ this.pdfPageRotate = defaultViewport.rotate;this.renderingState = RenderingStates.INITIAL;this.resume = null;+ this.textContent = null;this.textLayer = null;- this.zoomLayer = null;-- this.annotationLayer = null;-var anchor = document.createElement('a');anchor.name = '' + this.id;@@ -3750,140 +2395,46 @@ var PageView = function pageView(container, id, scale,this.setPdfPage = function pageViewSetPdfPage(pdfPage) {this.pdfPage = pdfPage;this.pdfPageRotate = pdfPage.rotate;- var totalRotation = (this.rotation + this.pdfPageRotate) % 360;- this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);+ this.viewport = pdfPage.getViewport(this.scale);this.stats = pdfPage.stats;- this.reset();+ this.update();};this.destroy = function pageViewDestroy() {- this.zoomLayer = null;- this.reset();+ this.update();if (this.pdfPage) {this.pdfPage.destroy();}};- this.reset = function pageViewReset() {- if (this.renderTask) {- this.renderTask.cancel();- }- this.resume = null;- this.renderingState = RenderingStates.INITIAL;-- div.style.width = Math.floor(this.viewport.width) + 'px';- div.style.height = Math.floor(this.viewport.height) + 'px';-- var childNodes = div.childNodes;- for (var i = div.childNodes.length - 1; i >= 0; i--) {- var node = childNodes[i];- if (this.zoomLayer && this.zoomLayer === node) {- continue;- }- div.removeChild(node);- }- div.removeAttribute('data-loaded');-- this.annotationLayer = null;-- delete this.canvas;-- this.loadingIconDiv = document.createElement('div');- this.loadingIconDiv.className = 'loadingIcon';- div.appendChild(this.loadingIconDiv);- };-this.update = function pageViewUpdate(scale, rotation) {- this.scale = scale || this.scale;+ this.renderingState = RenderingStates.INITIAL;+ this.resume = null;if (typeof rotation !== 'undefined') {this.rotation = rotation;}- var totalRotation = (this.rotation + this.pdfPageRotate) % 360;- this.viewport = this.viewport.clone({- scale: this.scale * CSS_UNITS,- rotation: totalRotation- });-- if (USE_ONLY_CSS_ZOOM && this.canvas) {- this.cssTransform(this.canvas);- return;- } else if (this.canvas && !this.zoomLayer) {- this.zoomLayer = this.canvas.parentNode;- this.zoomLayer.style.position = 'absolute';- }- if (this.zoomLayer) {- this.cssTransform(this.zoomLayer.firstChild);- }- this.reset();- };-- this.cssTransform = function pageCssTransform(canvas) {- // Scale canvas, canvas wrapper, and page container.- var width = this.viewport.width;- var height = this.viewport.height;- canvas.style.width = canvas.parentNode.style.width = div.style.width =- Math.floor(width) + 'px';- canvas.style.height = canvas.parentNode.style.height = div.style.height =- Math.floor(height) + 'px';- // The canvas may have been originally rotated, so rotate relative to that.- var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;- var absRotation = Math.abs(relativeRotation);- var scaleX = 1, scaleY = 1;- if (absRotation === 90 || absRotation === 270) {- // Scale x and y because of the rotation.- scaleX = height / width;- scaleY = width / height;- }- var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +- 'scale(' + scaleX + ',' + scaleY + ')';- CustomStyle.setProp('transform', canvas, cssTransform);-- if (this.textLayer) {- // Rotating the text layer is more complicated since the divs inside the- // the text layer are rotated.- // TODO: This could probably be simplified by drawing the text layer in- // one orientation then rotating overall.- var textRelativeRotation = this.viewport.rotation -- this.textLayer.viewport.rotation;- var textAbsRotation = Math.abs(textRelativeRotation);- var scale = (width / canvas.width);- if (textAbsRotation === 90 || textAbsRotation === 270) {- scale = width / canvas.height;- }- var textLayerDiv = this.textLayer.textLayerDiv;- var transX, transY;- switch (textAbsRotation) {- case 0:- transX = transY = 0;- break;- case 90:- transX = 0;- transY = '-' + textLayerDiv.style.height;- break;- case 180:- transX = '-' + textLayerDiv.style.width;- transY = '-' + textLayerDiv.style.height;- break;- case 270:- transX = '-' + textLayerDiv.style.width;- transY = 0;- break;- default:- console.error('Bad rotation value.');- break;- }- CustomStyle.setProp('transform', textLayerDiv,- 'rotate(' + textAbsRotation + 'deg) ' +- 'scale(' + scale + ', ' + scale + ') ' +- 'translate(' + transX + ', ' + transY + ')');- CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');- }-- if (USE_ONLY_CSS_ZOOM && this.annotationLayer) {- setupAnnotations(div, this.pdfPage, this.viewport);- }+ this.scale = scale || this.scale;++ var totalRotation = (this.rotation + this.pdfPageRotate) % 360;+ this.viewport = this.viewport.clone({+ scale: this.scale,+ rotation: totalRotation+ });++ div.style.width = Math.floor(this.viewport.width) + 'px';+ div.style.height = Math.floor(this.viewport.height) + 'px';++ while (div.hasChildNodes())+ div.removeChild(div.lastChild);+ div.removeAttribute('data-loaded');++ delete this.canvas;++ this.loadingIconDiv = document.createElement('div');+ this.loadingIconDiv.className = 'loadingIcon';+ div.appendChild(this.loadingIconDiv);};Object.defineProperty(this, 'width', {@@ -3900,77 +2451,19 @@ var PageView = function pageView(container, id, scale,enumerable: true});- var self = this;-- function setupAnnotations(pageDiv, pdfPage, viewport) {+ function setupAnnotations(annotationsDiv, pdfPage, viewport) {function bindLink(link, dest) {link.href = PDFView.getDestinationHash(dest);link.onclick = function pageViewSetupLinksOnclick() {- if (dest) {+ if (dest)PDFView.navigateTo(dest);- }- return false;- };- if (dest) {- link.className = 'internalLink';- }- }-- function bindNamedAction(link, action) {- link.href = PDFView.getAnchorUrl('');- link.onclick = function pageViewSetupNamedActionOnClick() {- // See PDF reference, table 8.45 - Named action- switch (action) {- case 'GoToPage':- document.getElementById('pageNumber').focus();- break;-- case 'GoBack':- PDFHistory.back();- break;-- case 'GoForward':- PDFHistory.forward();- break;-- case 'Find':- if (!PDFView.supportsIntegratedFind) {- PDFFindBar.toggle();- }- break;-- case 'NextPage':- PDFView.page++;- break;-- case 'PrevPage':- PDFView.page--;- break;-- case 'LastPage':- PDFView.page = PDFView.pages.length;- break;-- case 'FirstPage':- PDFView.page = 1;- break;-- default:- break; // No action according to spec- }return false;};link.className = 'internalLink';}pdfPage.getAnnotations().then(function(annotationsData) {- if (self.annotationLayer) {- // If an annotationLayer already exists, delete it to avoid creating- // duplicate annotations when rapidly re-zooming the document.- pageDiv.removeChild(self.annotationLayer);- self.annotationLayer = null;- }viewport = viewport.clone({ dontFlip: true });for (var i = 0; i < annotationsData.length; i++) {var data = annotationsData[i];@@ -4002,20 +2495,10 @@ var PageView = function pageView(container, id, scale,CustomStyle.setProp('transformOrigin', element, transformOriginStr);if (data.subtype === 'Link' && !data.url) {- if (data.action) {- bindNamedAction(element, data.action);- } else {- bindLink(element, ('dest' in data) ? data.dest : null);- }+ bindLink(element, ('dest' in data) ? data.dest : null);}- if (!self.annotationLayer) {- var annotationLayerDiv = document.createElement('div');- annotationLayerDiv.className = 'annotationLayer';- pageDiv.appendChild(annotationLayerDiv);- self.annotationLayer = annotationLayerDiv;- }- self.annotationLayer.appendChild(element);+ annotationsDiv.appendChild(element);}});}@@ -4025,112 +2508,102 @@ var PageView = function pageView(container, id, scale,};this.scrollIntoView = function pageViewScrollIntoView(dest) {- if (PresentationMode.active) {- if (PDFView.page !== this.id) {- // Avoid breaking PDFView.getVisiblePages in presentation mode.- PDFView.page = this.id;+ if (!dest) {+ scrollIntoView(div);return;}- dest = null;- PDFView.setScale(PDFView.currentScaleValue, true, true);- }- if (!dest) {- scrollIntoView(div);- return;- }-- var x = 0, y = 0;- var width = 0, height = 0, widthScale, heightScale;- var changeOrientation = !!(this.rotation % 180);- var pageWidth = (changeOrientation ? this.height : this.width) /- this.scale / CSS_UNITS;- var pageHeight = (changeOrientation ? this.width : this.height) /- this.scale / CSS_UNITS;- var scale = 0;- switch (dest[1].name) {- case 'XYZ':- x = dest[2];- y = dest[3];- scale = dest[4];- // If x and/or y coordinates are not supplied, default to- // _top_ left of the page (not the obvious bottom left,- // since aligning the bottom of the intended page with the- // top of the window is rarely helpful).- x = x !== null ? x : 0;- y = y !== null ? y : pageHeight;- break;- case 'Fit':- case 'FitB':- scale = 'page-fit';- break;- case 'FitH':- case 'FitBH':- y = dest[2];- scale = 'page-width';- break;- case 'FitV':- case 'FitBV':- x = dest[2];- width = pageWidth;- height = pageHeight;- scale = 'page-height';- break;- case 'FitR':- x = dest[2];- y = dest[3];- width = dest[4] - x;- height = dest[5] - y;- widthScale = (PDFView.container.clientWidth - SCROLLBAR_PADDING) /- width / CSS_UNITS;- heightScale = (PDFView.container.clientHeight - SCROLLBAR_PADDING) /- height / CSS_UNITS;- scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));- break;- default:+ if (PDFView.isPresentationMode) { // Avoid breaking presentation mode.+ PDFView.page = id;return;- }+ }- if (scale && scale !== PDFView.currentScale) {- PDFView.setScale(scale, true, true);- } else if (PDFView.currentScale === UNKNOWN_SCALE) {- PDFView.setScale(DEFAULT_SCALE, true, true);- }+ var x = 0, y = 0;+ var width = 0, height = 0, widthScale, heightScale;+ var scale = 0;+ switch (dest[1].name) {+ case 'XYZ':+ x = dest[2];+ y = dest[3];+ scale = dest[4];+ // If x and/or y coordinates are not supplied, default to+ // _top_ left of the page (not the obvious bottom left,+ // since aligning the bottom of the intended page with the+ // top of the window is rarely helpful).+ x = x !== null ? x : 0;+ y = y !== null ? y : this.height / this.scale;+ break;+ case 'Fit':+ case 'FitB':+ scale = 'page-fit';+ break;+ case 'FitH':+ case 'FitBH':+ y = dest[2];+ scale = 'page-width';+ break;+ case 'FitV':+ case 'FitBV':+ x = dest[2];+ scale = 'page-height';+ break;+ case 'FitR':+ x = dest[2];+ y = dest[3];+ width = dest[4] - x;+ height = dest[5] - y;+ widthScale = (PDFView.container.clientWidth - SCROLLBAR_PADDING) /+ width / CSS_UNITS;+ heightScale = (PDFView.container.clientHeight - SCROLLBAR_PADDING) /+ height / CSS_UNITS;+ scale = Math.min(widthScale, heightScale);+ break;+ default:+ return;+ }- if (scale === 'page-fit' && !dest[4]) {- scrollIntoView(div);- return;- }+ if (scale && scale !== PDFView.currentScale) {+ PDFView.parseScale(scale, true, true);+ } else if (PDFView.currentScale === UNKNOWN_SCALE) {+ PDFView.parseScale(DEFAULT_SCALE, true, true);+ }- var boundingRect = [- this.viewport.convertToViewportPoint(x, y),- this.viewport.convertToViewportPoint(x + width, y + height)- ];- var left = Math.min(boundingRect[0][0], boundingRect[1][0]);- var top = Math.min(boundingRect[0][1], boundingRect[1][1]);+ if (scale === 'page-fit' && !dest[4]) {+ scrollIntoView(div);+ return;+ }- scrollIntoView(div, { left: left, top: top });+ var boundingRect = [+ this.viewport.convertToViewportPoint(x, y),+ this.viewport.convertToViewportPoint(x + width, y + height)+ ];+ setTimeout(function pageViewScrollIntoViewRelayout() {+ // letting page to re-layout before scrolling+ var scale = PDFView.currentScale;+ var x = Math.min(boundingRect[0][0], boundingRect[1][0]);+ var y = Math.min(boundingRect[0][1], boundingRect[1][1]);+ var width = Math.abs(boundingRect[0][0] - boundingRect[1][0]);+ var height = Math.abs(boundingRect[0][1] - boundingRect[1][1]);++ scrollIntoView(div, {left: x, top: y, width: width, height: height});+ }, 0);};this.getTextContent = function pageviewGetTextContent() {- return PDFView.getPage(this.id).then(function(pdfPage) {- return pdfPage.getTextContent();- });+ if (!this.textContent) {+ this.textContent = this.pdfPage.getTextContent();+ }+ return this.textContent;};this.draw = function pageviewDraw(callback) {var pdfPage = this.pdfPage;- if (this.pagePdfPromise) {- return;- }if (!pdfPage) {var promise = PDFView.getPage(this.id);promise.then(function(pdfPage) {- delete this.pagePdfPromise;this.setPdfPage(pdfPage);this.draw(callback);}.bind(this));- this.pagePdfPromise = promise;return;}@@ -4155,24 +2628,9 @@ var PageView = function pageView(container, id, scale,this.canvas = canvas;var scale = this.scale;- var ctx = canvas.getContext('2d');- var outputScale = getOutputScale(ctx);-- if (USE_ONLY_CSS_ZOOM) {- var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });- // Use a scale that will make the canvas be the original intended size- // of the page.- outputScale.sx *= actualSizeViewport.width / viewport.width;- outputScale.sy *= actualSizeViewport.height / viewport.height;- outputScale.scaled = true;- }-- canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;- canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;- canvas.style.width = Math.floor(viewport.width) + 'px';- canvas.style.height = Math.floor(viewport.height) + 'px';- // Add the viewport so it's known what it was originally drawn with.- canvas._viewport = viewport;+ var outputScale = getOutputScale();+ canvas.width = Math.floor(viewport.width) * outputScale.sx;+ canvas.height = Math.floor(viewport.height) * outputScale.sy;var textLayerDiv = null;if (!PDFJS.disableTextLayer) {@@ -4183,40 +2641,37 @@ var PageView = function pageView(container, id, scale,div.appendChild(textLayerDiv);}var textLayer = this.textLayer =- textLayerDiv ? new TextLayerBuilder({- textLayerDiv: textLayerDiv,- pageIndex: this.id - 1,- lastScrollSource: PDFView,- viewport: this.viewport,- isViewerInPresentationMode: PresentationMode.active- }) : null;+ textLayerDiv ? new TextLayerBuilder({+ textLayerDiv: textLayerDiv,+ pageIndex: this.id - 1,+ lastScrollSource: PDFView+ }) : null;++ if (outputScale.scaled) {+ var cssScale = 'scale(' + (1 / outputScale.sx) + ', ' ++ (1 / outputScale.sy) + ')';+ CustomStyle.setProp('transform' , canvas, cssScale);+ CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');+ if (textLayerDiv) {+ CustomStyle.setProp('transform' , textLayerDiv, cssScale);+ CustomStyle.setProp('transformOrigin' , textLayerDiv, '0% 0%');+ }+ }++ var ctx = canvas.getContext('2d');// TODO(mack): use data attributes to store thesectx._scaleX = outputScale.sx;ctx._scaleY = outputScale.sy;if (outputScale.scaled) {ctx.scale(outputScale.sx, outputScale.sy);}- if (outputScale.scaled && textLayerDiv) {- var cssScale = 'scale(' + (1 / outputScale.sx) + ', ' +- (1 / outputScale.sy) + ')';- CustomStyle.setProp('transform' , textLayerDiv, cssScale);- CustomStyle.setProp('transformOrigin' , textLayerDiv, '0% 0%');- textLayerDiv.dataset._scaleX = outputScale.sx;- textLayerDiv.dataset._scaleY = outputScale.sy;- }// Rendering areavar self = this;+ var renderingWasReset = false;function pageViewDrawCallback(error) {- // The renderTask may have been replaced by a new one, so only remove the- // reference to the renderTask if it matches the one that is triggering- // this callback.- if (renderTask === self.renderTask) {- self.renderTask = null;- }-- if (error === 'cancelled') {+ if (renderingWasReset) {return;}@@ -4227,11 +2682,6 @@ var PageView = function pageView(container, id, scale,delete self.loadingIconDiv;}- if (self.zoomLayer) {- div.removeChild(self.zoomLayer);- self.zoomLayer = null;- }-if (error) {PDFView.error(mozL10n.get('rendering_error', null,'An error occurred while rendering the page.'), error);@@ -4239,9 +2689,8 @@ var PageView = function pageView(container, id, scale,self.stats = pdfPage.stats;self.updateStats();- if (self.onAfterDraw) {+ if (self.onAfterDraw)self.onAfterDraw();- }cache.push(self);@@ -4259,6 +2708,12 @@ var PageView = function pageView(container, id, scale,viewport: this.viewport,textLayer: textLayer,continueCallback: function pdfViewcContinueCallback(cont) {+ if (self.renderingState === RenderingStates.INITIAL) {+ // The page update() was called, we just need to abort any rendering.+ renderingWasReset = true;+ return;+ }+if (PDFView.highestPriorityPage !== 'page' + self.id) {self.renderingState = RenderingStates.PAUSED;self.resume = function resumeCallback() {@@ -4270,9 +2725,7 @@ var PageView = function pageView(container, id, scale,cont();}};- var renderTask = this.renderTask = this.pdfPage.render(renderContext);-- this.renderTask.promise.then(+ this.pdfPage.render(renderContext).then(function pdfPageRenderCallback() {pageViewDrawCallback(null);},@@ -4300,7 +2753,7 @@ var PageView = function pageView(container, id, scale,// Use the same hack we use for high dpi displays for printing to get better// output until bug 811002 is fixed in FF.var PRINT_OUTPUT_SCALE = 2;- var canvas = document.createElement('canvas');+ var canvas = this.canvas = document.createElement('canvas');canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;canvas.style.width = (PRINT_OUTPUT_SCALE * viewport.width) + 'pt';@@ -4311,11 +2764,7 @@ var PageView = function pageView(container, id, scale,CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');var printContainer = document.getElementById('printContainer');- var canvasWrapper = document.createElement('div');- canvasWrapper.style.width = viewport.width + 'pt';- canvasWrapper.style.height = viewport.height + 'pt';- canvasWrapper.appendChild(canvas);- printContainer.appendChild(canvasWrapper);+ printContainer.appendChild(canvas);var self = this;canvas.mozPrintCallback = function(obj) {@@ -4332,7 +2781,7 @@ var PageView = function pageView(container, id, scale,viewport: viewport};- pdfPage.render(renderContext).promise.then(function() {+ pdfPage.render(renderContext).then(function() {// Tell the printEngine that rendering this canvas/page has finished.obj.done();self.pdfPage.destroy();@@ -4340,11 +2789,10 @@ var PageView = function pageView(container, id, scale,console.error(error);// Tell the printEngine that rendering this canvas/page has failed.// This will make the print proces stop.- if ('abort' in obj) {+ if ('abort' in obj)obj.abort();- } else {+ elseobj.done();- }self.pdfPage.destroy();});};@@ -4362,7 +2810,6 @@ var PageView = function pageView(container, id, scale,};};-var ThumbnailView = function thumbnailView(container, id, defaultViewport) {var anchor = document.createElement('a');anchor.href = PDFView.getAnchorUrl('#page=' + id);@@ -4372,9 +2819,10 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {return false;};+this.pdfPage = undefined;this.viewport = defaultViewport;- this.pdfPageRotate = defaultViewport.rotation;+ this.pdfPageRotate = defaultViewport.rotate;this.rotation = 0;this.pageWidth = this.viewport.width;@@ -4411,16 +2859,20 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {this.setPdfPage = function thumbnailViewSetPdfPage(pdfPage) {this.pdfPage = pdfPage;this.pdfPageRotate = pdfPage.rotate;- var totalRotation = (this.rotation + this.pdfPageRotate) % 360;- this.viewport = pdfPage.getViewport(1, totalRotation);+ this.viewport = pdfPage.getViewport(1);this.update();};- this.update = function thumbnailViewUpdate(rotation) {- if (rotation !== undefined) {- this.rotation = rotation;+ this.update = function thumbnailViewUpdate(rot) {+ if (!this.pdfPage) {+ return;}- var totalRotation = (this.rotation + this.pdfPageRotate) % 360;++ if (rot !== undefined) {+ this.rotation = rot;+ }++ var totalRotation = (this.rotation + this.pdfPage.rotate) % 360;this.viewport = this.viewport.clone({scale: 1,rotation: totalRotation@@ -4506,7 +2958,7 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {cont();}};- this.pdfPage.render(renderContext).promise.then(+ this.pdfPage.render(renderContext).then(function pdfPageRenderCallback() {self.renderingState = RenderingStates.FINISHED;callback();@@ -4520,17 +2972,8 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {};this.setImage = function thumbnailViewSetImage(img) {- if (!this.pdfPage) {- var promise = PDFView.getPage(this.id);- promise.then(function(pdfPage) {- this.setPdfPage(pdfPage);- this.setImage(img);- }.bind(this));- return;- }- if (this.hasImage || !img) {+ if (this.hasImage || !img)return;- }this.renderingState = RenderingStates.FINISHED;var ctx = this.getPageDrawContext();ctx.drawImage(img, 0, 0, img.width, img.height,@@ -4541,8 +2984,7 @@ var ThumbnailView = function thumbnailView(container, id, defaultViewport) {};-var FIND_SCROLL_OFFSET_TOP = -50;-var FIND_SCROLL_OFFSET_LEFT = -400;+/* globals CustomStyle, PDFFindController, scrollIntoView *//*** TextLayerBuilder provides text-selection@@ -4562,8 +3004,6 @@ var TextLayerBuilder = function textLayerBuilder(options) {this.pageIdx = options.pageIndex;this.matches = [];this.lastScrollSource = options.lastScrollSource;- this.viewport = options.viewport;- this.isViewerInPresentationMode = options.isViewerInPresentationMode;if(typeof PDFFindController === 'undefined') {window.PDFFindController = null;@@ -4584,7 +3024,10 @@ var TextLayerBuilder = function textLayerBuilder(options) {};this.renderLayer = function textLayerBuilderRenderLayer() {+ var self = this;var textDivs = this.textDivs;+ var bidiTexts = this.textContent.bidiTexts;+ var textLayerDiv = this.textLayerDiv;var canvas = document.createElement('canvas');var ctx = canvas.getContext('2d');@@ -4599,24 +3042,30 @@ var TextLayerBuilder = function textLayerBuilder(options) {if ('isWhitespace' in textDiv.dataset) {continue;}+ textLayerFrag.appendChild(textDiv);ctx.font = textDiv.style.fontSize + ' ' + textDiv.style.fontFamily;var width = ctx.measureText(textDiv.textContent).width;if (width > 0) {- textLayerFrag.appendChild(textDiv);var textScale = textDiv.dataset.canvasWidth / width;var rotation = textDiv.dataset.angle;var transform = 'scale(' + textScale + ', 1)';+ if (bidiTexts[i].dir === 'ttb') {+ rotation += 90;+ }transform = 'rotate(' + rotation + 'deg) ' + transform;CustomStyle.setProp('transform' , textDiv, transform);CustomStyle.setProp('transformOrigin' , textDiv, '0% 0%');++ textLayerDiv.appendChild(textDiv);}}- this.textLayerDiv.appendChild(textLayerFrag);this.renderingDone = true;this.updateMatches();++ textLayerDiv.appendChild(textLayerFrag);};this.setupRenderLayoutTimer = function textLayerSetupRenderLayoutTimer() {@@ -4651,10 +3100,8 @@ var TextLayerBuilder = function textLayerBuilder(options) {textDiv.style.fontSize = fontHeight + 'px';textDiv.style.fontFamily = geom.fontFamily;- var fontAscent = geom.ascent ? geom.ascent * fontHeight :- geom.descent ? (1 + geom.descent) * fontHeight : fontHeight;- textDiv.style.left = (geom.x + (fontAscent * Math.sin(geom.angle))) + 'px';- textDiv.style.top = (geom.y - (fontAscent * Math.cos(geom.angle))) + 'px';+ textDiv.style.left = (geom.x + (fontHeight * Math.sin(geom.angle))) + 'px';+ textDiv.style.top = (geom.y - (fontHeight * Math.cos(geom.angle))) + 'px';// The content of the div is set in the `setTextContent` function.@@ -4670,7 +3117,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {this.divContentDone = true;var textDivs = this.textDivs;- var bidiTexts = this.textContent;+ var bidiTexts = this.textContent.bidiTexts;for (var i = 0; i < bidiTexts.length; i++) {var bidiText = bidiTexts[i];@@ -4681,14 +3128,8 @@ var TextLayerBuilder = function textLayerBuilder(options) {}textDiv.textContent = bidiText.str;- // TODO refactor text layer to use text content position- /**- * var arr = this.viewport.convertToViewportPoint(bidiText.x, bidiText.y);- * textDiv.style.left = arr[0] + 'px';- * textDiv.style.top = arr[1] + 'px';- */// bidiText.dir may be 'ttb' for vertical texts.- textDiv.dir = bidiText.dir;+ textDiv.dir = bidiText.dir === 'rtl' ? 'rtl' : 'ltr';}this.setupRenderLayoutTimer();@@ -4702,7 +3143,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {this.convertMatches = function textLayerBuilderConvertMatches(matches) {var i = 0;var iIndex = 0;- var bidiTexts = this.textContent;+ var bidiTexts = this.textContent.bidiTexts;var end = bidiTexts.length - 1;var queryLen = PDFFindController === null ?0 : PDFFindController.state.query.length;@@ -4761,7 +3202,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {return;}- var bidiTexts = this.textContent;+ var bidiTexts = this.textContent.bidiTexts;var textDivs = this.textDivs;var prevEnd = null;var isSelectedPage = PDFFindController === null ?@@ -4834,10 +3275,8 @@ var TextLayerBuilder = function textLayerBuilder(options) {var isSelected = isSelectedPage && i === selectedMatchIdx;var highlightSuffix = (isSelected ? ' selected' : '');- if (isSelected && !this.isViewerInPresentationMode) {- scrollIntoView(textDivs[begin.divIdx], { top: FIND_SCROLL_OFFSET_TOP,- left: FIND_SCROLL_OFFSET_LEFT });- }+ if (isSelected)+ scrollIntoView(textDivs[begin.divIdx], {top: -50});// Match inside new div.if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {@@ -4876,7 +3315,7 @@ var TextLayerBuilder = function textLayerBuilder(options) {// Clear out all matches.var matches = this.matches;var textDivs = this.textDivs;- var bidiTexts = this.textContent;+ var bidiTexts = this.textContent.bidiTexts;var clearedUntilDivIdx = -1;// Clear out all current matches.@@ -4953,23 +3392,14 @@ var DocumentOutlineView = function documentOutlineView(outline) {}};--function webViewerLoad(evt) {+document.addEventListener('DOMContentLoaded', function webViewerLoad(evt) {PDFView.initialize();-var params = PDFView.parseQueryString(document.location.search.substring(1));- var file = 'file' in params ? params.file : DEFAULT_URL;- var fileInput = document.createElement('input');- fileInput.id = 'fileInput';- fileInput.className = 'fileInput';- fileInput.setAttribute('type', 'file');- fileInput.oncontextmenu = noContextMenuHandler;- document.body.appendChild(fileInput);+ var file = params.file || DEFAULT_URL;if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {document.getElementById('openFile').setAttribute('hidden', 'true');- document.getElementById('secondaryOpenFile').setAttribute('hidden', 'true');} else {document.getElementById('fileInput').value = null;}@@ -4998,20 +3428,7 @@ function webViewerLoad(evt) {PDFJS.disableHistory = (hashParams['disableHistory'] === 'true');}- if ('useOnlyCssZoom' in hashParams) {- USE_ONLY_CSS_ZOOM = (hashParams['useOnlyCssZoom'] === 'true');- }-- if ('verbosity' in hashParams) {- PDFJS.verbosity = hashParams['verbosity'] | 0;- }-- if ('ignoreCurrentPositionOnZoom' in hashParams) {- IGNORE_CURRENT_POSITION_ON_ZOOM =- (hashParams['ignoreCurrentPositionOnZoom'] === 'true');- }-- var locale = PDFJS.locale || navigator.language;+ var locale = navigator.language;if ('locale' in hashParams)locale = hashParams['locale'];mozL10n.setLanguage(locale);@@ -5040,24 +3457,23 @@ function webViewerLoad(evt) {if (!PDFView.supportsPrinting) {document.getElementById('print').classList.add('hidden');- document.getElementById('secondaryPrint').classList.add('hidden');}if (!PDFView.supportsFullscreen) {document.getElementById('presentationMode').classList.add('hidden');- document.getElementById('secondaryPresentationMode').- classList.add('hidden');}if (PDFView.supportsIntegratedFind) {document.getElementById('viewFind').classList.add('hidden');}- // Listen for unsuporrted features to trigger the fallback UI.- PDFJS.UnsupportedManager.listen(PDFView.fallback.bind(PDFView));-- // Suppress context menus for some controls- document.getElementById('scaleSelect').oncontextmenu = noContextMenuHandler;+ // Listen for warnings to trigger the fallback UI. Errors should be caught+ // and call PDFView.error() so we don't need to listen for those.+ PDFJS.LogManager.addLogger({+ warn: function() {+ PDFView.fallback();+ }+ });var mainContainer = document.getElementById('mainContainer');var outerContainer = document.getElementById('outerContainer');@@ -5109,6 +3525,26 @@ function webViewerLoad(evt) {PDFView.zoomOut();});+ document.getElementById('presentationMode').addEventListener('click',+ function() {+ PDFView.presentationMode();+ });++ document.getElementById('openFile').addEventListener('click',+ function() {+ document.getElementById('fileInput').click();+ });++ document.getElementById('print').addEventListener('click',+ function() {+ window.print();+ });++ document.getElementById('download').addEventListener('click',+ function() {+ PDFView.download();+ });+document.getElementById('pageNumber').addEventListener('click',function() {this.select();@@ -5126,29 +3562,32 @@ function webViewerLoad(evt) {document.getElementById('scaleSelect').addEventListener('change',function() {- PDFView.setScale(this.value);+ PDFView.parseScale(this.value);});- document.getElementById('presentationMode').addEventListener('click',- SecondaryToolbar.presentationModeClick.bind(SecondaryToolbar));-- document.getElementById('openFile').addEventListener('click',- SecondaryToolbar.openFileClick.bind(SecondaryToolbar));-- document.getElementById('print').addEventListener('click',- SecondaryToolbar.printClick.bind(SecondaryToolbar));+ document.getElementById('firstPage').addEventListener('click',+ function() {+ PDFView.page = 1;+ });- document.getElementById('download').addEventListener('click',- SecondaryToolbar.downloadClick.bind(SecondaryToolbar));+ document.getElementById('lastPage').addEventListener('click',+ function() {+ PDFView.page = PDFView.pdfDocument.numPages;+ });+ document.getElementById('pageRotateCcw').addEventListener('click',+ function() {+ PDFView.rotatePages(-90);+ });- if (file) {- PDFView.open(file, 0);- }+ document.getElementById('pageRotateCw').addEventListener('click',+ function() {+ PDFView.rotatePages(90);+ });-}-document.addEventListener('DOMContentLoaded', webViewerLoad, true);+ PDFView.open(file, 0);+}, true);function updateViewarea() {@@ -5182,7 +3621,7 @@ function updateViewarea() {currentId = visiblePages[0].id;}- if (!PresentationMode.active) {+ if (!PDFView.isPresentationMode) {updateViewarea.inProgress = true; // used in "set page"PDFView.page = currentId;updateViewarea.inProgress = false;@@ -5190,37 +3629,27 @@ function updateViewarea() {var currentScale = PDFView.currentScale;var currentScaleValue = PDFView.currentScaleValue;- var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ?- Math.round(currentScale * 10000) / 100 : currentScaleValue;+ var normalizedScaleValue = currentScaleValue == currentScale ?+ currentScale * 100 : currentScaleValue;var pageNumber = firstPage.id;var pdfOpenParams = '#page=' + pageNumber;pdfOpenParams += '&zoom=' + normalizedScaleValue;var currentPage = PDFView.pages[pageNumber - 1];- var container = PDFView.container;- var topLeft = currentPage.getPagePoint((container.scrollLeft - firstPage.x),- (container.scrollTop - firstPage.y));- var intLeft = Math.round(topLeft[0]);- var intTop = Math.round(topLeft[1]);- pdfOpenParams += ',' + intLeft + ',' + intTop;-- if (PresentationMode.active || PresentationMode.switchInProgress) {- PDFView.currentPosition = null;- } else {- PDFView.currentPosition = { page: pageNumber, left: intLeft, top: intTop };- }+ var topLeft = currentPage.getPagePoint(PDFView.container.scrollLeft,+ (PDFView.container.scrollTop - firstPage.y));+ pdfOpenParams += ',' + Math.round(topLeft[0]) + ',' + Math.round(topLeft[1]);var store = PDFView.store;store.initializedPromise.then(function() {store.set('exists', true);store.set('page', pageNumber);store.set('zoom', normalizedScaleValue);- store.set('scrollLeft', intLeft);- store.set('scrollTop', intTop);+ store.set('scrollLeft', Math.round(topLeft[0]));+ store.set('scrollTop', Math.round(topLeft[1]));});var href = PDFView.getAnchorUrl(pdfOpenParams);document.getElementById('viewBookmark').href = href;- document.getElementById('secondaryViewBookmark').href = href;// Update the current bookmark in the browsing history.PDFHistory.updateCurrentBookmark(pdfOpenParams, pageNumber);@@ -5229,14 +3658,10 @@ function updateViewarea() {window.addEventListener('resize', function webViewerResize(evt) {if (PDFView.initialized &&(document.getElementById('pageWidthOption').selected ||- document.getElementById('pageFitOption').selected ||- document.getElementById('pageAutoOption').selected)) {- PDFView.setScale(document.getElementById('scaleSelect').value);- }+ document.getElementById('pageFitOption').selected ||+ document.getElementById('pageAutoOption').selected))+ PDFView.parseScale(document.getElementById('scaleSelect').value);updateViewarea();-- // Set the 'max-height' CSS property of the secondary toolbar.- SecondaryToolbar.setMaxHeight(PDFView.container);});window.addEventListener('hashchange', function webViewerHashchange(evt) {@@ -5250,30 +3675,21 @@ window.addEventListener('change', function webViewerChange(evt) {if (!files || files.length === 0)return;- var file = files[0];-- if (!PDFJS.disableCreateObjectURL &&- typeof URL !== 'undefined' && URL.createObjectURL) {- PDFView.open(URL.createObjectURL(file), 0);- } else {- // Read the local file into a Uint8Array.- var fileReader = new FileReader();- fileReader.onload = function webViewerChangeFileReaderOnload(evt) {- var buffer = evt.target.result;- var uint8Array = new Uint8Array(buffer);- PDFView.open(uint8Array, 0);- };- fileReader.readAsArrayBuffer(file);- }+ // Read the local file into a Uint8Array.+ var fileReader = new FileReader();+ fileReader.onload = function webViewerChangeFileReaderOnload(evt) {+ var buffer = evt.target.result;+ var uint8Array = new Uint8Array(buffer);+ PDFView.open(uint8Array, 0);+ };+ var file = files[0];+ fileReader.readAsArrayBuffer(file);PDFView.setTitleUsingUrl(file.name);// URL does not reflect proper document location - hiding some icons.document.getElementById('viewBookmark').setAttribute('hidden', 'true');- document.getElementById('secondaryViewBookmark').- setAttribute('hidden', 'true');document.getElementById('download').setAttribute('hidden', 'true');- document.getElementById('secondaryDownload').setAttribute('hidden', 'true');}, true);function selectScaleOption(value) {@@ -5294,10 +3710,10 @@ function selectScaleOption(value) {window.addEventListener('localized', function localized(evt) {document.getElementsByTagName('html')[0].dir = mozL10n.getDirection();+ // Adjust the width of the zoom box to fit the content.+ // Note: This is only done if the zoom box is actually visible,+ // since otherwise element.clientWidth will return 0.PDFView.animationStartedPromise.then(function() {- // Adjust the width of the zoom box to fit the content.- // Note: This is only done if the zoom box is actually visible,- // since otherwise element.clientWidth will return 0.var container = document.getElementById('scaleSelectContainer');if (container.clientWidth > 0) {var select = document.getElementById('scaleSelect');@@ -5308,9 +3724,6 @@ window.addEventListener('localized', function localized(evt) {container.setAttribute('style', 'min-width: ' + width + 'px; ' +'max-width: ' + width + 'px;');}-- // Set the 'max-height' CSS property of the secondary toolbar.- SecondaryToolbar.setMaxHeight(PDFView.container);});}, true);@@ -5322,11 +3735,11 @@ window.addEventListener('scalechange', function scalechange(evt) {customScaleOption.selected = false;if (!evt.resetAutoSettings &&- (document.getElementById('pageWidthOption').selected ||- document.getElementById('pageFitOption').selected ||- document.getElementById('pageAutoOption').selected)) {- updateViewarea();- return;+ (document.getElementById('pageWidthOption').selected ||+ document.getElementById('pageFitOption').selected ||+ document.getElementById('pageAutoOption').selected)) {+ updateViewarea();+ return;}var predefinedValueFound = selectScaleOption('' + evt.scale);@@ -5342,62 +3755,73 @@ window.addEventListener('pagechange', function pagechange(evt) {if (PDFView.previousPageNumber !== page) {document.getElementById('pageNumber').value = page;var selected = document.querySelector('.thumbnail.selected');- if (selected) {+ if (selected)selected.classList.remove('selected');- }var thumbnail = document.getElementById('thumbnailContainer' + page);thumbnail.classList.add('selected');var visibleThumbs = PDFView.getVisibleThumbs();var numVisibleThumbs = visibleThumbs.views.length;-- // If the thumbnail isn't currently visible, scroll it into view.+ // If the thumbnail isn't currently visible scroll it into view.if (numVisibleThumbs > 0) {var first = visibleThumbs.first.id;// Account for only one thumbnail being visible.- var last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);- if (page <= first || page >= last) {- scrollIntoView(thumbnail, { top: THUMBNAIL_SCROLL_MARGIN });- }+ var last = numVisibleThumbs > 1 ?+ visibleThumbs.last.id : first;+ if (page <= first || page >= last)+ scrollIntoView(thumbnail);}+}document.getElementById('previous').disabled = (page <= 1);document.getElementById('next').disabled = (page >= PDFView.pages.length);}, true);-function handleMouseWheel(evt) {- var MOUSE_WHEEL_DELTA_FACTOR = 40;- var ticks = (evt.type === 'DOMMouseScroll') ? -evt.detail :- evt.wheelDelta / MOUSE_WHEEL_DELTA_FACTOR;- var direction = (ticks < 0) ? 'zoomOut' : 'zoomIn';-- if (evt.ctrlKey) { // Only zoom the pages, not the entire viewer+// Firefox specific event, so that we can prevent browser from zooming+window.addEventListener('DOMMouseScroll', function(evt) {+ if (evt.ctrlKey) {evt.preventDefault();- PDFView[direction](Math.abs(ticks));- } else if (PresentationMode.active) {- PDFView.mouseScroll(ticks * MOUSE_WHEEL_DELTA_FACTOR);++ var ticks = evt.detail;+ var direction = (ticks > 0) ? 'zoomOut' : 'zoomIn';+ for (var i = 0, length = Math.abs(ticks); i < length; i++)+ PDFView[direction]();+ } else if (PDFView.isPresentationMode) {+ var FIREFOX_DELTA_FACTOR = -40;+ PDFView.mouseScroll(evt.detail * FIREFOX_DELTA_FACTOR);}-}+}, false);++window.addEventListener('mousemove', function mousemove(evt) {+ if (PDFView.isPresentationMode) {+ PDFView.showPresentationControls();+ }+}, false);-window.addEventListener('DOMMouseScroll', handleMouseWheel);-window.addEventListener('mousewheel', handleMouseWheel);+window.addEventListener('mousedown', function mousedown(evt) {+ if (PDFView.isPresentationMode && evt.button === 0) {+ // Enable clicking of links in presentation mode.+ // Note: Only links that point to the currently loaded PDF document works.+ var targetHref = evt.target.href;+ var internalLink = targetHref && (targetHref.replace(/#.*$/, '') ===+ window.location.href.replace(/#.*$/, ''));+ if (!internalLink) {+ // Unless an internal link was clicked, advance a page in presentation+ // mode.+ evt.preventDefault();+ PDFView.page++;+ }+ }+}, false);window.addEventListener('click', function click(evt) {- if (!PresentationMode.active) {- if (SecondaryToolbar.opened && PDFView.container.contains(evt.target)) {- SecondaryToolbar.close();- }- } else if (evt.button === 0) {+ if (PDFView.isPresentationMode && evt.button === 0) {// Necessary since preventDefault() in 'mousedown' won't stop- // the event propagation in all circumstances in presentation mode.+ // the event propagation in all circumstances.evt.preventDefault();}}, false);window.addEventListener('keydown', function keydown(evt) {- if (PasswordPrompt.visible) {- return;- }-var handled = false;var cmd = (evt.ctrlKey ? 1 : 0) |(evt.altKey ? 2 : 0) |@@ -5409,15 +3833,9 @@ window.addEventListener('keydown', function keydown(evt) {if (cmd === 1 || cmd === 8 || cmd === 5 || cmd === 12) {// either CTRL or META key with optional SHIFT.switch (evt.keyCode) {- case 70: // f- if (!PDFView.supportsIntegratedFind) {- PDFFindBar.open();- handled = true;- }- break;- case 71: // g+ case 70:if (!PDFView.supportsIntegratedFind) {- PDFFindBar.dispatchEvent('again', cmd === 5 || cmd === 12);+ PDFFindBar.toggle();handled = true;}break;@@ -5436,37 +3854,20 @@ window.addEventListener('keydown', function keydown(evt) {break;case 48: // '0'case 96: // '0' on Numpad of Swedish keyboard- // keeping it unhandled (to restore page zoom to 100%)- setTimeout(function () {- // ... and resetting the scale after browser adjusts its scale- PDFView.setScale(DEFAULT_SCALE, true);- });- handled = false;- break;- }- }-- // CTRL or META without shift- if (cmd === 1 || cmd === 8) {- switch (evt.keyCode) {- case 83: // s- PDFView.download();- handled = true;+ PDFView.parseScale(DEFAULT_SCALE, true);+ handled = false; // keeping it unhandled (to restore page zoom to 100%)break;}}- // CTRL+ALT or Option+Command- if (cmd === 3 || cmd === 10) {+ // CTRL or META with or without SHIFT.+ if (cmd == 1 || cmd == 8 || cmd == 5 || cmd == 12) {switch (evt.keyCode) {- case 80: // p- SecondaryToolbar.presentationModeClick();- handled = true;- break;case 71: // g- // focuses input#pageNumber field- document.getElementById('pageNumber').select();- handled = true;+ if (!PDFView.supportsIntegratedFind) {+ PDFFindBar.dispatchEvent('again', cmd == 5 || cmd == 12);+ handled = true;+ }break;}}@@ -5479,14 +3880,15 @@ window.addEventListener('keydown', function keydown(evt) {// Some shortcuts should not get handled if a control/input element// is selected.var curElement = document.activeElement || document.querySelector(':focus');- var curElementTagName = curElement && curElement.tagName.toUpperCase();- if (curElementTagName === 'INPUT' ||- curElementTagName === 'TEXTAREA' ||- curElementTagName === 'SELECT') {- // Make sure that the secondary toolbar is closed when Escape is pressed.- if (evt.keyCode !== 27) { // 'Esc'- return;- }+ if (curElement && (curElement.tagName.toUpperCase() === 'INPUT' ||+ curElement.tagName.toUpperCase() === 'SELECT')) {+ return;+ }+ var controlsElement = document.getElementById('toolbar');+ while (curElement) {+ if (curElement === controlsElement && !PDFView.isPresentationMode)+ return; // ignoring if the 'toolbar' element is focused+ curElement = curElement.parentNode;}if (cmd === 0) { // no control key pressed at all.@@ -5494,7 +3896,7 @@ window.addEventListener('keydown', function keydown(evt) {case 38: // up arrowcase 33: // pg upcase 8: // backspace- if (!PresentationMode.active &&+ if (!PDFView.isPresentationMode &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -5512,10 +3914,6 @@ window.addEventListener('keydown', function keydown(evt) {handled = true;break;case 27: // esc key- if (SecondaryToolbar.opened) {- SecondaryToolbar.close();- handled = true;- }if (!PDFView.supportsIntegratedFind && PDFFindBar.opened) {PDFFindBar.close();handled = true;@@ -5524,7 +3922,7 @@ window.addEventListener('keydown', function keydown(evt) {case 40: // down arrowcase 34: // pg downcase 32: // spacebar- if (!PresentationMode.active &&+ if (!PDFView.isPresentationMode &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -5542,50 +3940,28 @@ window.addEventListener('keydown', function keydown(evt) {break;case 36: // home- if (PresentationMode.active) {+ if (PDFView.isPresentationMode) {PDFView.page = 1;handled = true;}break;case 35: // end- if (PresentationMode.active) {+ if (PDFView.isPresentationMode) {PDFView.page = PDFView.pdfDocument.numPages;handled = true;}break;- case 72: // 'h'- if (!PresentationMode.active) {- HandTool.toggle();- }- break;case 82: // 'r'PDFView.rotatePages(90);break;}- if (!handled && !PresentationMode.active) {- // 33=Page Up 34=Page Down 35=End 36=Home- // 37=Left 38=Up 39=Right 40=Down- if (evt.keyCode >= 33 && evt.keyCode <= 40 &&- !PDFView.container.contains(curElement)) {- // The page container is not focused, but a page navigation key has been- // pressed. Change the focus to the viewer container to make sure that- // navigation by keyboard works as expected.- PDFView.container.focus();- }- // 32=Spacebar- if (evt.keyCode === 32 && curElementTagName !== 'BUTTON') {- if (!PDFView.container.contains(curElement)) {- PDFView.container.focus();- }- }- }}if (cmd === 4) { // shift-keyswitch (evt.keyCode) {case 32: // spacebar- if (!PresentationMode.active &&+ if (!PDFView.isPresentationMode &&PDFView.currentScaleValue !== 'page-fit') {break;}@@ -5602,13 +3978,13 @@ window.addEventListener('keydown', function keydown(evt) {if (cmd === 2) { // alt-keyswitch (evt.keyCode) {case 37: // left arrow- if (PresentationMode.active) {+ if (PDFView.isPresentationMode) {PDFHistory.back();handled = true;}break;case 39: // right arrow- if (PresentationMode.active) {+ if (PDFView.isPresentationMode) {PDFHistory.forward();handled = true;}@@ -5630,6 +4006,25 @@ window.addEventListener('afterprint', function afterPrint(evt) {PDFView.afterPrint();});+(function presentationModeClosure() {+ function presentationModeChange(e) {+ var isPresentationMode = document.fullscreenElement ||+ document.mozFullScreen ||+ document.webkitIsFullScreen;++ if (isPresentationMode) {+ PDFView.enterPresentationMode();+ } else {+ PDFView.exitPresentationMode();+ }+ }++ window.addEventListener('fullscreenchange', presentationModeChange, false);+ window.addEventListener('mozfullscreenchange', presentationModeChange, false);+ window.addEventListener('webkitfullscreenchange', presentationModeChange,+ false);+})();+(function animationStartedClosure() {// The offsetParent is not set until the pdf.js iframe or object is visible.// Waiting for first animation.@@ -5639,10 +4034,9 @@ window.addEventListener('afterprint', function afterPrint(evt) {window.oRequestAnimationFrame ||window.msRequestAnimationFrame ||function startAtOnce(callback) { callback(); };- PDFView.animationStartedPromise = new Promise(function (resolve) {- requestAnimationFrame(function onAnimationFrame() {- resolve();- });+ PDFView.animationStartedPromise = new PDFJS.Promise();+ requestAnimationFrame(function onAnimationFrame() {+ PDFView.animationStartedPromise.resolve();});})();